def postproc_blueprints(netlist): for schematic in netlist.schematics: schematic.ports = {} for component in schematic.components: portname = component.get_attribute('portname', None) if portname is None: continue if component.refdes is not None: component.error(_("refdes= and portname= attributes " "are mutually exclusive")) if xorn.geda.attrib.search_all(component.ob, 'net'): component.error(_("portname= and net= attributes " "are mutually exclusive")) if not component.pins: component.error(_("I/O symbol doesn't have pins")) if len(component.pins) > 1: component.error(_("multiple pins on I/O symbol")) for pin in component.pins: if pin.number is not None or pin.ob.attached_objects(): pin.warn(_("pin attributes on I/O symbol are ignored")) try: ports = schematic.ports[portname] except KeyError: ports = schematic.ports[portname] = [] ports.append(component) component.has_portname_attrib = True
def warning(self): # apturl minver matches if not self.pkg_state == PkgStates.INSTALLED: if self._app.request: minver_matches = re.findall(r'minver=[a-z,0-9,-,+,.,~]*', self._app.request) if minver_matches and self.version: minver = minver_matches[0][7:] from softwarecenter.utils import version_compare if version_compare(minver, self.version) > 0: return _("Version %s or later not available.") % minver # can we enable a source if not self._pkg: source_to_enable = None if self.channelname and self._unavailable_channel(): source_to_enable = self.channelname elif (self.component and self.component not in ("independent", "commercial")): source_to_enable = self.component if source_to_enable: sources = source_to_enable.split('&') sources_length = len(sources) if sources_length == 1: warning = (_("Available from the \"%s\" source.") % sources[0]) elif sources_length > 1: # Translators: the visible string is constructed # concatenating the following 3 strings like this: # Available from the following sources: %s, ... %s, %s. warning = _("Available from the following sources: ") # Cycle through all, but the last for source in sources[:-1]: warning += _("\"%s\", ") % source warning += _("\"%s\".") % sources[sources_length - 1] return warning
def setup_command(self, session): # FIXME: Implement and add more potential sources of e-mails macmail_emails = self._testing_data(self._get_macmail_emails, ['1']) tbird_emails = self._testing_data(self._get_tbird_emails, ['1']) gnupg_emails = self._testing_data(self._get_gnupg_emails, [ { 'name': 'Innocent Adventurer', 'address': '*****@*****.**', 'source': 'The Youtubes' }, { 'name': 'Chelsea Manning', 'address': '*****@*****.**', 'source': 'Internal Tribute Store' }, { 'name': 'MUSCULAR', 'address': '*****@*****.**', 'source': 'Well funded adversaries' } ]) emails = macmail_emails + tbird_emails + gnupg_emails if not emails: return self._error(_('No e-mail addresses found')) else: return self._success(_('Discovered e-mail addresses'), { 'emails': emails })
def start (self): if len (self.errors) == 0: e = operations.FinishedEvent (self, operations.SUCCESSFUL) for l in self.listeners: l.on_finished (e) return elif len (self.errors) > 1: title = _("Unsupported file types") else: title = _("Unsupported file type") filenames = [] for e in self.errors: filenames.append (gnomevfs.URI(e.hints['location']).short_name) del self.__errors if len (filenames) == 1: msg = _("The following files were not added:") + "\n" else: msg = _("The following files were not added:") + "\n" msg += " " + filenames[0] for f in filenames[1:]: msg += ", " + f gtkutil.dialog_error (title, msg, self.parent) e = operations.FinishedEvent (self, operations.SUCCESSFUL) for l in self.listeners: l.on_finished (e)
def __init__(self, *args, **kwargs): super(_StuckStrip, self).__init__(*args, **kwargs) self.orientation = Gtk.Orientation.HORIZONTAL spacer1 = Gtk.Label(label='') self.pack_start(spacer1, True, True, 0) spacer2 = Gtk.Label(label='') self.pack_end(spacer2, expand=True, fill=False, padding=0) self.set_spacing(10) self.set_border_width(10) label = Gtk.Label(label=_("Stuck? You can still solve the puzzle.")) self.pack_start(label, False, True, 0) icon = Icon() icon.set_from_icon_name('edit-undo', Gtk.IconSize.LARGE_TOOLBAR) self.button = Gtk.Button(stock=Gtk.STOCK_UNDO) self.button.set_image(icon) self.button.set_label(_("Undo some moves")) self.pack_end(self.button, expand=False, fill=False, padding=0) def callback(source): self.emit('undo-clicked') self.button.connect('clicked', callback)
def render_web(self, cfg, tpl_names, data): """Render data as HTML""" alldata = default_dict(self.html_variables) alldata["config"] = cfg alldata.update(data) try: template = self._web_template(cfg, tpl_names) if template: return template.render(alldata) else: emsg = _("<h1>Template not found</h1>\n<p>%s</p><p>" "<b>DATA:</b> %s</p>") tpl_esc_names = [escape_html(tn) for tn in tpl_names] return emsg % (' or '.join(tpl_esc_names), escape_html('%s' % alldata)) except (UndefinedError, ): emsg = _("<h1>Template error</h1>\n" "<pre>%s</pre>\n<p>%s</p><p><b>DATA:</b> %s</p>") return emsg % (escape_html(traceback.format_exc()), ' or '.join([escape_html(tn) for tn in tpl_names]), escape_html('%.4096s' % alldata)) except (TemplateNotFound, TemplatesNotFound), e: emsg = _("<h1>Template not found in %s</h1>\n" "<b>%s</b><br/>" "<div><hr><p><b>DATA:</b> %s</p></div>") return emsg % tuple([escape_html(unicode(v)) for v in (e.name, e.message, '%.4096s' % alldata)])
def __accept_clicked_cb(self, widget): if self._section_view.needs_restart: self._section_toolbar.accept_button.set_sensitive(False) self._section_toolbar.cancel_button.set_sensitive(False) alert = Alert() alert.props.title = _('Warning') alert.props.msg = _('Changes require restart') icon = Icon(icon_name='dialog-cancel') alert.add_button(Gtk.ResponseType.CANCEL, _('Cancel changes'), icon) icon.show() if self._current_option != 'aboutme': icon = Icon(icon_name='dialog-ok') alert.add_button(Gtk.ResponseType.ACCEPT, _('Later'), icon) icon.show() icon = Icon(icon_name='system-restart') alert.add_button(Gtk.ResponseType.APPLY, _('Restart now'), icon) icon.show() self._vbox.pack_start(alert, False, False, 0) self._vbox.reorder_child(alert, 2) alert.connect('response', self.__response_cb) alert.show() else: self._show_main_view()
def command(self): session, config = self.session, self.session.config handle, lines = self.args[0], self.args[1:] vcard = config.vcards.get_vcard(handle) if not vcard: return self._error('%s not found: %s' % (self.VCARD, handle)) config.vcards.deindex_vcard(vcard) try: for l in lines: if '=' in l[:5]: ln, l = l.split('=', 1) vcard.set_line(int(ln.strip()), VCardLine(l.strip())) else: vcard.add(VCardLine(l)) vcard.save() return self._success(_("Added %d lines") % len(lines), result=self._vcard_list([vcard], simplify=True, info={ 'updated': handle, 'added': len(lines) })) except KeyboardInterrupt: raise except: config.vcards.index_vcard(vcard) self._ignore_exception() return self._error(_('Error adding lines to %s') % handle) finally: config.vcards.index_vcard(vcard)
def command(self, format, terms=None, **kwargs): session, config = self.session, self.session.config if not format in PluginManager.CONTACT_IMPORTERS.keys(): session.ui.error("No such import format") return False importer = PluginManager.CONTACT_IMPORTERS[format] if not all([x in kwargs.keys() for x in importer.required_parameters]): session.ui.error( _("Required paramter missing. Required parameters " "are: %s") % ", ".join(importer.required_parameters)) return False allparams = importer.required_parameters + importer.optional_parameters if not all([x in allparams for x in kwargs.keys()]): session.ui.error( _("Unknown parameter passed to importer. " "Provided %s; but known parameters are: %s" ) % (", ".join(kwargs), ", ".join(allparams))) return False imp = importer(kwargs) if terms: contacts = imp.filter_contacts(terms) else: contacts = imp.get_contacts() for importedcontact in contacts: # Check if contact exists. If yes, then update. Else create. pass
def _getFilesizeEstimate(self): """Estimates the final file size. Estimates in megabytes (over 30 MB) are rounded to the nearest 10 MB to smooth out small variations. You'd be surprised how imprecision can improve perceived accuracy. Returns: str: A human-readable (ex: "14 MB") estimate for the file size. """ if not self.current_position or self.current_position == 0: return None current_filesize = os.stat(path_from_uri(self.outfile)).st_size length = self.project.ges_timeline.props.duration estimated_size = float( current_filesize * float(length) / self.current_position) # Now let's make it human-readable (instead of octets). # If it's in the giga range (10⁹) instead of mega (10⁶), use 2 decimals if estimated_size > 10e8: gigabytes = estimated_size / (10 ** 9) return _("%.2f GB" % gigabytes) else: megabytes = int(estimated_size / (10 ** 6)) if megabytes > 30: megabytes = int(round(megabytes, -1)) # -1 means round to 10 return _("%d MB" % megabytes)
def _apply_changes(request, old_status, new_status): """Apply the changes""" modified = False if old_status['enabled'] != new_status['enabled']: sub_command = 'enable' if new_status['enabled'] else 'disable' actions.superuser_run('transmission', [sub_command]) transmission.service.notify_enabled(None, new_status['enabled']) modified = True if old_status['download_dir'] != new_status['download_dir'] or \ old_status['rpc_username'] != new_status['rpc_username'] or \ old_status['rpc_password'] != new_status['rpc_password']: new_configuration = { 'download-dir': new_status['download_dir'], 'rpc-username': new_status['rpc_username'], 'rpc-password': new_status['rpc_password'], } actions.superuser_run('transmission', ['merge-configuration', json.dumps(new_configuration)]) modified = True if modified: messages.success(request, _('Configuration updated')) else: messages.info(request, _('Setting unchanged'))
def setup_parser(self): self.parser.add_option('--org', dest='org', help=_("organization name (required)")) self.parser.add_option('--name', dest='name', help=_("filter name (required)")) self.parser.add_option('--package', dest='package_id', help=_("package id (required)"))
def _download_manifest(self): """ Download the manifest file, and process it to return an ISOManifest. :return: manifest of available ISOs :rtype: pulp_rpm.plugins.db.models.ISOManifest """ manifest_url = urljoin(self._repo_url, models.ISOManifest.FILENAME) # I probably should have called this manifest destination, but I couldn't help myself manifest_destiny = StringIO() manifest_request = request.DownloadRequest(manifest_url, manifest_destiny) self.downloader.download([manifest_request]) # We can inspect the report status to see if we had an error when retrieving the manifest. if self.progress_report.state == self.progress_report.STATE_MANIFEST_FAILED: raise IOError(_("Could not retrieve %(url)s") % {'url': manifest_url}) manifest_destiny.seek(0) try: manifest = models.ISOManifest(manifest_destiny, self._repo_url) except ValueError: self.progress_report.error_message = _('The PULP_MANIFEST file was not in the ' + 'expected format.') self.progress_report.state = self.progress_report.STATE_MANIFEST_FAILED raise ValueError(self.progress_report.error_message) return manifest
def __init__(self): # load glade-file glade_file = os.path.join(os.path.dirname(__file__),"accelmap.glade") self.__xml = gtk.glade.XML(glade_file, "AccelDialog") # and get some widgets self.__dialog = self.__xml.get_widget("AccelDialog") self.__tree = self.__xml.get_widget("ActionTree") # add colums to treeview self.__tree.append_column(gtk.TreeViewColumn(_("Action"), gtk.CellRendererText(), markup=0)) self.__tree.append_column(gtk.TreeViewColumn(_("Shortcut"), gtk.CellRendererText(), text=1)) # create and fill treemodel self.__model_iters = dict() self.__model = gtk.TreeStore(str, str, str) self.__my_accel_map = dict() gtk.accel_map_foreach(self.populate_tree) self.__model.set_sort_column_id(0, gtk.SORT_ASCENDING) self.__tree.set_model(self.__model) # connect event-handler self.__tree.connect("row-activated", self.on_double_click) self.__xml.get_widget("cancel").connect('clicked', self.on_cancel_clicked) self.__xml.get_widget("apply").connect('clicked', self.on_apply_clicked)
def run(self): org = self.get_option('org') name = self.get_option('name') self.api.delete(org, name) print _("Successfully deleted filter [ %s ]") % name return os.EX_OK
def build_widget(self): v=gtk.VBox() self.label={} self.label['title']=gtk.Label() v.pack_start(self.label['title'], expand=False) exp=gtk.Expander() exp.set_expanded(False) exp.set_label(_("Contents")) c=self.label['contents']=gtk.Label() c.set_line_wrap(True) c.set_selectable(True) c.set_single_line_mode(False) c.set_alignment(0.0, 0.0) exp.add(c) v.pack_start(exp, expand=False) f=gtk.Frame(_("Members")) # Display members self.members_widget=gtk.VBox() f.add(self.members_widget) v.add(f) return v
def _check_for_relative_path_conflicts(repo, config, config_conduit, error_messages): relative_path = get_repo_relative_path(repo, config) conflicting_distributors = config_conduit.get_repo_distributors_by_relative_url(relative_path, repo.repo_id) # in all honesty, this loop should execute at most once # but it may be interesting/useful for erroneous situations for distributor in conflicting_distributors: conflicting_repo_id = distributor["repo_id"] conflicting_relative_url = None if "relative_url" in distributor["config"]: conflicting_relative_url = distributor["config"]["relative_url"] msg = _( "Relative URL [{relative_path}] for repository [{repo_id}] conflicts with " "existing relative URL [{conflict_url}] for repository [{conflict_repo}]" ) else: msg = _( "Relative URL [{relative_path}] for repository [{repo_id}] conflicts with " "repo id for existing repository [{conflict_repo}]" ) error_messages.append( msg.format( relative_path=relative_path, repo_id=repo.repo_id, conflict_url=conflicting_relative_url, conflict_repo=conflicting_repo_id, ) )
def __operation_finished_cb(self, backend): self._progress_bar.set_fraction(1.0) if self._operation == OPERATION_BACKUP: self._message_label.set_text(_('Backup finished successfully')) if self._operation == OPERATION_RESTORE: self._message_label.set_text(_('Restore realized successfully.')) self._view.props.is_valid = True
def run(self, **kwargs): consumer_id = self.get_consumer_id(kwargs) options = self.get_update_options(kwargs) units = self.get_content_units(kwargs) if not units: msg = _('No content units specified') self.context.prompt.render_failure_message(msg) return try: response = self.api.update(consumer_id, units=units, options=options) except NotFoundException: msg = _('Consumer [ %(c)s ] not found') % {'c': consumer_id} self.context.prompt.render_failure_message(msg, tag='not-found') return os.EX_DATAERR else: task = response.response_body for task_id in [t.task_id for t in task.spawned_tasks]: msg = _('Update task created with id [ %(t)s ]') % {'t': task_id} self.context.prompt.render_success_message(msg) self.poll([task], kwargs)
def modInit(self): """ Initialize the module """ self.lvls = prefs.get(__name__, 'levels', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) self.preset = prefs.get(__name__, 'preset', _('Flat')) self.cfgWindow = None modules.addMenuItem(_('Equalizer'), self.configure, '<Control>E')
def __init__(self, view): Gtk.VBox.__init__(self) self._view = view hbox = Gtk.HBox() self.backup_btn = _BackupButton( icon_name='backup-backup', title=_('Save the contents of your Journal'), pixel_size=style.GRID_CELL_SIZE) self.backup_btn.connect('button_press_event', self.__backup_button_press_cb) hbox.pack_start(self.backup_btn, False, False, style.DEFAULT_SPACING) self.restore_btn = _BackupButton( icon_name='backup-restore', title=_('Restore the contents of your Journal'), pixel_size=style.GRID_CELL_SIZE) self.restore_btn.connect('button_press_event', self.__restore_button_press_cb) hbox.pack_start(self.restore_btn, False, False, style.DEFAULT_SPACING) hbox.set_valign(Gtk.Align.CENTER) hbox.set_halign(Gtk.Align.CENTER) self.add(hbox) self.show_all()
def _setup_toolbars(self): ''' Setup the toolbars.. ''' tools_toolbar = Gtk.Toolbar() numbers_toolbar = Gtk.Toolbar() toolbox = ToolbarBox() self.activity_toolbar_button = ActivityToolbarButton(self) toolbox.toolbar.insert(self.activity_toolbar_button, 0) self.activity_toolbar_button.show() self.numbers_toolbar_button = ToolbarButton( page=numbers_toolbar, icon_name='number-tools') if MODE == 'number': numbers_toolbar.show() toolbox.toolbar.insert(self.numbers_toolbar_button, -1) self.numbers_toolbar_button.show() self.tools_toolbar_button = ToolbarButton( page=tools_toolbar, icon_name='view-source') self.button_pattern = button_factory( 'new-pattern-game', toolbox.toolbar, self._select_game_cb, cb_arg='pattern', tooltip=_('New game')) self._set_extras(toolbox.toolbar) self._sep.append(separator_factory(toolbox.toolbar, True, False)) stop_button = StopButton(self) stop_button.props.accelerator = '<Ctrl>q' toolbox.toolbar.insert(stop_button, -1) stop_button.show() button_factory('score-copy', self.activity_toolbar_button, self._write_scores_to_clipboard, tooltip=_('Export scores to clipboard')) self.set_toolbar_box(toolbox) toolbox.show() if MODE == 'word': self.words_tool_button = button_factory( 'word-tools', tools_toolbar, self._edit_words_cb, tooltip=_('Edit word lists.')) self.import_button = button_factory( 'image-tools', tools_toolbar, self.image_import_cb, tooltip=_('Import custom cards')) self.button_custom = button_factory( 'new-custom-game', tools_toolbar, self._select_game_cb, cb_arg='custom', tooltip=_('New custom game')) self.button_custom.set_sensitive(False) if MODE == 'number': self._setup_number_buttons(numbers_toolbar)
def __init__(self, context, name='list', description=DESC_LIST, method=None, repos_title=None, other_repos_title=None, include_all_flag=True): self.context = context self.prompt = context.prompt if method is None: method = self.run self.repos_title = repos_title if self.repos_title is None: self.repos_title = _('Repositories') self.other_repos_title = other_repos_title if self.other_repos_title is None: self.other_repos_title = _('Other Pulp Repositories') super(ListRepositoriesCommand, self).__init__(name, description, method) d = _('if specified, detailed configuration information is displayed for each repository') self.add_option(PulpCliFlag('--details', d)) d = _('comma-separated list of repository fields; if specified, only the given fields will displayed') self.add_option(PulpCliOption('--fields', d, required=False)) self.supports_all = include_all_flag if self.supports_all: d = _('if specified, information on all Pulp repositories, regardless of type, will be displayed') self.add_option(PulpCliFlag('--all', d, aliases=['-a']))
def read (self): self.emit('progress',0,_('Logging into %s')%'www.cooksillustrated.com') global driver if driver: # Don't log in twice :) self.d = driver else: #self.d = webdriver.Chrome() self.d = webdriver.Firefox() print 'Logging in...' driver = self.d self.d.get('https://www.cooksillustrated.com/sign_in/') username,pw = self.get_username_and_pw() #un=self.d.find_element_by_xpath('//*[@name="user[email]"]') un=self.d.find_element_by_xpath('//*[@id="email"]') print 'Got email element',un un.send_keys(username) #pw_el = self.d.find_element_by_xpath('//*[@name="user[password]"]') pw_el = self.d.find_element_by_xpath('//*[@id="password"]') print 'Got password element',pw_el pw_el.send_keys(pw+'\n') # Now get URL # First log in... self.emit('progress',0.5,_('Logging into %s')%'www.cooksillustrated.com') self.emit('progress',0.6,_('Retrieving %s')%self.url) self.d.get(self.url) self.emit('progress',1,_('Retrieving %s')%self.url) self.content_type = 'text/html' self.data = self.d.page_source
def _create_technical(self): vbox = Gtk.VBox() vbox.props.spacing = style.DEFAULT_SPACING if 'filesize' in self._metadata: filesize = self._metadata['filesize'] else: filesize = model.get_file_size(self._metadata['uid']) lines = [ _('Kind: %s') % (self._metadata.get('mime_type') or _('Unknown'),), _('Date: %s') % (self._format_date(),), _('Size: %s') % (format_size(int(filesize))) ] for line in lines: linebox = Gtk.HBox() vbox.pack_start(linebox, False, False, 0) text = Gtk.Label() text.set_markup('<span foreground="%s">%s</span>' % ( style.COLOR_BUTTON_GREY.get_html(), line)) linebox.pack_start(text, False, False, 0) return vbox
def __init__(self, parent): BaseDialog.__init__(self, parent) self.main_ui = parent self.header_label = QtGui.QLabel() self.header_label.setAlignment(QtCore.Qt.AlignCenter) self.pcde_le = UpperCaseLineEdit() self.pcde_le.setText(self.main_ui.pt.pcde) self.simd_label = QtGui.QLabel() self.simd_label.setAlignment(QtCore.Qt.AlignCenter) self.tbi_checkbox = QtGui.QCheckBox( _("ToothBrushing Instruction Given")) self.tbi_checkbox.setChecked(True) self.di_checkbox = QtGui.QCheckBox(_("Dietary Advice Given")) self.di_checkbox.setChecked(True) self.fl_checkbox = QtGui.QCheckBox(_("Fluoride Varnish Applied")) self.fl_checkbox.setToolTip( _("Fee claimable for patients betwen 2 and 5")) self.fl_checkbox.setChecked(2 <= self.main_ui.pt.ageYears <= 5) self.insertWidget(self.header_label) self.insertWidget(self.pcde_le) self.insertWidget(self.simd_label) self.insertWidget(self.tbi_checkbox) self.insertWidget(self.di_checkbox) self.insertWidget(self.fl_checkbox) self.pcde_le.textEdited.connect(self.check_pcde) self._simd = None
def _file_part_receiver(self, target, filename, part, numparts, bytes, title=None, color=None, sender=None): # ignore my own signal if sender == self._tube.get_unique_name(): return if not (target == 'all' or target == self._tube.get_unique_name()): return # first chunk if part == 1: tmp_root = join(environ['SUGAR_ACTIVITY_ROOT'], 'instance') temp_dir = tempfile.mkdtemp(dir=tmp_root) chmod(temp_dir, 0777) self.temp_file = join(temp_dir, 'game.zip') self.files[filename] = self.temp_file self.f = open(self.temp_file, 'a+b') self.f.write(bytes) percentage = int(float(part) / float(numparts) * 100.0) self.game.set_load_mode(_('Receiving game') + ': ' + str(percentage) + '% ' + _('done') + '.') # last chunk if part == numparts: self.f.close() #file = self.files[filename] # Saves the zip in datastore gameObject = datastore.create() gameObject.metadata['title'] = title gameObject.metadata['mime_type'] = 'application/x-memorize-project' gameObject.metadata['icon-color'] = color gameObject.file_path = self.temp_file datastore.write(gameObject)
def on_save(self): self.bookmarks_win.save() if find_duplicates(self.new_bookmarks): self.core.information(_('Duplicate bookmarks in list (saving aborted)'), 'Error') return for bm in self.new_bookmarks: if safeJID(bm.jid): if not self.bookmarks[bm.jid]: self.bookmarks.append(bm) else: self.core.information(_('Invalid JID for bookmark: %s/%s') % (bm.jid, bm.nick), 'Error') return for bm in self.removed_bookmarks: if bm in self.bookmarks: self.bookmarks.remove(bm) def send_cb(success): if success: self.core.information(_('Bookmarks saved.'), 'Info') else: self.core.information(_('Remote bookmarks not saved.'), 'Error') log.debug('alerte %s', str(stanza_storage(self.bookmarks.bookmarks))) self.bookmarks.save(self.core.xmpp, callback=send_cb) self.core.close_tab() return True
def update_disc_usage (self): if not self.update: return if self.source.total_duration > self.disc_size: self.__capacity_exceeded.show () else: self.__capacity_exceeded.hide () # Flush events so progressbar redrawing gets done while gtk.events_pending(): gtk.main_iteration(True) if self.source.total_duration > 0: duration = self.__disc_size - self.source.total_duration if duration > 0: dur = _("%s remaining") % self.__hig_duration (duration) else: dur = _("%s overlaping") % self.__hig_duration (abs (duration)) else: dur = _("Empty") self.__usage_label.set_text (dur) e = operations.Event(self) for l in self.listeners: l.on_contents_changed (e)
def on_added(self): actions = {} def configure_dnie(): os.system('%s --install-dnie' % CERTMANAGER_CMD) def configure_ceres(): os.system('%s --install-ceres' % CERTMANAGER_CMD) if os.path.exists(CERTMANAGER_CMD): actions[_("Configure DNIe")] = configure_dnie actions[_("Configure FNMT-Ceres card")] = configure_ceres def add_user_to_scard(): import pwd # The os.getlogin() raises OSError: [Errno 25] # Moved to getpwuid user = pwd.getpwuid(os.geteuid())[0] # get root access if get_sudo(): cmd = '/usr/bin/gksudo /usr/sbin/adduser %s scard' % user status, output = commands.getstatusoutput(cmd) self.msg_render.show_info(_('Session restart needed'), _('You must restart your session to apply the changes')) status, output = commands.getstatusoutput('/usr/bin/groups') if 'scard' not in output: actions[_("Add user to scard group")] = add_user_to_scard self.msg_render.show(self.__device_title__, self.__device_conn_description__, self.__icon_path__, actions=actions)
def __init__(self, *args, **kwargs): super(SaveMetadataStep, self).__init__(*args, **kwargs) self.description = _('Save metadata')
def _setup_page(self): for child in self.get_children(): self.remove(child) def _setup_name_page(self): self._current_page = self._name_page def _setup_color_page(self): self._current_page = self._color_page def _setup_gender_page(self): if self._color_page.get_color() is not None: self._gender_page.update_color(self._color_page.get_color()) self._current_page = self._gender_page def _setup_age_page(self): if self._gender_page.get_gender() is not None: self._age_page.update_gender(self._gender_page.get_gender()) if self._color_page.get_color() is not None: self._age_page.update_color(self._color_page.get_color()) self._current_page = self._age_page setup_methods = [ _setup_name_page, _setup_color_page, _setup_gender_page, _setup_age_page ] setup_methods[self._page](self) self.pack_start(self._current_page, True, True, 0) self._current_page.show() button_box = Gtk.HButtonBox() if self._page == self.PAGE_FIRST: button_box.set_layout(Gtk.ButtonBoxStyle.END) else: button_box.set_layout(Gtk.ButtonBoxStyle.EDGE) back_button = Gtk.Button(_('Back')) image = Icon(icon_name='go-left') back_button.set_image(image) back_button.connect('clicked', self._back_activated_cb) button_box.pack_start(back_button, True, True, 0) back_button.show() self._next_button = Gtk.Button() image = Icon(icon_name='go-right') self._next_button.set_image(image) if self._page == self.PAGE_LAST: self._next_button.set_label(_('Done')) self._next_button.connect('clicked', self._done_activated_cb) else: self._next_button.set_label(_('Next')) self._next_button.connect('clicked', self._next_activated_cb) self._current_page.activate() self._update_next_button() button_box.pack_start(self._next_button, True, True, 0) self._next_button.show() self._current_page.connect('notify::valid', self._page_valid_changed_cb) self.pack_start(button_box, False, True, 0) button_box.show() if not self.PAGES[self._page]: next(self)
def __init__(self): super().__init__(name="IDE", description=_("Generic IDEs"), logo_path=None)
def __init_attributes(self, editor): self.__editor = editor self.__manager = None # name, shortcut, description, category = ( # "zencoding-toggle-comment", # "<alt>c", # _("Add or remove comments in most web languages"), # _("Markup Operations") # ) # self.__trigger1 = self.create_trigger(name, shortcut, description, category) # self.__trigger1.zen_action = "toggle_comment" name, shortcut, description, category = ( "zencoding-expand-abbreviation", "<ctrl>comma", _("Expand markup abbreviations"), _("Markup Operations") ) self.__trigger2 = self.create_trigger(name, shortcut, description, category) self.__trigger2.zen_action = "expand_abbreviation" name, shortcut, description, category = ( "zencoding-next-edit-point", "<super><alt>Right", _("Move cursor to next edit point"), _("Markup Operations") ) self.__trigger3 = self.create_trigger(name, shortcut, description, category) self.__trigger3.zen_action = "next_edit_point" name, shortcut, description, category = ( "zencoding-previous-edit-point", "<super><alt>Left", _("Move cursor to previous edit point"), _("Markup Operations") ) self.__trigger4 = self.create_trigger(name, shortcut, description, category) self.__trigger4.zen_action = "prev_edit_point" name, shortcut, description, category = ( "zencoding-remove-tag", "<super>r", _("Remove a tag"), _("Markup Operations") ) self.__trigger5 = self.create_trigger(name, shortcut, description, category) self.__trigger5.zen_action = "remove_tag" name, shortcut, description, category = ( "zencoding-select-in-tag", "<super>i", _("Select inner tag's content"), _("Markup Operations") ) self.__trigger6 = self.create_trigger(name, shortcut, description, category) self.__trigger6.zen_action = "match_pair_inward" name, shortcut, description, category = ( "zencoding-select-out-tag", "<super>o", _("Select outer tag's content"), _("Markup Operations") ) self.__trigger7 = self.create_trigger(name, shortcut, description, category) self.__trigger7.zen_action = "match_pair_outward" name, shortcut, description, category = ( "zencoding-split", "<super>j", _("Toggle between single and double tag"), _("Markup Operations") ) self.__trigger8 = self.create_trigger(name, shortcut, description, category) self.__trigger8.zen_action = "split_join_tag" name, shortcut, description, category = ( "zencoding-merge", "<super>m", _("Merge lines"), _("Markup Operations") ) self.__trigger9 = self.create_trigger(name, shortcut, description, category) self.__trigger9.zen_action = "merge_lines" name, shortcut, description, category = ( "zencoding-wrap-with-abbreviation", "<ctrl>less", _("Wrap with abbreviation"), _("Markup Operations") ) self.__trigger10 = self.create_trigger(name, shortcut, description, category) self.__trigger10.zen_action = "wrap_with_abbreviation" return
from gettext import gettext as _ import hashlib import os import sys import rpm from pulp.client.commands.options import OPTION_REPO_ID from pulp.client.commands.repo.upload import UploadCommand, MetadataException from pulp.client.extensions.extensions import PulpCliFlag from pulp_rpm.common.ids import TYPE_ID_RPM, TYPE_ID_SRPM from pulp_rpm.extensions.admin.repo_options import OPT_CHECKSUM_TYPE NAME_RPM = 'rpm' DESC_RPM = _('uploads one or more RPMs into a repository') SUFFIX_RPM = '.rpm' NAME_SRPM = 'srpm' DESC_SRPM = _('uploads one or more SRPMs into a repository') SUFFIX_SRPM = '.src.rpm' DESC_SKIP_EXISTING = _('if specified, RPMs that already exist on the server will not be uploaded') FLAG_SKIP_EXISTING = PulpCliFlag('--skip-existing', DESC_SKIP_EXISTING) RPMTAG_NOSOURCE = 1051 CHECKSUM_READ_BUFFER_SIZE = 65536 class _CreatePackageCommand(UploadCommand): """
# -*- coding: utf-8 -*- # Resolving gettext as _ for module loading. from gettext import gettext as _ SKILL_NAME = "Bangalore Guide" WELCOME = _("Welcome to Bangalore Guide!") HELP = _("Say about, to hear more about the city, or say coffee, breakfast, lunch, or dinner, to hear local restaurant suggestions, or say recommend an attraction, or say, go outside. ") ABOUT = _("Bangalore, Karnataka is a city in South India. A popular city for anything tech related, Bangalore is known for its tech scene and diverse urban population.") STOP = _("Okay, see you next time!") FALLBACK = _("The {} can't help you with that. It can help you learn about Bangalore if you say tell me about this place. What can I help you with?") GENERIC_REPROMPT = _("What can I help you with?") CITY_DATA = { "city": "Bangalore", "state": "Karnataka", "postcode": "560025", "restaurants": [ { "name": "A Whole Lotta Love", "address": 'Koramangala', "phone": '978-283-0474', "meals": 'Breakfast', "description": 'A cozy and popular spot for breakfast. Try the omlettes!', }, { "name": 'Cafe Coffee Day', "address": 'Richmond Road', "phone": '978-281-1851', "meals": 'coffee, snacks',
def __init__(self, repo, conduit, config): """ :param repo: repository to sync :type repo: pulp.plugins.model.Repository :param conduit: sync conduit to use :type conduit: pulp.plugins.conduits.repo_sync.RepoSyncConduit :param config: config object for the sync :type config: pulp.plugins.config.PluginCallConfiguration """ super(RepoSync, self).__init__(step_type=constants.SYNC_STEP, repo=repo, conduit=conduit, config=config) self.description = _('Syncing Repository') self.feed_url = self.get_config().get('feed').strip('/') self.releases = self.get_config().get('releases', 'stable').split(',') self.architectures = split_or_none(self.get_config().get('architectures')) self.components = split_or_none(self.get_config().get('components')) self.unit_relative_urls = {} self.available_units = None # dicts with release names as keys to multiplex variables self.apt_repo_meta = {} self.release_units = {} self.release_files = { release: os.path.join(self.get_working_dir(), release, 'Release') for release in self.releases} self.feed_urls = { release: urlparse.urljoin(self.feed_url + '/', '/'.join(['dists', release])) for release in self.releases} self.release_urls = { release: urlparse.urljoin(self.feed_urls[release] + '/', 'Release') for release in self.releases} self.packages_urls = {} # double dicts with release/component as keys self.component_units = defaultdict(dict) self.component_packages = defaultdict(dict) for release in self.releases: misc.mkdir(os.path.dirname(self.release_files[release])) _logger.info("Downloading %s", self.release_urls[release]) # defining lifecycle # metadata self.add_child(publish_step.DownloadStep( constants.SYNC_STEP_RELEASE_DOWNLOAD, plugin_type=ids.TYPE_ID_IMPORTER, description=_('Retrieving metadata: release file(s)'), downloads=[ DownloadRequest(self.release_urls[release], self.release_files[release]) for release in self.releases])) self.add_child(ParseReleaseStep(constants.SYNC_STEP_RELEASE_PARSE)) self.step_download_Packages = publish_step.DownloadStep( constants.SYNC_STEP_PACKAGES_DOWNLOAD, plugin_type=ids.TYPE_ID_IMPORTER, description=_('Retrieving metadata: Packages files')) self.add_child(self.step_download_Packages) self.add_child(ParsePackagesStep(constants.SYNC_STEP_PACKAGES_PARSE)) # packages self.step_local_units = publish_step.GetLocalUnitsStep( importer_type=ids.TYPE_ID_IMPORTER) self.add_child(self.step_local_units) self.add_child(CreateRequestsUnitsToDownload( constants.SYNC_STEP_UNITS_DOWNLOAD_REQUESTS)) self.step_download_units = publish_step.DownloadStep( constants.SYNC_STEP_UNITS_DOWNLOAD, plugin_type=ids.TYPE_ID_IMPORTER, description=_('Retrieving units')) self.add_child(self.step_download_units) self.add_child(SaveDownloadedUnits(constants.SYNC_STEP_SAVE)) # metadata self.add_child(SaveMetadataStep(constants.SYNC_STEP_SAVE_META))
def __init__(self, *args, **kwargs): super(CreateRequestsUnitsToDownload, self).__init__(*args, **kwargs) self.description = _('Prepare Package Download')
def __init__(self, *args, **kwargs): super(ParseReleaseStep, self).__init__(*args, **kwargs) self.description = _('Parse Release Files')
def __init__(self, *args, **kwargs): super(SaveDownloadedUnits, self).__init__(*args, **kwargs) self.description = _('Save and associate downloaded units')
def __str__(self): return _('RepoSyncConduit for repository [%(r)s]') % { 'r': self.repo_id }
def __init__(self, *args, **kwargs): super(ParsePackagesStep, self).__init__(*args, **kwargs) self.description = _('Parse Packages Files')
def run(self, **kwargs): arg_utils.convert_removed_options(kwargs) importer_config = self.parse_user_input(kwargs) name = kwargs.pop(OPT_UPSTREAM_NAME.keyword, None) if name is not None: importer_config[constants.CONFIG_KEY_UPSTREAM_NAME] = name if importer_config: kwargs['importer_config'] = importer_config # Update distributor configuration web_config = {} export_config = {} value = kwargs.pop(OPT_PROTECTED.keyword, None) if value is not None: web_config[constants.CONFIG_KEY_PROTECTED] = value value = kwargs.pop(OPT_REDIRECT_URL.keyword, None) if value is not None: web_config[constants.CONFIG_KEY_REDIRECT_URL] = value export_config[constants.CONFIG_KEY_REDIRECT_URL] = value value = kwargs.pop(OPT_REPO_REGISTRY_ID.keyword, None) if value is not None: web_config[constants.CONFIG_KEY_REPO_REGISTRY_ID] = value export_config[constants.CONFIG_KEY_REPO_REGISTRY_ID] = value value = kwargs.pop(OPT_AUTO_PUBLISH.keyword, None) if value is not None: web_config['auto_publish'] = value if web_config or export_config: kwargs['distributor_configs'] = {} if web_config: kwargs['distributor_configs'][ constants.CLI_WEB_DISTRIBUTOR_ID] = web_config if export_config: kwargs['distributor_configs'][ constants.CLI_EXPORT_DISTRIBUTOR_ID] = export_config # Update Tags repo_id = kwargs.get(OPTION_REPO_ID.keyword) response = self.context.server.repo.repository(repo_id).response_body scratchpad = response.get(u'scratchpad', {}) image_tags = scratchpad.get(u'tags', []) user_tags = kwargs.get(OPTION_TAG.keyword) if user_tags: user_tags = kwargs.pop(OPTION_TAG.keyword) for tag, image_id in user_tags: if len(image_id) < 6: msg = _( 'The image id, (%s), must be at least 6 characters.') self.prompt.render_failure_message(msg % image_id) return # Ensure the specified images exist in the repo images_requested = set([image_id for tag, image_id in user_tags]) images = ['^%s' % image_id for image_id in images_requested] image_regex = '|'.join(images) search_criteria = { 'type_ids': constants.IMAGE_TYPE_ID, 'match': [['image_id', image_regex]], 'fields': ['image_id'] } response = self.context.server.repo_unit.search(repo_id, **search_criteria).\ response_body if len(response) != len(images): images_found = set( [x[u'metadata'][u'image_id'] for x in response]) missing_images = images_requested.difference(images_found) msg = _( 'Unable to create tag in repository. The following image(s) do not ' 'exist in the repository: %s.') self.prompt.render_failure_message(msg % ', '.join(missing_images)) return # Get the full image id from the returned values and save in tags_to_update dictionary tags_to_update = {} for image in response: found_image_id = image[u'metadata'][u'image_id'] for tag, image_id in user_tags: if found_image_id.startswith(image_id): tags_to_update[tag] = found_image_id # Create a list of tag dictionaries that can be saved on the repo scratchpad # using the original tags and new tags specified by the user image_tags = tags.generate_updated_tags(scratchpad, tags_to_update) scratchpad[u'tags'] = image_tags kwargs[u'scratchpad'] = scratchpad remove_tags = kwargs.get(OPTION_REMOVE_TAG.keyword) if remove_tags: kwargs.pop(OPTION_REMOVE_TAG.keyword) for tag in remove_tags: # For each tag in remove_tags, remove the respective tag dictionary # for matching tag. for image_tag in image_tags[:]: if tag == image_tag[constants.IMAGE_TAG_KEY]: image_tags.remove(image_tag) scratchpad[u'tags'] = image_tags kwargs[u'scratchpad'] = scratchpad super(UpdateDockerRepositoryCommand, self).run(**kwargs)
from gettext import gettext as _ SKILL_NAME = _("Sauce Boss") HEADER_TITLE = _("Welcome to {}") RECIPE_HEADER_TITLE = _("HOW TO MAKE {} SAUCE") HELP_HEADER_TITLE = _("HELP") HELP_HEADER_SUBTITLE = _("Select the sauce you want to prepare") WELCOME_MESSAGE = _( "Welcome to {}. You can ask a question like, what's the recipe for {} sauce? ... Now, which sauce would you like to prepare?" ) WELCOME_REPROMPT = _( "For instructions on what you can say, please say help me. Which sauce would you like to prepare?" ) DISPLAY_CARD_TITLE = _("{} - Recipe for {}") HELP_MESSAGE = _( "You can ask questions such as, what's the recipe for {}, or, you can say exit ... Now, which sauce would you like to prepare?" ) HELP_REPROMPT = _( "You can say things like, what's the recipe for {}, or you can say ... Now, which sauce would you like to prepare?" ) STOP_MESSAGE = _("Goodbye!") RECIPE_REPEAT_MESSAGE = _("Try saying repeat") RECIPE_NOT_FOUND_WITH_ITEM_NAME = _( "I'm sorry, I currently do not know the recipe for {}. Which sauce would you like to prepare?" ) RECIPE_NOT_FOUND_WITHOUT_ITEM_NAME = _( "I'm sorry, I currently do not know that recipe. Which sauce would you like to prepare?" ) RECIPE_NOT_FOUND_REPROMPT = _("Which sauce would you like to prepare?") ERROR_MESSAGE = _("I'm sorry I didn't catch that. Can you reformulate please?") HINT_TEMPLATE = _("How do I make {} sauce?")
def on_setup_new(self): launch("blueman-assistant", None, False, "blueman", _("Bluetooth Assistant"))
def load_plugin(self, name: Optional[str] = None, user_action: bool = False) -> None: if name: try: self.__load_plugin(self.__classes[name]) except LoadException: pass except Exception: if user_action: d = ErrorDialog(_( "<b>An error has occured while loading " "a plugin. Please notify the developers " "with the content of this message to our </b>\n" "<a href=\"http://github.com/blueman-project/blueman/issues\">website.</a>" ), excp=traceback.format_exc()) d.run() d.destroy() raise return path = os.path.dirname(self.module_path.__file__) plugins = [] for root, dirs, files in os.walk(path): for f in files: if f.endswith(".py") and not (f.endswith(".pyc") or f.endswith("_.py")): plugins.append(f[0:-3]) logging.info(plugins) for plugin in plugins: try: importlib.import_module(self.module_path.__name__ + f".{plugin}") except ImportError: logging.error(f"Unable to load plugin module {plugin}", exc_info=True) except PluginException as err: logging.warning(f"Failed to start plugin {plugin}: {err}") for cls in self.plugin_class.__subclasses__(): self.__classes[cls.__name__] = cls if cls.__name__ not in self.__deps: self.__deps[cls.__name__] = [] if cls.__name__ not in self.__cfls: self.__cfls[cls.__name__] = [] for c in cls.__depends__: if c not in self.__deps: self.__deps[c] = [] self.__deps[c].append(cls.__name__) for c in cls.__conflicts__: if c not in self.__cfls: self.__cfls[c] = [] self.__cfls[c].append(cls.__name__) if c not in self.__cfls[cls.__name__]: self.__cfls[cls.__name__].append(c) cl = self.config_list for name, cls in self.__classes.items(): for dep in self.__deps[name]: # plugins that are required by not unloadable plugins are not unloadable too if not self.__classes[dep].__unloadable__: cls.__unloadable__ = False if (cls.__autoload__ or (cl and cls.__name__ in cl)) and \ not (cls.__unloadable__ and cl and "!" + cls.__name__ in cl): self.__load_plugin(cls)
def on_local_services(self): launch("blueman-services", None, False, "blueman", _("Service Preferences"))
from gettext import gettext as _ from pulp.client import arg_utils, parsers from pulp.client.commands.options import OPTION_REPO_ID from pulp.client.commands.repo.cudl import CreateAndConfigureRepositoryCommand from pulp.client.commands.repo.cudl import UpdateRepositoryCommand from pulp.client.commands.repo.importer_config import ImporterConfigMixin from pulp.common.constants import REPO_NOTE_TYPE_KEY from pulp.client.extensions.extensions import PulpCliOption from pulp_docker.common import constants, tags from pulp_docker.extensions.admin import parsers as docker_parsers d = _( 'if "true", on each successful sync the repository will automatically be ' 'published; if "false" content will only be available after manually publishing ' 'the repository; defaults to "true"') OPT_AUTO_PUBLISH = PulpCliOption('--auto-publish', d, required=False, parse_func=parsers.parse_boolean) d = _( 'The URL that will be used when generating the redirect map for connecting the docker ' 'API to the location the content is stored. ' 'The value defaults to https://<server_name_from_pulp_server.conf>/pulp/docker/<repo_name>.' ) OPT_REDIRECT_URL = PulpCliOption('--redirect-url', d, required=False) d = _( 'the name that will be used for this repository in the Docker registry. If not specified, '
def on_devices(self): lockfile = get_lockfile('blueman-manager') pid = get_pid(lockfile) if not lockfile or not kill(pid, 'blueman-manager'): launch("blueman-manager", None, False, "blueman", _("Device Manager"))
class StandardItems(AppletPlugin): __depends__ = ["StatusIcon", "Menu"] __unloadable__ = False __description__ = _("Adds standard menu items to the status icon menu") __author__ = "walmis" def on_load(self): self._plugin_window = None self.parent.Plugins.Menu.add(self, 21) self.new_dev = self.parent.Plugins.Menu.add( self, 30, text=_("_Set Up New Device") + "…", icon_name="document-new", callback=self.on_setup_new) self.parent.Plugins.Menu.add(self, 31) self.send = self.parent.Plugins.Menu.add( self, 40, text=_("Send _Files to Device") + "…", icon_name="blueman-send-file", callback=self.on_send) self.parent.Plugins.Menu.add(self, 51) self.devices = self.parent.Plugins.Menu.add(self, 60, text=_("_Devices") + "…", icon_name="blueman", callback=self.on_devices) self.adapters = self.parent.Plugins.Menu.add( self, 70, text=_("Adap_ters") + "…", icon_name="blueman-device", callback=self.on_adapters) self.parent.Plugins.Menu.add(self, 80, text=_("_Local Services") + "…", icon_name="preferences-desktop", callback=self.on_local_services) self.parent.Plugins.Menu.add(self, 81) self.parent.Plugins.Menu.add(self, 90, text="_Help", icon_name='help-about', callback=self.on_about) self.parent.Plugins.Menu.add(self, 85, text=_("_Plugins"), icon_name="blueman-plugin", callback=self.on_plugins) self.parent.Plugins.StatusIcon.connect( "activate", lambda _status_icon: self.on_devices()) def change_sensitivity(self, sensitive): if 'PowerManager' in self.parent.Plugins.get_loaded(): power = self.parent.Plugins.PowerManager.get_bluetooth_status() else: power = True sensitive = sensitive and self.parent.Manager and power self.new_dev.set_sensitive(sensitive) self.send.set_sensitive(sensitive) self.devices.set_sensitive(sensitive) self.adapters.set_sensitive(sensitive) def on_manager_state_changed(self, state): self.change_sensitivity(state) def on_power_state_changed(self, manager, state): self.change_sensitivity(state) def on_setup_new(self): launch("blueman-assistant", None, False, "blueman", _("Bluetooth Assistant")) def on_send(self): launch("blueman-sendto", None, False, "blueman", _("File Sender")) def on_devices(self): lockfile = get_lockfile('blueman-manager') pid = get_pid(lockfile) if not lockfile or not kill(pid, 'blueman-manager'): launch("blueman-manager", None, False, "blueman", _("Device Manager")) def on_adapters(self): launch("blueman-adapters", None, False, "blueman", _("Adapter Preferences")) def on_local_services(self): launch("blueman-services", None, False, "blueman", _("Service Preferences")) def on_about(self): about = show_about_dialog("Blueman " + _("applet"), run=False) im = Gtk.Image(icon_name="blueman-plugin", pixel_size=16) button = Gtk.Button(label=_("Plugins"), visible=True, image=im) button.connect("clicked", lambda _button: self.on_plugins()) about.action_area.pack_start(button, True, True, 0) about.action_area.reorder_child(button, 0) about.run() about.destroy() def on_plugins(self): def on_close(win, event): win.destroy() self._plugin_window = None if self._plugin_window: self._plugin_window.present() else: self._plugin_window = PluginDialog(self.parent) self._plugin_window.connect("delete-event", on_close) self._plugin_window.show()
def create_palette(): palette = Palette(_('Show my keyboard')) palette.set_group_id('frame') return palette
def on_adapters(self): launch("blueman-adapters", None, False, "blueman", _("Adapter Preferences"))
def get_page_title(self): return _('HSV Square')
def on_send(self): launch("blueman-sendto", None, False, "blueman", _("File Sender"))
class StaticInterface(BaseAddressRecord, BasePTR, ExpirableMixin): # Keep in mind that BaseAddressRecord will have it's methods called before # BasePTR """The StaticInterface Class. >>> s = StaticInterface(label=label, domain=domain, ip_str=ip_str, ... ip_type=ip_type, dhcp_enabled=True, dns_enabled=True) >>> s.save() This class is the main interface to DNS and DHCP. A static interface consists of three key pieces of information: IP address, MAC address, and hostname (the hostname is comprised of a label and a domain). From these three pieces of information, three things are ensured: An A or AAAA DNS record, a PTR record, and a `host` statement in the DHCP builds that grants the MAC address of the interface the correct IP address and hostname. If you want an A/AAAA, PTR, and a DHCP lease, create one of these objects. In terms of DNS, a static interface represents a PTR and A record and must adhere to the requirements of those classes. The interface inherits from BaseAddressRecord. """ pretty_type = 'static interface' id = models.AutoField(primary_key=True) mac = MacAddrField(dhcp_enabled='dhcp_enabled', verbose_name='MAC address', help_text='(required if DHCP is enabled)') reverse_domain = models.ForeignKey(Domain, null=True, blank=True, related_name='reverse_staticintr_set') system = models.ForeignKey( System, help_text='System to associate the interface with') workgroup = models.ForeignKey(Workgroup, null=True, blank=True) dhcp_enabled = models.BooleanField(verbose_name='Enable DHCP?', default=True) dns_enabled = models.BooleanField(verbose_name='Enable DNS?', default=True) last_seen = models.DateTimeField(null=True, blank=True) search_fields = ('mac', 'ip_str', 'fqdn') class Meta: app_label = 'cyder' db_table = 'static_interface' unique_together = (('ip_upper', 'ip_lower'), ('label', 'domain')) @staticmethod def filter_by_ctnr(ctnr, objects=None): objects = objects or StaticInterface.objects return objects.filter(ctnr=ctnr) def __unicode__(self): return self.fqdn @property def range(self): if self.ip_str: return find_range(self.ip_str) def details(self): data = super(StaticInterface, self).details() data['data'] = ( ('Name', 'fqdn', self), ('System', 'system', self.system), ('IP', 'ip_str', str(self.ip_str)), ('MAC', 'mac', self.mac), ('Workgroup', 'workgroup', self.workgroup), ('DHCP', 'dhcp_enabled', 'True' if self.dhcp_enabled else 'False'), ('DNS', 'dns_enabled', 'True' if self.dns_enabled else 'False'), ('Last seen', 'last_seen', self.last_seen), ) return data @staticmethod def eg_metadata(): """EditableGrid metadata.""" return { 'metadata': [ { 'name': 'fqdn', 'datatype': 'string', 'editable': False }, ] } @property def rdtype(self): return 'INTR' def get_related_systems(self): related_interfaces = StaticInterface.objects.filter(mac=self.mac) related_interfaces = related_interfaces.select_related('system') related_systems = set() for interface in related_interfaces: related_systems.update([interface.system]) return related_systems @transaction_atomic def save(self, *args, **kwargs): self.full_clean() update_range_usage = kwargs.pop('update_range_usage', True) old_range = None if self.id is not None: old_range = StaticInterface.objects.get(id=self.id).range super(StaticInterface, self).save(*args, **kwargs) self.schedule_zone_rebuild() if update_range_usage: new_range = self.range if new_range: new_range.save(commit=False) if old_range: old_range.save(commit=False) @transaction_atomic def delete(self, *args, **kwargs): rng = self.range update_range_usage = kwargs.pop('update_range_usage', True) delete_system = kwargs.pop('delete_system', True) if delete_system: if (not self.system.staticinterface_set.exclude( id=self.id).exists() and not self.system.dynamicinterface_set.exists()): self.system.delete(commit=False) super(StaticInterface, self).delete(*args, **kwargs) if rng and update_range_usage: rng.save(commit=False) def schedule_zone_rebuild(self): if self.domain.soa is not None: self.domain.soa.schedule_rebuild() if self.reverse_domain.soa is not None: self.reverse_domain.soa.schedule_rebuild() def check_A_PTR_collision(self): if PTR.objects.filter(ip_str=self.ip_str).exists(): raise ValidationError("A PTR already uses '%s'" % self.ip_str) if AddressRecord.objects.filter(ip_str=self.ip_str, fqdn=self.fqdn).exists(): raise ValidationError("An A record already uses '%s' and '%s'" % (self.fqdn, self.ip_str)) def format_host_option(self, option): s = str(option) s = s.replace('%h', self.label) s = s.replace('%i', self.ip_str) s = s.replace('%m', self.mac.replace(':', '')) s = s.replace('%6m', self.mac.replace(':', '')[0:6]) return s def build_host(self, options=None): build_str = '\thost {0} {{\n'.format(self.fqdn) build_str += '\t\thardware ethernet {0};\n'.format(self.mac) if self.ip_type == IP_TYPE_6: build_str += '\t\tfixed-address6 {0};\n'.format(self.ip_str) else: build_str += '\t\tfixed-address {0};\n'.format(self.ip_str) build_str += join_dhcp_args(map(self.format_host_option, options), depth=2) options = self.staticinterfaceav_set.filter( attribute__attribute_type=ATTRIBUTE_OPTION) statements = self.staticinterfaceav_set.filter( attribute__attribute_type=ATTRIBUTE_STATEMENT) if options: build_str += '\t\t# Host Options\n' build_str += join_dhcp_args(options, depth=2) if statements: build_str += '\t\t# Host Statements\n' build_str += join_dhcp_args(statements, depth=2) build_str += '\t}\n' return build_str def build_subclass(self, classname): return 'subclass "{0}" 1:{1};\n'.format(classname, self.mac) def clean(self, *args, **kwargs): validate_glue = kwargs.pop('validate_glue', True) super(StaticInterface, self).clean(validate_glue=False, ignore_intr=True) from cyder.cydns.ptr.models import PTR if PTR.objects.filter(ip_str=self.ip_str, fqdn=self.fqdn).exists(): raise ValidationError("A PTR already uses '%s' and '%s'" % (self.fqdn, self.ip_str)) if AddressRecord.objects.filter(ip_str=self.ip_str, fqdn=self.fqdn).exists(): raise ValidationError("An A record already uses '%s' and '%s'" % (self.fqdn, self.ip_str)) if validate_glue: self.check_glue_status() if self.dhcp_enabled: if not (self.range and self.range.range_type == STATIC): raise ValidationError('DHCP is enabled for this interface, so ' 'its IP must be in a static range.') def check_glue_status(self): """If this interface is a 'glue' record for a Nameserver instance, do not allow modifications to this record. The Nameserver will need to point to a different record before this record can be updated. """ if self.pk is None: return # First get this object from the database and compare it to the # Nameserver object about to be saved. db_self = StaticInterface.objects.get(pk=self.pk) if db_self.label == self.label and db_self.domain == self.domain: return # The label of the domain changed. Make sure it's not a glue record. from cyder.cydns.nameserver.models import Nameserver if Nameserver.objects.filter(intr_glue=self).exists(): raise ValidationError( "This Interface represents a glue record for a " "Nameserver. Change the Nameserver to edit this record.") a_template = _("{bind_name:$lhs_just} {ttl:$ttl_just} " "{rdclass:$rdclass_just}" " {rdtype_clob:$rdtype_just} {ip_str:$rhs_just}") ptr_template = _("{dns_ip:$lhs_just} {ttl:$ttl_just} " "{rdclass:$rdclass_just}" " {rdtype_clob:$rdtype_just} {fqdn:1}.") def bind_render_record(self, pk=False, **kwargs): self.rdtype_clob = kwargs.pop('rdtype', 'INTR') if kwargs.pop('reverse', False): self.template = self.ptr_template self.dns_ip = ip_to_reverse_name(self.ip_str) + '.' else: self.template = self.a_template return super(StaticInterface, self).bind_render_record(pk=pk, **kwargs)
def get_page_description(self): return _("An HSV Square which can be rotated to show different hues.")
def get_name(cls): return _(u"Freehand Drawing")
def _update_tooltips(self): self.__ring.set_tooltip_text(_("HSV Hue")) self.__square.set_tooltip_text(_("HSV Saturation and Value"))
def convert_to_unit(self, px, unit): if unit == _('px'): return px return px * UnitAdjustment.CONVERT_UNITS[unit][0] / self.dpi
def get_usage(self): return _(u"Paint free-form brush strokes")