code
stringlengths
1
18.2k
one can write:: lockin.calculate(operation='*', constant=1.337) .. note:: Do not use trace, constant and type together. .. note:: The calculation takes some time. Check the status byte to see when the operation is done. A running scan will be paused until the operation is complete. .. warning:: The SR850 will generate ...
def bin(self): """The bin index of this mark. :returns: An integer bin index or None if the mark is inactive. """ bin = self._query(('MBIN?', Integer, Integer), self.idx) return None if bin == -1 else bin
def active(self): """The indices of the active marks.""" # TODO avoid direct usage of transport object. marks = tuple(int(x) for x in transport.ask('MACT').split(',')) return marks[1:]
def query(self, sql, **kwargs): """ Shortcut for GET /v1/query, except with argument format='dataframe' (the default), in which case it will simply wrap the result of the GET query to /v1/query (with format='table') in a `pandas.DataFrame`. """ if 'format' not in kwargs or kwargs['format'] == 'dataframe': resp = self.g...
def put_and_track(self, url, payload, refresh_rate_sec=1): """ Put and track progress, displaying progress bars. May display the wrong progress if 2 things post/put on the same procedure name at the same time. """ if not url.startswith('/v1/procedures'): raise Exception("The only supported route is /v1/procedures") par...
def post_and_track(self, url, payload, refresh_rate_sec=1): """ Post and track progress, displaying progress bars. May display the wrong progress if 2 things post/put on the same procedure name at the same time. """ if not url.startswith('/v1/procedures'): raise Exception("The only supported route is /v1/procedures") i...
def _makeService(self): """ Construct a service for the endpoint as described. """ if self._endpointService is None: _service = service else: _service = self._endpointService return _service( self.description.encode('ascii'), self.factory.getFactory())
def postOptions(self): """ Display details about the ports which already exist. """ store = self.parent.parent.getStore() port = None factories = {} for portType in [TCPPort, SSLPort, StringEndpointPort]: for port in store.query(portType): key = port.factory.storeID if key not in factories: factories[key] = (port.facto...
( port.certificatePath.path,) else: pathPart = 'NO CERTIFICATE' if port.portNumber is not None: portPart = 'port %d' % (port.portNumber,) else: portPart = 'NO PORT' print ' %d) SSL, %s, %s, %s' % ( port.storeID, interface, portPart, pathPart) elif isinstance(port, StringEndpointPort): print ' {:d}) Endpoint {!r}'.forma...
def _delete(self, store, portIDs): """ Try to delete the ports with the given store IDs. @param store: The Axiom store from which to delete items. @param portIDs: A list of Axiom store IDs for TCPPort or SSLPort items. @raise L{SystemExit}: If one of the store IDs does not identify a port item. """ for portID in portID...
def postOptions(self): """ Delete the ports specified with the port-identifier option. """ if self.portIdentifiers: store = self.parent.parent.getStore() store.transact(self._delete, store, self.portIdentifiers) print "Deleted." raise SystemExit(0) else: self.opt_help()
def absl_flags(): """ Extracts absl-py flags that the user has specified and outputs their key-value mapping. By default, extracts only those flags in the current __package__ and mainfile. Useful to put into a trial's param_map. """ # TODO: need same thing for argparse flags_dict = flags.FLAGS.flags_by_module_dict() # ...
def pipeline(pipe=None, name=None, autoexec=False, exit_handler=None): """ This is the foundational function for all of redpipe. Everything goes through here. create pipelines, nest pipelines, get pipelines for a specific name. It all happens here. Here's a simple example: .. code:: python with pipeline() as pipe: pipe...
if pipe is None: return Pipeline(name=name, autoexec=autoexec, exit_handler=exit_handler) try: if pipe.supports_redpipe_pipeline(): return NestedPipeline( parent=pipe, name=name, autoexec=autoexec, exit_handler=exit_handler ) except AttributeError: pass raise InvalidPipeline('check your configuration')
def autoexec(pipe=None, name=None, exit_handler=None): """ create a pipeline with a context that will automatically execute the pipeline upon leaving the context if no exception was raised. :param pipe: :param name: :return: """ return pipeline(pipe=pipe, name=name, autoexec=True, exit_handler=exit_handler)
def _pipeline(self, name): """ Don't call this function directly. Used by the NestedPipeline class when it executes. :param name: :return: """ if name == self.connection_name: return self try: return self._pipelines[name] except KeyError: pipe = Pipeline(name=name, autoexec=True) self._pipelines[name] = pipe return pip...
def execute(self): """ Invoke the redispy pipeline.execute() method and take all the values returned in sequential order of commands and map them to the Future objects we returned when each command was queued inside the pipeline. Also invoke all the callback functions queued up. :param raise_on_error: boolean :return: ...
of these are callable. # there shouldn't be any non-callables. for item, args, kwargs, future in stack: f = getattr(pipe, item) if callable(f): futures.append(future) call_stack.append((f, args, kwargs)) # here's where we actually pass the commands to the # underlying redis-py pipeline() object. for f, args, kwargs in ...
def reset(self): """ cleanup method. get rid of the stack and callbacks. :return: """ self._stack = [] self._callbacks = [] pipes = self._pipelines self._pipelines = {} for pipe in pipes.values(): pipe.reset()
def execute(self): """ execute the commands inside the nested pipeline. This causes all queued up commands to be passed upstream to the parent, including callbacks. The state of this pipeline object gets cleaned up. :return: """ stack = self._stack callbacks = self._callbacks self._stack = [] self._callbacks = [] defer...
def dump_etree_helper(container_name, data, rules, nsmap, attrib): """Convert DataCite JSON format to DataCite XML. JSON should be validated before it is given to to_xml. """ output = etree.Element(container_name, nsmap=nsmap, attrib=attrib) for rule in rules: if rule not in data: continue element = rules[rule](rule, d...
def etree_to_string(root, pretty_print=True, xml_declaration=True, encoding='utf-8'): """Dump XML etree as a string.""" return etree.tostring( root, pretty_print=pretty_print, xml_declaration=xml_declaration, encoding=encoding, ).decode('utf-8')
def rule(self, key): """Decorate as a rule for a key in top level JSON.""" def register(f): self.rules[key] = f return f return register
def from_dataframe(cls, name, df, indices, primary_key=None): """Infer table metadata from a DataFrame""" # ordered list (column_name, column_type) pairs column_types = [] # which columns have nullable values nullable = set() # tag cached database by dataframe's number of rows and columns for column_name in df.columns:...
def detail_parking(self, **kwargs): """Obtain detailed info of a given parking. Args: lang (str): Language code (*es* or *en*). day (int): Day of the month in format DD. The number is automatically padded if it only has one digit. month (int): Month number in format MM. The number is automatically padded if it only has...
message string in case of error. """ # Endpoint parameters date = util.datetime_string( kwargs.get('day', 1), kwargs.get('month', 1), kwargs.get('year', 1970), kwargs.get('hour', 0), kwargs.get('minute', 0) ) params = { 'language': util.language_code(kwargs.get('lang')), 'publicData': True, 'date': date, 'id': kwargs.g...
def detail_poi(self, **kwargs): """Obtain detailed info of a given POI. Args: family (str): Family code of the POI (3 chars). lang (str): Language code (*es* or *en*). id (int): Optional, ID of the POI to query. Passing value -1 will result in information from all POIs. Returns: Status boolean and parsed response (list...
def icon_description(self, **kwargs): """Obtain a list of elements that have an associated icon. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[IconDescription]), or message string in case of error. """ # Endpoint parameters params = {'language': util.language_code(kwa...
def info_parking_poi(self, **kwargs): """Obtain generic information on POIs and parkings. This returns a list of elements in a given radius from the coordinates. Args: radius (int): Radius of the search (in meters). latitude (double): Latitude in decimal degrees. longitude (double): Longitude in decimal degrees. lang (...
automatically padded if it only has one digit. poi_info (list[tuple]): List of tuples with the format ``(list[family], type, category)`` to query. Check the API documentation. min_free (list[int]): Number of free spaces to check. Must have the same length of ``poi_info``. field_codes (list[tuple]): List of tuples with ...
family_categories }, 'coordinate': { 'latitude': str(kwargs.get('latitude', '0.0')), 'longitude': str(kwargs.get('longitude', '0.0')) }, 'dateTimeUse': date, 'language': util.language_code(kwargs.get('lang')), 'minimumPlacesAvailable': { 'lstminimumPlacesAvailable': kwargs.get('min_free', []) }, 'nameFieldCodes': { 'ls...
def list_features(self, **kwargs): """Obtain a list of parkings. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Parking]), or message string in case of error. """ # Endpoint parameters params = { 'language': util.language_code(kwargs.get('lang')), 'publicData': True } ...
def list_parking(self, **kwargs): """Obtain a list of parkings. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Parking]), or message string in case of error. """ # Endpoint parameters url_args = {'lang': util.language_code(kwargs.get('lang'))} # Request result = self.m...
def list_street_poi_parking(self, **kwargs): """Obtain a list of addresses and POIs. This endpoint uses an address to perform the search Args: lang (str): Language code (*es* or *en*). address (str): Address in which to perform the search. Returns: Status boolean and parsed response (list[ParkingPoi]), or message strin...
def list_types_poi(self, **kwargs): """Obtain a list of families, types and categories of POI. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[ParkingPoiType]), or message string in case of error. """ # Endpoint parameters url_args = {'language': util.language_code(kwar...
def readQuotes(self, start, end): ''' read quotes from Yahoo Financial''' if self.symbol is None: LOG.debug('Symbol is None') return [] return self.__yf.getQuotes(self.symbol, start, end)
def deepcopy(value): """ The default copy.deepcopy seems to copy all objects and some are not `copy-able`. We only need to make sure the provided data is a copy per key, object does not need to be copied. """ if not isinstance(value, (dict, list, tuple)): return value if isinstance(value, dict): copy = {} for k, v in v...
def _factory_default(self, confirm=False): """Resets the device to factory defaults. :param confirm: This function should not normally be used, to prevent accidental resets, a confirm value of `True` must be used. """ if confirm is True: self._write(('DFLT', Integer), 99) else: raise ValueError('Reset to factory defaul...
def usernameFromRequest(request): """ Take an HTTP request and return a username of the form <user>@<domain>. @type request: L{inevow.IRequest} @param request: A HTTP request @return: A C{str} """ username = request.args.get('username', [''])[0] if '@' not in username: username = '%s@%s' % ( username, request.getHeader...
def createSessionForKey(self, key, user): """ Create a persistent session in the database. @type key: L{bytes} @param key: The persistent session identifier. @type user: L{bytes} @param user: The username the session will belong to. """ PersistentSession( store=self.store, sessionKey=key, authenticatedAs=user)
def authenticatedUserForKey(self, key): """ Find a persistent session for a user. @type key: L{bytes} @param key: The persistent session identifier. @rtype: L{bytes} or C{None} @return: The avatar ID the session belongs to, or C{None} if no such session exists. """ session = self.store.findFirst( PersistentSession, Per...
def removeSessionWithKey(self, key): """ Remove a persistent session, if it exists. @type key: L{bytes} @param key: The persistent session identifier. """ self.store.query( PersistentSession, PersistentSession.sessionKey == key).deleteFromStore()
def _cleanSessions(self): """ Clean expired sesisons. """ tooOld = extime.Time() - timedelta(seconds=PERSISTENT_SESSION_LIFETIME) self.store.query( PersistentSession, PersistentSession.lastUsed < tooOld).deleteFromStore() self._lastClean = self._clock.seconds()
def _maybeCleanSessions(self): """ Clean expired sessions if it's been long enough since the last clean. """ sinceLast = self._clock.seconds() - self._lastClean if sinceLast > self.sessionCleanFrequency: self._cleanSessions()
def cookieDomainForRequest(self, request): """ Pick a domain to use when setting cookies. @type request: L{nevow.inevow.IRequest} @param request: Request to determine cookie domain for @rtype: C{str} or C{None} @return: Domain name to use when setting cookies, or C{None} to indicate that only the domain in the request ...
return suffix # Subdomains are not enabled, so None is returned to allow the # default restriction, which will enable this cookie only for # the domain in the request, to apply. return None if self._enableSubdomains and host.endswith(suffix): # The request is for a subdomain of a directly recognized # domain and subdom...
+ host # Subdomains are disabled and the domain from the request was not # recognized. Return None to get the default behavior. return None
def savorSessionCookie(self, request): """ Make the session cookie last as long as the persistent session. @type request: L{nevow.inevow.IRequest} @param request: The HTTP request object for the guard login URL. """ cookieValue = request.getSession().uid request.addCookie( self.cookieKey, cookieValue, path='/', max_age...
def login(self, request, session, creds, segments): """ Called to check the credentials of a user. Here we extend guard's implementation to preauthenticate users if they have a valid persistent session. @type request: L{nevow.inevow.IRequest} @param request: The HTTP request being handled. @type session: L{nevow.guard....
create a database session and associate it with this user cookieValue = session.uid if request.args.get('rememberMe'): self.createSessionForKey(cookieValue, creds.username) self.savorSessionCookie(request) return input return ( guard.SessionWrapper.login( self, request, session, creds, segments) .addCallback(cbLoginSuc...
def explicitLogout(self, session): """ Handle a user-requested logout. Here we override guard's behaviour for the logout action to delete the persistent session. In this case the user has explicitly requested a logout, so the persistent session must be deleted to require the user to log in on the next request. @type se...
def getCredentials(self, request): """ Derive credentials from an HTTP request. Override SessionWrapper.getCredentials to add the Host: header to the credentials. This will make web-based virtual hosting work. @type request: L{nevow.inevow.IRequest} @param request: The request being handled. @rtype: L{twisted.cred.cred...
def setTabURLs(tabs, webTranslator): """ Sets the C{linkURL} attribute on each L{Tab} instance in C{tabs} that does not already have it set @param tabs: sequence of L{Tab} instances @param webTranslator: L{xmantissa.ixmantissa.IWebTranslator} implementor @return: None """ for tab in tabs: if not tab.linkURL: tab.linkUR...
def getSelectedTab(tabs, forURL): """ Returns the tab that should be selected when the current resource lives at C{forURL}. Call me after L{setTabURLs} @param tabs: sequence of L{Tab} instances @param forURL: L{nevow.url.URL} @return: L{Tab} instance """ flatTabs = [] def flatten(tabs): for t in tabs: flatTabs.append(t...
def startMenu(translator, navigation, tag): """ Drop-down menu-style navigation view. For each primary navigation element available, a copy of the I{tab} pattern will be loaded from the tag. It will have its I{href} slot filled with the URL for that navigation item. It will have its I{name} slot filled with the user-vi...
tabs: if tab.children: kids = getp('subtabs').fillSlots('kids', fillSlots(tab.children)) else: kids = '' yield dictFillSlots(getp('tab'), dict(href=tab.linkURL, name=tab.name, kids=kids)) return tag.fillSlots('tabs', fillSlots(navigation))
def applicationNavigation(ctx, translator, navigation): """ Horizontal, primary-only navigation view. For the navigation element currently being viewed, copies of the I{selected-app-tab} and I{selected-tab-contents} patterns will be loaded from the tag. For all other navigation elements, copies of the I{app-tab} and I{...
= IQ(ctx.tag).onePattern tabs = [] for tab in navigation: if tab == selectedTab or selectedTab in tab.children: p = 'selected-app-tab' contentp = 'selected-tab-contents' else: p = 'app-tab' contentp = 'tab-contents' childTabs = [] for subtab in tab.children: try: subtabp = getp("subtab") except NodeNotFound: continue c...
def pathFromItem(self, item, avatar): """ @param item: A thing that we linked to, and such. @return: a list of [child, grandchild, great-grandchild, ...] that indicates a path from me to the navigation for that item, or [] if there is no path from here to there. """ for subnav in self.children: subpath = subnav.pathFro...
def _generate(): """ Generate a new SSH key pair. """ privateKey = rsa.generate_private_key( public_exponent=65537, key_size=4096, backend=default_backend()) return Key(privateKey).toString('openssh')
def getFactory(self): """ Create an L{SSHFactory} which allows access to Mantissa accounts. """ privateKey = Key.fromString(data=self.hostKey) public = privateKey.public() factory = SSHFactory() factory.publicKeys = {'ssh-rsa': public} factory.privateKeys = {'ssh-rsa': privateKey} factory.portal = Portal( IRealm(self.s...
def _draw(self): """ Call the drawing API for the main menu widget with the current known terminal size and the terminal. """ self._window.draw(self._width, self._height, self.terminal)
def reactivate(self): """ Called when a sub-protocol is finished. This disconnects the sub-protocol and redraws the main menu UI. """ self._protocol.connectionLost(None) self._protocol = None self.terminal.reset() self._window.filthy() self._window.repaint()
def switchTo(self, app): """ Use the given L{ITerminalServerFactory} to create a new L{ITerminalProtocol} and connect it to C{self.terminal} (such that it cannot actually disconnect, but can do most anything else). Control of the terminal is delegated to it until it gives up that control by disconnecting itself from th...
def keystrokeReceived(self, keyID, modifier): """ Forward input events to the application-supplied protocol if one is currently active, otherwise forward them to the main menu UI. """ if self._protocol is not None: self._protocol.keystrokeReceived(keyID, modifier) else: self._window.keystrokeReceived(keyID, modifier)
def indirect(self, interface): """ Create an L{IConchUser} avatar which will use L{ShellServer} to interact with the connection. """ if interface is IConchUser: componentized = Componentized() user = _BetterTerminalUser(componentized, None) session = _BetterTerminalSession(componentized) session.transportFactory = Term...
def fetch(self): """ Fetch & return a new `FloatingIP` object representing the floating IP's current state :rtype: FloatingIP :raises DOAPIError: if the API endpoint replies with an error (e.g., if the floating IP no longer exists) """ api = self.doapi_manager return api._floating_ip(api.request(self.url)["floating_ip"...
def assign(self, droplet_id): """ Assign the floating IP to a droplet :param droplet_id: the droplet to assign the floating IP to as either an ID or a `Droplet` object :type droplet_id: integer or `Droplet` :return: an `Action` representing the in-progress operation on the floating IP :rtype: Action :raises DOAPIError:...
def _id(self): r""" The `SSHKey`'s ``id`` field, or if that is not defined, its ``fingerprint`` field. If neither field is defined, accessing this attribute raises a `TypeError`. """ if self.get("id") is not None: return self.id elif self.get("fingerprint") is not None: return self.fingerprint else: raise TypeError('SS...
def fetch(self): """ Fetch & return a new `SSHKey` object representing the SSH key's current state :rtype: SSHKey :raises DOAPIError: if the API endpoint replies with an error (e.g., if the SSH key no longer exists) """ api = self.doapi_manager return api._ssh_key(api.request(self.url)["ssh_key"])
def update_ssh_key(self, name): # The `_ssh_key` is to avoid conflicts with MutableMapping.update. """ Update (i.e., rename) the SSH key :param str name: the new name for the SSH key :return: an updated `SSHKey` object :rtype: SSHKey :raises DOAPIError: if the API endpoint replies with an error """ api = self.doapi_man...
def parse(msg): """ Helper method for parsing a Mongrel2 request string and returning a new `MongrelRequest` instance. """ sender, conn_id, path, rest = msg.split(' ', 3) headers, rest = tnetstring.pop(rest) body, _ = tnetstring.pop(rest) if type(headers) is str: headers = json.loads(headers) return MongrelRequest(send...
def should_close(self): """ Check whether the HTTP connection of this request should be closed after the request is finished. We check for the `Connection` HTTP header and for the HTTP Version (only `HTTP/1.1` supports keep-alive. """ if self.headers.get('connection') == 'close': return True elif 'content-length' in se...
def system_status(self): """The system status codes.""" flag, timestamp, status = self._query(('GETDAT? 1', (Integer, Float, Integer))) return { # convert unix timestamp to datetime object 'timestamp': datetime.datetime.fromtimestamp(timestamp), # bit 0-3 represent the temperature controller status 'temperature': STATU...
def beep(self, duration, frequency): """Generates a beep. :param duration: The duration in seconds, in the range 0.1 to 5. :param frequency: The frequency in Hz, in the range 500 to 5000. """ cmd = 'BEEP', [Float(min=0.1, max=5.0), Integer(min=500, max=5000)] self._write(cmd, duration, frequency)
def move(self, position, slowdown=0): """Move to the specified sample position. :param position: The target position. :param slowdown: The slowdown code, an integer in the range 0 to 14, used to scale the stepper motor speed. 0, the default, is the fastest rate and 14 the slowest. """ cmd = 'MOVE', [Float, Integer, Int...
def move_to_limit(self, position): """Move to limit switch and define it as position. :param position: The new position of the limit switch. """ cmd = 'MOVE', [Float, Integer] self._write(cmd, position, 1)
def redefine_position(self, position): """Redefines the current position to the new position. :param position: The new position. """ cmd = 'MOVE', [Float, Integer] self._write(cmd, position, 2)
def scan_temperature(self, measure, temperature, rate, delay=1): """Performs a temperature scan. Measures until the target temperature is reached. :param measure: A callable called repeatedly until stability at target temperature is reached. :param temperature: The target temperature in kelvin. :param rate: The sweep r...
def scan_field(self, measure, field, rate, mode='persistent', delay=1): """Performs a field scan. Measures until the target field is reached. :param measure: A callable called repeatedly until stability at the target field is reached. :param field: The target field in Oersted. .. note:: The conversion is 1 Oe = 0.1 mT....
does not change. switch_heat_time = datetime.timedelta(seconds=self.magnet_config[5]) start = datetime.datetime.now() while True: now = datetime.datetime.now() if now - start > switch_heat_time: break measure() time.sleep(delay) while True: status = self.system_status['magnet'] if status in ('persistent, stable', 'driv...
def set_field(self, field, rate, approach='linear', mode='persistent', wait_for_stability=True, delay=1): """Sets the magnetic field. :param field: The target field in Oersted. .. note:: The conversion is 1 Oe = 0.1 mT. :param rate: The field rate in Oersted per minute. :param approach: The approach mode, either 'linea...
= self.system_status['magnet'] if status in ('persistent, stable', 'driven, stable'): break time.sleep(delay)
def set_temperature(self, temperature, rate, mode='fast', wait_for_stability=True, delay=1): """Sets the temperature. :param temperature: The target temperature in kelvin. :param rate: The sweep rate in kelvin per minute. :param mode: The sweep mode, either 'fast' or 'no overshoot'. :param wait_for_stability: If wait_f...
def loadgrants(source=None, setspec=None, all_grants=False): """Harvest grants from OpenAIRE. :param source: Load the grants from a local sqlite db (offline). The value of the parameter should be a path to the local file. :type source: str :param setspec: Harvest specific set through OAI-PMH Creates a remote connection...
click.progressbar(loader.iter_grants(), length=cnt) as grants_bar: for grant_json in grants_bar: register_grant.delay(grant_json)
def registergrant(source=None, setspec=None): """Harvest grants from OpenAIRE.""" with open(source, 'r') as fp: data = json.load(fp) register_grant(data)
def dumpgrants(destination, as_json=None, setspec=None): """Harvest grants from OpenAIRE and store them locally.""" if os.path.isfile(destination): click.confirm("Database '{0}' already exists." "Do you want to write to it?".format(destination), abort=True) # no cover dumper = OAIREDumper(destination, setspec=setspec) ...
def postOptions(self): """ Find an installed offering and set the site front page to its application's front page. """ o = self.store.findFirst( offering.InstalledOffering, (offering.InstalledOffering.offeringName == self["name"])) if o is None: raise usage.UsageError("No offering of that name" " is installed.") fp = s...
def _legacySpecialCases(form, patterns, parameter): """ Create a view object for the given parameter. This function implements the remaining view construction logic which has not yet been converted to the C{viewFactory}-style expressed in L{_LiveFormMixin.form}. @type form: L{_LiveFormMixin} @param form: The form fragm...
p, dict(label=parameter.label or parameter.name, input=dictFillSlots(patterns[inputPattern], dict(name=parameter.name, type=parameter.type, value=value)))) p(**{'class' : 'liveform_'+parameter.name}) if parameter.description: description = patterns['description'].fillSlots( 'description', parameter.description) else: d...
def _textParameterToView(parameter): """ Return a L{TextParameterView} adapter for C{TEXT_INPUT}, C{PASSWORD_INPUT}, and C{FORM_INPUT} L{Parameter} instances. """ if parameter.type == TEXT_INPUT: return TextParameterView(parameter) if parameter.type == PASSWORD_INPUT: return PasswordParameterView(parameter) if paramete...
def fromInputs(self, inputs): """ Extract the inputs associated with the child forms of this parameter from the given dictionary and coerce them using C{self.coercer}. @type inputs: C{dict} mapping C{unicode} to C{list} of C{unicode} @param inputs: The contents of a form post, in the conventional structure. @rtype: L{D...
def clone(self, default): """ Make a copy of this parameter, supplying a different default. @type default: C{unicode} or C{NoneType} @param default: A value which will be initially presented in the view as the value for this parameter, or C{None} if no such value is to be presented. @rtype: L{Parameter} """ return self...
def _prepareSubForm(self, liveForm): """ Utility for turning liveforms into subforms, and compacting them as necessary. @param liveForm: a liveform. @type liveForm: L{LiveForm} @return: a sub form. @rtype: L{LiveForm} """ liveForm = liveForm.asSubForm(self.name) # XXX Why did this work??? # if we are compact, tell the ...
def _cloneDefaultedParameter(self, original, default): """ Make a copy of the parameter C{original}, supplying C{default} as the default value. @type original: L{Parameter} or L{ChoiceParameter} @param original: A liveform parameter. @param default: An alternate default value for the parameter. @rtype: L{Parameter} or ...
def _idForObject(self, defaultObject): """ Generate an opaque identifier which can be used to talk about C{defaultObject}. @rtype: C{int} """ identifier = self._allocateID() self._idsToObjects[identifier] = defaultObject return identifier
def _newIdentifier(self): """ Make a new identifier for an as-yet uncreated model object. @rtype: C{int} """ id = self._allocateID() self._idsToObjects[id] = self._NO_OBJECT_MARKER self._lastValues[id] = None return id
def _makeALiveForm(self, parameters, identifier, removable=True): """ Make a live form with the parameters C{parameters}, which will be used to edit the values/model object with identifier C{identifier}. @type parameters: C{list} @param parameters: list of L{Parameter} instances. @type identifier: C{int} @type removabl...
def _makeDefaultLiveForm(self, (defaults, identifier)): """ Make a liveform suitable for editing the set of default values C{defaults}. @type defaults: C{dict} @param defaults: Mapping of parameter names to values. @rtype: L{repeatedLiveFormWrapper} """ parameters = [self._cloneDefaultedParameter(p, defaults[p.name]) f...