INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Render an image
def get_image_field_display(self, field_name, field): """ Render an image """ image = getattr(self.instance, field_name) if image: fltr, _ = Filter.objects.get_or_create(spec='max-400x400') rendition = image.get_rendition(fltr) return rendition.img_tag ...
Render a link to a document
def get_document_field_display(self, field_name, field): """ Render a link to a document """ document = getattr(self.instance, field_name) if document: return mark_safe( '<a href="%s">%s <span class="meta">(%s, %s)</span></a>' % ( document.url, ...
Return a dictionary containing label and value values to display for a field.
def get_dict_for_field(self, field_name): """ Return a dictionary containing `label` and `value` values to display for a field. """ try: field = self.model._meta.get_field(field_name) except FieldDoesNotExist: field = None return { ...
Return a list of label/ value dictionaries to represent the fiels named by the model_admin class s get_inspect_view_fields method
def get_fields_dict(self): """ Return a list of `label`/`value` dictionaries to represent the fiels named by the model_admin class's `get_inspect_view_fields` method """ fields = [] for field_name in self.model_admin.get_inspect_view_fields(): fields.append(se...
Generates the actual list of data.
def items_for_result(view, result): """ Generates the actual list of data. """ model_admin = view.model_admin for field_name in view.list_display: empty_value_display = model_admin.get_empty_value_display() row_classes = ['field-%s' % field_name] try: f, attr, val...
Displays the headers and data list together
def result_list(context): """ Displays the headers and data list together """ view = context['view'] object_list = context['object_list'] headers = list(result_headers(view)) num_sorted_fields = 0 for h in headers: if h['sortable'] and h['sorted']: num_sorted_fields +...
TEAL interface for the acssum function.
def run(configobj=None): """ TEAL interface for the `acssum` function. """ acssum(configobj['input'], configobj['output'], exec_path=configobj['exec_path'], time_stamps=configobj['time_stamps'], verbose=configobj['verbose'], quiet=configobj['quiet'...
Called by: func: detsat.
def _detsat_one(filename, ext, sigma=2.0, low_thresh=0.1, h_thresh=0.5, small_edge=60, line_len=200, line_gap=75, percentile=(4.5, 93.0), buf=200, plot=False, verbose=False): """Called by :func:`detsat`.""" if verbose: t_beg = time.time() fname = '{0}[{1}]'.format(fi...
Give array shape and desired indices return indices that are correctly bounded by the shape.
def _get_valid_indices(shape, ix0, ix1, iy0, iy1): """Give array shape and desired indices, return indices that are correctly bounded by the shape.""" ymax, xmax = shape if ix0 < 0: ix0 = 0 if ix1 > xmax: ix1 = xmax if iy0 < 0: iy0 = 0 if iy1 > ymax: iy1 = ym...
Transform a point from original image coordinates to rotated image coordinates and back. It assumes the rotation point is the center of an image.
def _rotate_point(point, angle, ishape, rshape, reverse=False): """Transform a point from original image coordinates to rotated image coordinates and back. It assumes the rotation point is the center of an image. This works on a simple rotation transformation:: newx = (startx) * np.cos(angle) ...
Create DQ mask for an image for a given satellite trail. This mask can be added to existing DQ data using: func: update_dq.
def make_mask(filename, ext, trail_coords, sublen=75, subwidth=200, order=3, sigma=4, pad=10, plot=False, verbose=False): """Create DQ mask for an image for a given satellite trail. This mask can be added to existing DQ data using :func:`update_dq`. .. note:: Unlike :func:`detsat`, m...
Update the given image and DQ extension with the given satellite trails mask and flag.
def update_dq(filename, ext, mask, dqval=16384, verbose=True): """Update the given image and DQ extension with the given satellite trails mask and flag. Parameters ---------- filename : str FITS image filename to update. ext : int, str, or tuple DQ extension, as accepted by ``a...
Multiprocessing worker.
def _satdet_worker(work_queue, done_queue, sigma=2.0, low_thresh=0.1, h_thresh=0.5, small_edge=60, line_len=200, line_gap=75, percentile=(4.5, 93.0), buf=200): """Multiprocessing worker.""" for fil, chip in iter(work_queue.get, 'STOP'): try: result = _de...
Find satellite trails in the given images and extensions. The trails are calculated using Probabilistic Hough Transform.
def detsat(searchpattern, chips=[1, 4], n_processes=4, sigma=2.0, low_thresh=0.1, h_thresh=0.5, small_edge=60, line_len=200, line_gap=75, percentile=(4.5, 93.0), buf=200, plot=False, verbose=True): """Find satellite trails in the given images and extensions. The trails are calcu...
Decorator for subscribing a function to a specific event.
def on(self, event: str) -> Callable: """ Decorator for subscribing a function to a specific event. :param event: Name of the event to subscribe to. :type event: str :return: The outer function. :rtype: Callable """ def outer(func): self.add_event(f...
Adds a function to a event.
def add_event(self, func: Callable, event: str) -> None: """ Adds a function to a event. :param func: The function to call when event is emitted :type func: Callable :param event: Name of the event. :type event: str """ self._events[event].add(func)
Emit an event and run the subscribed functions.
def emit(self, event: str, *args, **kwargs) -> None: """ Emit an event and run the subscribed functions. :param event: Name of the event. :type event: str .. notes: Passing in threads=True as a kwarg allows to run emitted events as separate threads. This can sig...
Specifically only emits certain subscribed events.
def emit_only(self, event: str, func_names: Union[str, List[str]], *args, **kwargs) -> None: """ Specifically only emits certain subscribed events. :param event: Name of the event. :type event: str :param func_names: Function(s) to emit. :type func_names: Unio...
Decorator that emits events after the function is completed.
def emit_after(self, event: str) -> Callable: """ Decorator that emits events after the function is completed. :param event: Name of the event. :type event: str :return: Callable .. note: This plainly just calls functions without passing params into the ...
Removes a subscribed function from a specific event.
def remove_event(self, func_name: str, event: str) -> None: """ Removes a subscribed function from a specific event. :param func_name: The name of the function to be removed. :type func_name: str :param event: The name of the event. :type event: str :raise EventDoesntE...
Returns an Iterable of the functions subscribed to a event.
def _event_funcs(self, event: str) -> Iterable[Callable]: """ Returns an Iterable of the functions subscribed to a event. :param event: Name of the event. :type event: str :return: A iterable to do things with. :rtype: Iterable """ for func in self._events[event...
Returns string name of each function subscribed to an event.
def _event_func_names(self, event: str) -> List[str]: """ Returns string name of each function subscribed to an event. :param event: Name of the event. :type event: str :return: Names of functions subscribed to a specific event. :rtype: list """ return [func.__n...
Returns the total amount of subscribed events.
def _subscribed_event_count(self) -> int: """ Returns the total amount of subscribed events. :return: Integer amount events. :rtype: int """ event_counter = Counter() # type: Dict[Any, int] for key, values in self._events.items(): event_counter[key] = len(v...
r Remove horizontal stripes from ACS WFC post - SM4 data.
def clean(input, suffix, stat="pmode1", maxiter=15, sigrej=2.0, lower=None, upper=None, binwidth=0.3, mask1=None, mask2=None, dqbits=None, rpt_clean=0, atol=0.01, clobber=False, verbose=True): r"""Remove horizontal stripes from ACS WFC post-SM4 data. Parameters ---------- ...
Clean each input image.
def perform_correction(image, output, stat="pmode1", maxiter=15, sigrej=2.0, lower=None, upper=None, binwidth=0.3, mask=None, dqbits=None, rpt_clean=0, atol=0.01, clobber=False, verbose=True): """ Clean each input image. Parameters --...
Apply destriping algorithm to input array.
def clean_streak(image, stat="pmode1", maxiter=15, sigrej=2.0, lower=None, upper=None, binwidth=0.3, mask=None, rpt_clean=0, atol=0.01, verbose=True): """ Apply destriping algorithm to input array. Parameters ---------- image : `StripeArray` object Arrays a...
Iterative sigma - clipping.
def djs_iterstat(InputArr, MaxIter=10, SigRej=3.0, Max=None, Min=None, Mask=None, lineno=None): """ Iterative sigma-clipping. Parameters ---------- InputArr : `numpy.ndarray` Input image array. MaxIter, SigRej : see `clean` Max, Min : float Max and min val...
TEAL interface for the clean function.
def run(configobj=None): """TEAL interface for the `clean` function.""" clean(configobj['input'], suffix=configobj['suffix'], stat=configobj['stat'], maxiter=configobj['maxiter'], sigrej=configobj['sigrej'], lower=configobj['lower'], upper=configobj['u...
Command line driver.
def main(): """Command line driver.""" import argparse parser = argparse.ArgumentParser( prog=__taskname__, description='Remove horizontal stripes from ACS WFC post-SM4 data.') parser.add_argument( 'arg0', metavar='input', type=str, help='Input file') parser.add_argument( ...
Get the SCI and ERR data.
def configure_arrays(self): """Get the SCI and ERR data.""" self.science = self.hdulist['sci', 1].data self.err = self.hdulist['err', 1].data self.dq = self.hdulist['dq', 1].data if (self.ampstring == 'ABCD'): self.science = np.concatenate( (self.scien...
Process flatfield.
def ingest_flatfield(self): """Process flatfield.""" self.invflat = extract_flatfield( self.hdulist[0].header, self.hdulist[1]) # If BIAS or DARK, set flatfield to unity if self.invflat is None: self.invflat = np.ones_like(self.science) return ...
Process post - flash.
def ingest_flash(self): """Process post-flash.""" self.flash = extract_flash(self.hdulist[0].header, self.hdulist[1]) # Set post-flash to zeros if self.flash is None: self.flash = np.zeros_like(self.science) return # Apply the flash subtraction if neces...
Process dark.
def ingest_dark(self): """Process dark.""" self.dark = extract_dark(self.hdulist[0].header, self.hdulist[1]) # If BIAS or DARK, set dark to zeros if self.dark is None: self.dark = np.zeros_like(self.science) return # Apply the dark subtraction if necess...
Write out the destriped data.
def write_corrected(self, output, clobber=False): """Write out the destriped data.""" # un-apply the flatfield if necessary if self.flatcorr != 'COMPLETE': self.science = self.science / self.invflat self.err = self.err / self.invflat # un-apply the post-flash if...
Run the calacs. e executable as from the shell.
def calacs(input_file, exec_path=None, time_stamps=False, temp_files=False, verbose=False, debug=False, quiet=False, single_core=False, exe_args=None): """ Run the calacs.e executable as from the shell. By default this will run the calacs given by 'calacs.e'. Parameters -----...
TEAL interface for the calacs function.
def run(configobj=None): """ TEAL interface for the `calacs` function. """ calacs(configobj['input_file'], exec_path=configobj['exec_path'], time_stamps=configobj['time_stamps'], temp_files=configobj['temp_files'], verbose=configobj['verbose'], deb...
Return a boolean to indicate whether the supplied user has any permissions at all on the associated model
def has_any_permissions(self, user): """ Return a boolean to indicate whether the supplied user has any permissions at all on the associated model """ for perm in self.get_all_model_permissions(): if self.has_specific_permission(user, perm.codename): r...
Identifies possible parent pages for the current user by first looking at allowed_parent_page_models () on self. model to limit options to the correct type of page then checking permissions on those individual pages to make sure we have permission to add a subpage to it.
def get_valid_parent_pages(self, user): """ Identifies possible parent pages for the current user by first looking at allowed_parent_page_models() on self.model to limit options to the correct type of page, then checking permissions on those individual pages to make sure we have ...
r Run the acsrej. e executable as from the shell.
def acsrej(input, output, exec_path='', time_stamps=False, verbose=False, shadcorr=False, crrejtab='', crmask=False, scalense=None, initgues='', skysub='', crsigmas='', crradius=None, crthresh=None, badinpdq=None, newbias=False, readnoise_only=False, exe_args=None): r""" Run the...
TEAL interface for the acsrej function.
def run(configobj=None): """ TEAL interface for the `acsrej` function. """ acsrej(configobj['input'], configobj['output'], exec_path=configobj['exec_path'], time_stamps=configobj['time_stamps'], verbose=configobj['verbose'], shadcorr=configobj['sha...
Replace os. fork * with wrappers that use ForkSafeLock to acquire all locks before forking and release them afterwards.
def monkeypatch_os_fork_functions(): """ Replace os.fork* with wrappers that use ForkSafeLock to acquire all locks before forking and release them afterwards. """ builtin_function = type(''.join) if hasattr(os, 'fork') and isinstance(os.fork, builtin_function): global _orig_os_fork ...
A Python work - a - like of pthread_atfork. Any time a fork () is called from Python all prepare callables will be called in the order they were registered using this function.
def atfork(prepare=None, parent=None, child=None): """A Python work-a-like of pthread_atfork. Any time a fork() is called from Python, all 'prepare' callables will be called in the order they were registered using this function. After the fork (successful or not), all 'parent' callables will be ca...
Given a list of callables in call_list call them all in order and save and return a list of sys. exc_info () tuples for each exception raised.
def _call_atfork_list(call_list): """ Given a list of callables in call_list, call them all in order and save and return a list of sys.exc_info() tuples for each exception raised. """ exception_list = [] for func in call_list: try: func() except: exception...
Call all parent after fork callables release the lock and print all prepare and parent callback exceptions.
def parent_after_fork_release(): """ Call all parent after fork callables, release the lock and print all prepare and parent callback exceptions. """ prepare_exceptions = list(_prepare_call_exceptions) del _prepare_call_exceptions[:] exceptions = _call_atfork_list(_parent_call_list) _for...
Given a list of sys. exc_info tuples print them all using the traceback module preceeded by a message and separated by a blank line.
def _print_exception_list(exceptions, message, output_file=None): """ Given a list of sys.exc_info tuples, print them all using the traceback module preceeded by a message and separated by a blank line. """ output_file = output_file or sys.stderr message = 'Exception %s:\n' % message for exc...
Wraps os. forkpty () to run atfork handlers.
def os_forkpty_wrapper(): """Wraps os.forkpty() to run atfork handlers.""" pid = None prepare_to_fork_acquire() try: pid, fd = _orig_os_forkpty() finally: if pid == 0: child_after_fork_release() else: parent_after_fork_release() return pid, fd
Wraps an object with a Maybe instance.
def maybe(value): """Wraps an object with a Maybe instance. >>> maybe("I'm a value") Something("I'm a value") >>> maybe(None); Nothing Testing for value: >>> maybe("I'm a value").is_some() True >>> maybe("I'm a value").is_none() False >>> may...
Called after instantiation
def setup(self): '''Called after instantiation''' TelnetHandlerBase.setup(self) # Spawn a greenlet to handle socket input self.greenlet_ic = eventlet.spawn(self.inputcooker) # Note that inputcooker exits on EOF # Sleep for 0.5 second to allow options negotiation ...
Put the cooked data in the input queue ( no locking needed )
def inputcooker_store_queue(self, char): """Put the cooked data in the input queue (no locking needed)""" if type(char) in [type(()), type([]), type("")]: for v in char: self.cookedq.put(v) else: self.cookedq.put(char)
Setup the connection.
def setup(self): '''Setup the connection.''' log.debug( 'New request from address %s, port %d', self.client_address ) try: self.transport.load_server_moduli() except: log.exception( '(Failed to load moduli -- gex will be unsupported.)' ) rais...
Translate this class for use in a StreamServer
def streamserver_handle(cls, socket, address): '''Translate this class for use in a StreamServer''' request = cls.dummy_request() request._sock = socket server = None cls(request, address, server)
Request to start a shell on the given channel
def check_channel_shell_request(self, channel): '''Request to start a shell on the given channel''' try: self.channels[channel].start() except KeyError: log.error('Requested to start a channel (%r) that was not previously set up.', channel) return False ...
Request to allocate a PTY terminal.
def check_channel_pty_request(self, channel, term, width, height, pixelwidth, pixelheight, modes): '''Request to allocate a PTY terminal.''' #self.sshterm = term #print "term: %r, modes: %r" % (term, modes) log.debug('PTY requested. Setting up %r.', sel...
if py3: file_size = int ( u. getheader ( Content - Length ) [ 0 ] ) else: file_size = int ( u. info (). getheaders ( Content - Length ) [ 0 ] )
def download(url, file_name): r = requests.get(url, stream=True) file_size = int(r.headers['Content-length']) ''' if py3: file_size = int(u.getheader("Content-Length")[0]) else: file_size = int(u.info().getheaders("Content-Length")[0]) ''' file_exists = False if...
Request an authentication order. The: py: meth: collect method is used to query the status of the order.
def authenticate( self, end_user_ip, personal_number=None, requirement=None, **kwargs ): """Request an authentication order. The :py:meth:`collect` method is used to query the status of the order. Note that personal number is not needed when authentication is to be done on t...
Request an signing order. The: py: meth: collect method is used to query the status of the order.
def sign( self, end_user_ip, user_visible_data, personal_number=None, requirement=None, user_non_visible_data=None, **kwargs ): """Request an signing order. The :py:meth:`collect` method is used to query the status of the order. Note t...
Collects the result of a sign or auth order using the orderRef as reference.
def collect(self, order_ref): """Collects the result of a sign or auth order using the ``orderRef`` as reference. RP should keep on calling collect every two seconds as long as status indicates pending. RP must abort if status indicates failed. The user identity is returned when...
Cancels an ongoing sign or auth order.
def cancel(self, order_ref): """Cancels an ongoing sign or auth order. This is typically used if the user cancels the order in your service or app. :param order_ref: The UUID string specifying which order to cancel. :type order_ref: str :return: Boolean regarding succes...
Called after instantiation
def setup(self): '''Called after instantiation''' TelnetHandlerBase.setup(self) # Spawn a thread to handle socket input self.thread_ic = threading.Thread(target=self.inputcooker) self.thread_ic.setDaemon(True) self.thread_ic.start() # Note that inputcooker exits o...
Return one character from the input queue
def getc(self, block=True): """Return one character from the input queue""" if not block: if not len(self.cookedq): return '' while not len(self.cookedq): time.sleep(0.05) self.IQUEUELOCK.acquire() ret = self.cookedq[0] self.cookedq...
Put the cooked data in the input queue ( with locking )
def inputcooker_store_queue(self, char): """Put the cooked data in the input queue (with locking)""" self.IQUEUELOCK.acquire() if type(char) in [type(()), type([]), type("")]: for v in char: self.cookedq.append(v) else: self.cookedq.append(char) ...
Put data in output queue rebuild the prompt and entered data
def writemessage(self, text): """Put data in output queue, rebuild the prompt and entered data""" # Need to grab the input queue lock to ensure the entered data doesn't change # before we're done rebuilding it. # Note that writemessage will eventually call writecooked self.IQUEUE...
Put data directly into the output queue
def writecooked(self, text): """Put data directly into the output queue""" # Ensure this is the only thread writing self.OQUEUELOCK.acquire() TelnetHandlerBase.writecooked(self, text) self.OQUEUELOCK.release()
Splits a PKCS12 certificate into Base64 - encoded DER certificate and key.
def split_certificate(certificate_path, destination_folder, password=None): """Splits a PKCS12 certificate into Base64-encoded DER certificate and key. This method splits a potentially password-protected `PKCS12 <https://en.wikipedia.org/wiki/PKCS_12>`_ certificate (format ``.p12`` or ``.pfx``) into on...
Process chars while not in a part
def process_delimiter(self, char): '''Process chars while not in a part''' if char in self.whitespace: return if char in self.quote_chars: # Store the quote type (' or ") and switch to quote processing. self.inquote = char self.process_char = self....
Process chars while in a part
def process_part(self, char): '''Process chars while in a part''' if char in self.whitespace or char == self.eol_char: # End of the part. self.parts.append( ''.join(self.part) ) self.part = [] # Switch back to processing a delimiter. self.proce...
Process character while in a quote
def process_quote(self, char): '''Process character while in a quote''' if char == self.inquote: # Quote is finished, switch to part processing. self.process_char = self.process_part return try: self.part.append(char) except: se...
Handle the char after the escape char
def process_escape(self, char): '''Handle the char after the escape char''' # Always only run once, switch back to the last processor. self.process_char = self.last_process_char if self.part == [] and char in self.whitespace: # Special case where \ is by itself and not at the...
Step through the line and process each character
def process(self, line): '''Step through the line and process each character''' self.raw = self.raw + line try: if not line[-1] == self.eol_char: # Should always be here, but add it just in case. line = line + self.eol_char except IndexError: ...
Translate this class for use in a StreamServer
def streamserver_handle(cls, sock, address): '''Translate this class for use in a StreamServer''' request = cls.false_request() request._sock = sock server = None log.debug("Accepted connection, starting telnet session.") try: cls(request, address, server) ...
Set the curses structures for this terminal
def setterm(self, term): "Set the curses structures for this terminal" log.debug("Setting termtype to %s" % (term, )) curses.setupterm(term) # This will raise if the termtype is not supported self.TERM = term self.ESCSEQ = {} for k in self.KEYS.keys(): str = c...
Connect incoming connection to a telnet session
def setup(self): "Connect incoming connection to a telnet session" try: self.TERM = self.request.term except: pass self.setterm(self.TERM) self.sock = self.request._sock for k in self.DOACK.keys(): self.sendcommand(self.DOACK[k], k) ...
End this session
def finish(self): "End this session" log.debug("Session disconnected.") try: self.sock.shutdown(socket.SHUT_RDWR) except: pass self.session_end()
Negotiate options
def options_handler(self, sock, cmd, opt): "Negotiate options" if cmd == NOP: self.sendcommand(NOP) elif cmd == WILL or cmd == WONT: if self.WILLACK.has_key(opt): self.sendcommand(self.WILLACK[opt], opt) else: self.sendcommand(D...
Send a telnet command ( IAC )
def sendcommand(self, cmd, opt=None): "Send a telnet command (IAC)" if cmd in [DO, DONT]: if not self.DOOPTS.has_key(opt): self.DOOPTS[opt] = None if (((cmd == DO) and (self.DOOPTS[opt] != True)) or ((cmd == DONT) and (self.DOOPTS[opt] != False))): ...
Echo a recieved character move cursor etc...
def _readline_echo(self, char, echo): """Echo a recieved character, move cursor etc...""" if self._readline_do_echo(echo): self.write(char)
Deal properly with inserted chars in a line.
def _readline_insert(self, char, echo, insptr, line): """Deal properly with inserted chars in a line.""" if not self._readline_do_echo(echo): return # Write out the remainder of the line self.write(char + ''.join(line[insptr:])) # Cursor Left to the current insert poi...
Handles reading ANSI escape sequences
def ansi_to_curses(self, char): '''Handles reading ANSI escape sequences''' # ANSI sequences are: # ESC [ <key> # If we see ESC, read a char if char != ESC: return char # If we see [, read another char if self.getc(block=True) != ANSI_START_SEQ: ...
Return a line of text including the terminating LF If echo is true always echo if echo is false never echo If echo is None follow the negotiated setting. prompt is the current prompt to write ( and rewrite if needed ) use_history controls if this current line uses ( and adds to ) the command history.
def readline(self, echo=None, prompt='', use_history=True): """Return a line of text, including the terminating LF If echo is true always echo, if echo is false never echo If echo is None follow the negotiated setting. prompt is the current prompt to write (and rewrite if needed...
Send a packet with line ending.
def writeline(self, text): """Send a packet with line ending.""" log.debug('writing line %r' % text) self.write(text+chr(10))
Write out an asynchronous message then reconstruct the prompt and entered text.
def writemessage(self, text): """Write out an asynchronous message, then reconstruct the prompt and entered text.""" log.debug('writing message %r', text) self.write(chr(10)+text+chr(10)) self.write(self._current_prompt+''.join(self._current_line))
Send a packet to the socket. This function cooks output.
def write(self, text): """Send a packet to the socket. This function cooks output.""" text = str(text) # eliminate any unicode or other snigglets text = text.replace(IAC, IAC+IAC) text = text.replace(chr(10), chr(13)+chr(10)) self.writecooked(text)
Get one character from the raw queue. Optionally blocking. Raise EOFError on end of stream. SHOULD ONLY BE CALLED FROM THE INPUT COOKER.
def _inputcooker_getc(self, block=True): """Get one character from the raw queue. Optionally blocking. Raise EOFError on end of stream. SHOULD ONLY BE CALLED FROM THE INPUT COOKER.""" if self.rawq: ret = self.rawq[0] self.rawq = self.rawq[1:] return re...
Put the cooked data in the correct queue
def _inputcooker_store(self, char): """Put the cooked data in the correct queue""" if self.sb: self.sbdataq = self.sbdataq + char else: self.inputcooker_store_queue(char)
Input Cooker - Transfer from raw queue to cooked queue.
def inputcooker(self): """Input Cooker - Transfer from raw queue to cooked queue. Set self.eof when connection is closed. Don't block unless in the midst of an IAC sequence. """ try: while True: c = self._inputcooker_getc() if not sel...
[ <command > ] Display help Display either brief help on all commands or detailed help on a single command passed as a parameter.
def cmdHELP(self, params): """[<command>] Display help Display either brief help on all commands, or detailed help on a single command passed as a parameter. """ if params: cmd = params[0].upper() if self.COMMANDS.has_key(cmd): meth...
Display the command history
def cmdHISTORY(self, params): """ Display the command history """ cnt = 0 self.writeline('Command history\n') for line in self.history: cnt = cnt + 1 self.writeline("%-5d : %s" % (cnt, ''.join(line)))
Exception handler ( False to abort )
def handleException(self, exc_type, exc_param, exc_tb): "Exception handler (False to abort)" self.writeline(''.join( traceback.format_exception(exc_type, exc_param, exc_tb) )) return True
Checks the authentication and sets the username of the currently connected terminal. Returns True or False
def authentication_ok(self): '''Checks the authentication and sets the username of the currently connected terminal. Returns True or False''' username = None password = None if self.authCallback: if self.authNeedUser: username = self.readline(prompt=self.PROM...
The actual service to which the user has connected.
def handle(self): "The actual service to which the user has connected." if self.TELNET_ISSUE: self.writeline(self.TELNET_ISSUE) if not self.authentication_ok(): return if self.DOECHO: self.writeline(self.WELCOME) self.session_start() w...
Called after instantiation
def setup(self): '''Called after instantiation''' TelnetHandlerBase.setup(self) # Spawn a greenlet to handle socket input self.greenlet_ic = gevent.spawn(self.inputcooker) # Note that inputcooker exits on EOF # Sleep for 0.5 second to allow options negotiation ...
Return one character from the input queue
def getc(self, block=True): """Return one character from the input queue""" try: return self.cookedq.get(block) except gevent.queue.Empty: return ''
Request an authentication order. The: py: meth: collect method is used to query the status of the order.
def authenticate(self, personal_number, **kwargs): """Request an authentication order. The :py:meth:`collect` method is used to query the status of the order. :param personal_number: The Swedish personal number in format YYYYMMDDXXXX. :type personal_number: str :retu...
Request an signing order. The: py: meth: collect method is used to query the status of the order.
def sign(self, user_visible_data, personal_number=None, **kwargs): """Request an signing order. The :py:meth:`collect` method is used to query the status of the order. :param user_visible_data: The information that the end user is requested to sign. :type user_visible_data: ...
Collect the progress status of the order with the specified order reference.
def collect(self, order_ref): """Collect the progress status of the order with the specified order reference. :param order_ref: The UUID string specifying which order to collect status from. :type order_ref: str :return: The CollectResponse parsed to a dictionary. ...
Transforms the replies to a regular Python dict with strings and datetimes.
def _dictify(self, doc): """Transforms the replies to a regular Python dict with strings and datetimes. Tested with BankID version 2.5 return data. :param doc: The response as interpreted by :py:mod:`zeep`. :returns: The response parsed to a dict. :rtype: dict ...
Load all image formats if needed.
def intercept_image_formats(self, options): """ Load all image formats if needed. """ if 'entityTypes' in options: for entity in options['entityTypes']: if entity['type'] == ENTITY_TYPES.IMAGE and 'imageFormats' in entity: if entity['imageF...
Retrieves the normalized timestamp.
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cann...
Copies a POSIX timestamp from a date and time string.
def CopyFromDateTimeString(self, time_string): """Copies a POSIX timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can...
Copies the POSIX timestamp to a date and time string.
def CopyToDateTimeString(self): """Copies the POSIX timestamp to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss" or None if the timestamp is missing. """ if self._timestamp is None: return None number_of_days, hours, minutes, seco...