class PositionalChoiceCompleter(PositionalCompleter): baseclass() def complete(self, token, parsed, parser, **kwargs): action = self.expected_action(parsed, parser) if action and action.choices: return [value for value in action.choices if value.startswith(token)]
class PathCompleter(PositionalCompleter): """Completes a path name.""" baseclass() @db.ro_transact def complete(self, token, parsed, parser, **kwargs): # If there is still any positional option to complete: if self.expected_action(parsed, parser): base_path = os.path.dirname(token) container = self.context.traverse(base_path) if IContainer.providedBy(container): def suffix(obj): if IContainer.providedBy(follow_symlinks(obj)): return '/' elif ICommand.providedBy(follow_symlinks(obj)): return '*' elif isinstance(obj, Symlink): return '@' else: return '' def name(obj): return os.path.join(base_path, obj.__name__) return [name(obj) + suffix(obj) for obj in container.listcontent() if name(obj).startswith(token)]
class KeywordValueCompleter(ArgSwitchCompleter): """Completes the `value` part of key=value constructs based on the type of the keyword. Currently works only for args which declare an explicit enumeration.""" baseclass() def complete(self, token, parsed, parser, **kwargs): if '=' in token: keyword, value_prefix = token.split('=') action = self.find_action(keyword, parsed, parser) if isinstance(action, GroupDictAction) and action.is_path: subcompleter = KeywordPathSubCompleter(self.context, action.base_path) return subcompleter.complete(token, parsed, parser, **kwargs) if action and action.choices: return [keyword + '=' + value for value in action.choices if value.startswith(value_prefix)] return [] def find_action(self, keyword, parsed, parser): for action_group in parser._action_groups: for action in action_group._group_actions: if action.dest == keyword: return action
class SubscriberSelectedChecker( z3c.menu.ready2go.checker.ViewNameSelectedChecker, grok.MultiAdapter): """Selected checker using a subscription adapter to check view names. In subclass as a ``grok.adapts`` statement like this:: grok.adapts(zope.interface.Interface, icemac.addressbook.browser.interfaces.IAddressBookLayer, zope.interface.Interface, icemac.addressbook.browser.menus.menu.MainMenu, <concrete menu item class>) """ subscriber_interface = NotImplemented grok.baseclass() @property def selected(self): if super(SubscriberSelectedChecker, self).selected: return True view_name = self.view.__name__ context = self.context items = zope.component.subscribers((self, ), self.subscriber_interface) for item in itertools.chain(*items): if isinstance(item, six.string_types): if view_name == item: return True # If item is no view name it has to be an interface: elif item.providedBy(context): return True return False
class View(BaseView): baseclass() context(Interface) responseFactory = Response def url(self, obj, name=None, data=None): """This function does something. Args: obj (object): The ILocation providing object. Kwargs: name (str): . data (dict): . Returns: str. """ return compute_url(self.request, obj, name, data) def application_url(self): return self.request.application_url def flash(self, message, type=BASE_MESSAGE_TYPE): return send(message, type=type) def redirect(self, url, code=302): exception = REDIRECTIONS[code] raise exception(url) def namespace(self): ns = super(View, self).namespace() ns.update(h=format_decimal) return ns
class SameNthWeekdayFromEndInMonthBase(SameNthWeekdayInMonthBase): """Base class for recurrings on the same day nth weekday in month ... ... counting from the end of the month. """ grok.baseclass() n_mapping = { 1: _('last'), 2: _('last but one'), 3: _('last but two'), 4: _('last but three'), 5: _('last but four') } @zope.cachedescriptors.property.Lazy def n_from_end(self): last_of_month = gocept.month.IMonth(self.context).lastOfMonth() return int( math.ceil((last_of_month.day - (self.context.day - 1)) / 7.0)) @property def n(self): return recurrences_of_weekday_in_month( self.context, self.current_month) - self.n_from_end @property def info(self): return _(self.message_id, mapping={ 'recurrence': self.n_mapping[self.n_from_end], 'weekday': self._weekday })
class KeywordPathSubCompleter(PathCompleter): """ Implement a FS path completer which works as subcompleter for the keyworded arguments. """ baseclass() def __init__(self, context, base_path=''): super(KeywordPathSubCompleter, self).__init__(context) self.base_path = base_path @defer.inlineCallbacks def complete(self, token, parsed, parser, **kwargs): self.original_context = self.context self.context = self keyword, value_prefix = token.split('=') res = yield super(KeywordPathSubCompleter, self).complete(value_prefix, parsed, parser, **kwargs) if res is not None: defer.returnValue([keyword + '=' + i for i in res]) def traverse(self, path): if not os.path.isabs(path): path = self.base_path + path return self.original_context.traverse(path) def expected_action(self, parsed, parser): return True
class LayoutAware(object): """A mixin to make views aware of layouts. """ grok.baseclass() layout = None def _get_layout(self): wanted = layout.bind().get(self) return zope.component.getMultiAdapter((self.request, self.context), wanted) def __call__(self): self.layout = self._get_layout() mapply(self.update, (), self.request) if self.request.response.getStatus() in (302, 303): # A redirect was triggered somewhere in update(). Don't # continue rendering the template or doing anything else. return return self.layout(self) def default_namespace(self): namespace = super(LayoutAware, self).default_namespace() namespace['layout'] = self.layout return namespace def content(self): template = getattr(self, 'template', None) if template is not None: return self._render_template() return mapply(self.render, (), self.request)
class SaltBase(Adapter): """Base class for all Salt method calls.""" context(ISaltInstalled) baseclass() action = None __executor__ = None # 'sync' and 'async' are left for backwards compatibility with older configs executor_classes = { 'sync': SimpleSaltExecutor, 'async': AsynchronousSaltExecutor, 'simple': SimpleSaltExecutor } @defer.inlineCallbacks def run(self, *args, **kwargs): executor_class = self.__executor__ hostname = yield op.IMinion(self.context).hostname() interaction = db.context(self.context).get('interaction', None) executor = executor_class(hostname, self.action, interaction, timeout=self.timeout) res = yield executor.run(*args, **kwargs) defer.returnValue(res)
class Converter(grok.Adapter): """This adapter works a bit differently: It adapts its context to a separately _configured_ `interface`, and declines if that is not possible; but all adapters are _registered_ for the same basic ICMSContent interface. This way we can retrieve data stored in various DAVPropertyAdapters. """ grok.baseclass() grok.context(zeit.cms.interfaces.ICMSContent) interface = NotImplemented # Subclasses need to register as named adapters to work with # `TMSRepresentation`, e.g. by specifying `grok.name(interface.__name__)` def __new__(cls, context): adapted = cls.interface(context, None) if adapted is None: return None instance = object.__new__(cls) instance.context = adapted instance.content = context return instance def __init__(self, context): pass # self.context has been set by __new__() already. def __call__(self): return {'payload': {}}
class SameWeekdayBase(StaticIntervalBase): """Base class for recurrences on the same weekday.""" grok.baseclass() def _get_start_date(self): return next_date_of_same_weekday(self.context, self.interval_start)
class PositionalCompleter(Completer): """Base class for positional completers.""" baseclass() def expected_action(self, parsed, parser): """Currently expected action. It looks at the cardinalities """ for action_group in parser._action_groups: for action in action_group._group_actions: # For every positional argument: if not action.option_strings: actual = 0 maximum = 0 # Count how many of them we have already. values = getattr(parsed, action.dest, []) if values == action.default: # don't count default values values = [] if not isinstance(values, list): values = [values] actual += len(values) # And the maximum number of expected occurencies. if action.nargs is None: maximum += 1 elif isinstance(action.nargs, int): maximum += action.nargs elif action.nargs == argparse.OPTIONAL: maximum += 1 else: maximum = float('inf') if actual < maximum: return action
class BaseClassPathMapping(component.Subscription): """ Base class for all extjs class path mapping registrations """ component.baseclass() component.context(IApplicationContext) namespace = '' path = ''
class PingProducer(Producer): """An example ping-message producer base class, which: 1) declares transient *direct* exchange *collective.zamqp* 2) declares transient queue *collective.zamqp.connection_id* 3) bind queue to exchange by its name.""" grok.baseclass() exchange = 'collective.zamqp' @property def routing_key(self): return self.queue @property def queue(self): return 'collective.zamqp.%s' % self.connection_id queue_arguments = { 'x-message-ttl': 3600000, # 60 * 60s = 1 minute } serializer = 'text/plain' durable = False
class SameNthWeekdayFromBeginningInMonthBase(SameNthWeekdayInMonthBase): """Base class For recurrings on the same day nth weekday in month counting from the beginning of the month. """ grok.baseclass() n_mapping = { 0: _('1st'), 1: _('2nd'), 2: _('3rd'), 3: _('4th'), 4: _('5th') } @zope.cachedescriptors.property.Lazy def n(self): return int(math.ceil(self.context.day / 7.0)) - 1 @property def info(self): return _(self.message_id, mapping={ 'recurrence': self.n_mapping[self.n], 'weekday': self._weekday })
class ReferenceFactory(zeit.content.article.edit.block.BlockFactory): grok.baseclass() def __call__(self, position=None): block = super(ReferenceFactory, self).__call__(position) block.is_empty = True return block
class LinkColumn(LinkColumn): baseclass() def getLinkURL(self, item): """Setup link url.""" if self.linkName is not None: return '%s/%s' % ( get_absolute_url(item, self.request), self.linkName) return get_absolute_url(item, self.request)
class DependencyBase(grok.Adapter): grok.name('must be set in subclass') grok.baseclass() retract_dependencies = False def get_dependencies(self): return ()
class SetOrMkCmdDynamicArguments(Adapter): """Dynamically creates the key=value arguments for the `set` and `mk` commands depending on the object or type being edited or created. """ implements(IContextualCmdArgumentsSyntax) baseclass() @db.transact def arguments(self, parser, args, rest): parser.declare_argument('keywords', {}) model_or_obj, args_required = ((creatable_models.get(args.type), True) if self.context.name == 'mk' else (self.context.traverse(args.path), False)) schema_fields = get_schema_fields(model_or_obj, marker=getattr( self.context.current_obj, '__contains__', None)) for name, field, schema in schema_fields: if field.readonly: continue field = field.bind(model_or_obj) choices = ([i.value.encode('utf-8') for i in field.vocabulary] if isinstance(field, zope.schema.Choice) else None) type = (int if isinstance(field, zope.schema.Int) else None) kwargs = {} if isinstance(field, Path): kwargs['is_path'] = True base_path = '.' if field.relative_to == Path.PARENT: if self.context.name == 'mk': base_path = self.context.protocol._cwd() else: base_path = canonical_path(model_or_obj.__parent__) kwargs['base_path'] = os.path.join(base_path, field.base_path) parser.add_argument('=%s' % name, required=(args_required and field.required), type=type, action=GroupDictAction, group='keywords', help=field.title.encode('utf8'), choices=choices, **kwargs) return parser
class BlockFactory(zeit.edit.block.ElementFactory): grok.baseclass() grok.context(zeit.content.article.edit.interfaces.IArticleArea) # No title so we are excluded from @@block-factories -- our blocks are # created via the toolbar, and should not appear in the module library. title = None def get_xml(self): return getattr(lxml.objectify.E, self.element_type)()
class DependencyBase(grok.Adapter): grok.implements(zeit.workflow.interfaces.IPublicationDependencies) grok.name('must be set in subclass') grok.baseclass() retract_dependencies = False def get_dependencies(self): return ()
class DayTimeActivity(grok.MultiSubscription): grok.implements(IActivity) grok.adapts(Cave, Mammoth) grok.baseclass() def __init__(self, where, who): self.where = where self.who = who def do(self): print 'nothing'
class MasterdataChildBreadcrumb(Breadcrumb): """Breadcrumb those parent is `masterdata.html`.""" grok.baseclass() @property def parent(self): return zope.component.getMultiAdapter( (icemac.addressbook.interfaces.IAddressBook( self.context), self.request), name='masterdata.html')
class CheckBoxColumn(CheckBoxColumn): baseclass() def isSelected(self, item): v = self.request.form.get(self.getItemKey(item), []) if not isinstance(v, list): # ensure that we have a list which prevents to compare strings v = [v] if self.getItemValue(item) in v: return True return False
class ViewletForm(ViewletForm): baseclass() def namespace(self): namespace = super(ViewletForm, self).namespace() namespace['macro'] = self.getTemplate().macros return namespace def getTemplate(self): template = getMultiAdapter((self, self.request), ITemplate) return template
class SubMenu(Menu): baseclass() context(Interface) viewletmanager(IMenu) def __init__(self, context, request, view, parentmenu=None): Menu.__init__(self, context, request, view) self.parentmenu = parentmenu def update(self): BaseMenu.update(self)
class ContainerInjector(Subscription): implements(IContainerInjector) baseclass() __class__ = None __interfaces__ = () def inject(self): if '__name__' not in self.__class__.__dict__: raise KeyError('__name__ not found in __dict__ of (%s)' % (self.__class__)) return {self.__class__.__dict__['__name__']: self.__class__()}
class HypervisorSshAttachAction(AttachAction): """For consoles that are attached by running a command on the hypervisor host.""" baseclass() @db.ro_transact def _do_connection(self, size): self.write("Attaching to %s. Use ^] to force exit.\n" % self.name) phy = self.context.__parent__.__parent__.__parent__.__parent__ ssh_connect_interactive_shell('root', phy.hostname, 22, self.transport, self._set_channel, size, self.command)
class TablePage(Table, Page): baseclass() context(Interface) def update(self): Table.update(self) def render(self): if self.template: return self.template.render( self, target_language=self.target_language, **self.namespace()) return self.renderTable()
class SignalAction(Action): """Send a given signal""" baseclass() def execute(self, cmd, args): from opennode.oms.zodb import db @db.ro_transact def execute(): self.context.signal(self.__signal__) execute()