code stringlengths 1 18.2k |
|---|
and max_order >= self.order: return # Group the pixels by iterating down from the order. At each # order, where all 4 adjacent pixels are present (or we are above # the maximum order) they are replaced with a single pixel in the # next lower order. Otherwise the pixel should appear in the MOC # unless it is already rep... |
whether this order is above the maximum, or # if we have all 4 adjacent pixels. Also do this if # the pixel was already contained at a lower level # so that we can avoid checking the adjacent pixels. if (already_contained or (order > max_order) or (((pixel ^ 1) in pixels) and ((pixel ^ 2) in pixels) and ((pixel ^ 3) in... |
def flattened(self, order=None, include_smaller=True): """Return a flattened pixel collection at a single order.""" if order is None: order = self.order else: order = self._validate_order(order) # Start with the cells which are already at this order. flat = set(self[order]) # Look at lower orders and expand them into t... |
def read(self, filename, filetype=None, include_meta=False, **kwargs): """Read data from the given file into the MOC object. The cell lists read from the file are added to the current object. Therefore if the object already contains some cells, it will be updated to represent the union of the current coverge and that f... |
or read_moc_ascii). """ if filetype is not None: filetype = filetype.lower() else: filetype = self._guess_file_type(filename) if filetype == 'fits': from .io.fits import read_moc_fits read_moc_fits(self, filename, include_meta, **kwargs) elif filetype == 'json': from .io.json import read_moc_json read_moc_json(self, fi... |
def write(self, filename, filetype=None, **kwargs): """Write the coverage data in the MOC object to a file. The filetype can be given or left to be inferred as for the read method. Any additional keyword arguments (kwargs) are passed on to the corresponding pymoc.io write functions (write_moc_fits, write_moc_json or wr... |
def _guess_file_type(self, filename): """Attempt to guess the type of a MOC file. Returns "fits", "json" or "ascii" if successful and raised a ValueError otherwise. """ # First attempt to guess from the file name. namelc = filename.lower() if namelc.endswith('.fits') or namelc.endswith('.fit'): return 'fits' elif namel... |
def _validate_order(self, order): """Check that the given order is valid.""" try: order = int(order) except ValueError as e: raise TypeError('MOC order must be convertable to int') if not 0 <= order <= MAX_ORDER: raise ValueError( 'MOC order must be in range 0-{0}'.format(MAX_ORDER)) return order |
def _validate_cell(self, order, cell): """Check that the given cell is valid. The order is assumed already to have been validated. """ max_cells = self._order_num_cells(order) try: cell = int(cell) except ValueError as e: raise TypeError('MOC cell must be convertable to int') if not 0 <= cell < max_cells: raise ValueEr... |
def webhook2lambda2sqs_handler(event, context): """ Main entry point/handler for the lambda function. Wraps :py:func:`~.handle_event` to ensure that we log detailed information if it raises an exception. :param event: Lambda event that triggered the handler :type event: dict :param context: Lambda function context - se... |
raise Exception('Failed enqueueing all messages') # if success, return the success JSON response return res |
def queues_for_endpoint(event): """ Return the list of queues to publish to for a given endpoint. :param event: Lambda event that triggered the handler :type event: dict :return: list of queues for endpoint :rtype: :std:term:`list` :raises: Exception """ global endpoints # endpoint config that's templated in by generat... |
def msg_body_for_event(event, context): """ Generate the JSON-serialized message body for an event. :param event: Lambda event that triggered the handler :type event: dict :param context: Lambda function context - see http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html :return: JSON-serialized succes... |
def handle_event(event, context): """ Do the actual event handling - try to enqueue the request. :param event: Lambda event that triggered the handler :type event: dict :param context: Lambda function context - see http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html :return: JSON-serialized success r... |
def try_enqueue(conn, queue_name, msg): """ Try to enqueue a message. If it succeeds, return the message ID. :param conn: SQS API connection :type conn: :py:class:`botocore:SQS.Client` :param queue_name: name of queue to put message in :type queue_name: str :param msg: JSON-serialized message body :type msg: str :retur... |
def serializable_dict(d): """ Return a dict like d, but with any un-json-serializable elements removed. """ newd = {} for k in d.keys(): if isinstance(d[k], type({})): newd[k] = serializable_dict(d[k]) continue try: json.dumps({'k': d[k]}) newd[k] = d[k] except: pass # unserializable return newd |
def cmdline(argv=sys.argv[1:]): """ Script for rebasing a text file """ parser = ArgumentParser( description='Rebase a text from his stop words') parser.add_argument('language', help='The language used to rebase') parser.add_argument('source', help='Text file to rebase') options = parser.parse_args(argv) factory = Stop... |
def create(self, data): """Creates new entry in mongo database """ q = self.history.insert_one(data).inserted_id logging.debug(self.history.find_one({"_id":q})) |
def get_url(self, **kwargs): """ Return an url, relative to the request associated with this table. Any keywords arguments provided added to the query string, replacing existing values. """ return build( self._request.path, self._request.GET, self._meta.prefix, **kwargs ) |
def object_list(self): """ Return this table's object_list, transformed (sorted, reversed, filtered, etc) according to its meta options. """ def _sort(ob, ol): reverse = ob.startswith("-") ob = ob[1:] if reverse else ob for column in self.columns: if column.sort_key_fn is not None and column.name == ob: return sorted(o... |
def rows(self): """Return the list of object on the active page.""" return map( lambda o: self._meta.row_class(self, o), self.paginator.page(self._meta.page).object_list ) |
async def spawn(self): """Spawn the command wrapped in this object as a subprocess.""" self._server._pending_set.add(self) await self._server._sem.acquire() self._subprocess = await asyncio.create_subprocess_shell( self._cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) self._began_at = datetime.now(... |
async def wait_done(self) -> int: """Coroutine to wait for subprocess run completion. Returns: The exit code of the subprocess. """ await self._done_running_evt.wait() if self._exit_code is None: raise SublemonLifetimeError( 'Subprocess exited abnormally with `None` exit code') return self._exit_code |
def _poll(self) -> None: """Check the status of the wrapped running subprocess. Note: This should only be called on currently-running tasks. """ if self._subprocess is None: raise SublemonLifetimeError( 'Attempted to poll a non-active subprocess') elif self._subprocess.returncode is not None: self._exit_code = self._su... |
async def stdout(self) -> AsyncGenerator[str, None]: """Asynchronous generator for lines from subprocess stdout.""" await self.wait_running() async for line in self._subprocess.stdout: # type: ignore yield line |
async def stderr(self) -> AsyncGenerator[str, None]: """Asynchronous generator for lines from subprocess stderr.""" await self.wait_running() async for line in self._subprocess.stderr: # type: ignore yield line |
def _execute(self, worker): """ This method is ASSIGNED during the evaluation to control how to resume it once it has been paused """ self._assert_status_is(TaskStatus.RUNNING) operation = worker.look_up(self.operation) operation.invoke(self, [], worker=worker) |
def bind_to(self, table, name): """ Bind this column to a table, and assign it a name. This method can only be called once per instance, because a Column cannot be bound to multiple tables. (The sort order would be ambiguous.) """ if self.bound_to is not None: raise AttributeError( "Column is already bound to '%s' as '... |
def value(self, cell): """ Extract the value of ``cell``, ready to be rendered. If this Column was instantiated with a ``value`` attribute, it is called here to provide the value. (For example, to provide a calculated value.) Otherwise, ``cell.value`` is returned. """ if self._value is not None: return self._value(cell... |
def css_class(self, cell): """Return the CSS class for this column.""" if isinstance(self._css_class, basestring): return self._css_class else: return self._css_class(cell) |
def sort_url(self): """ Return the URL to sort the linked table by this column. If the table is already sorted by this column, the order is reversed. Since there is no canonical URL for a table the current URL (via the HttpRequest linked to the Table instance) is reused, and any unrelated parameters will be included in... |
def sort_direction(self): """ Return the direction in which the linked table is is sorted by this column ("asc" or "desc"), or None this column is unsorted. """ if self.table._meta.order_by == self.name: return "asc" elif self.table._meta.order_by == ("-" + self.name): return "desc" else: return None |
def check_or_confirm_overwrite(file_name): """ Returns True if OK to proceed, False otherwise """ try: with open(file_name) as fd: header = next(fd) if header.find(':sedge:') == -1: okay = ask_overwrite(file_name) if okay: backup_file(file_name) else: return False except FileNotFoundError: click.echo("{} not found".for... |
def cli(config, verbose, key_directory, no_verify, output_file, config_file): """ Template and share OpenSSH ssh_config(5) files. A preprocessor for OpenSSH configurations. """ config.verbose = verbose config.key_directory = key_directory config.config_file = config_file config.output_file = output_file config.no_verif... |
def init(config): """ Initialise ~./sedge/config file if none exists. Good for first time sedge usage """ from pkg_resources import resource_stream import shutil config_file = Path(config.config_file) if config_file.is_file(): click.echo('{} already exists, maybe you want $ sedge update'.format(config_file)) sys.exit()... |
def update(config): """ Update ssh config from sedge specification """ def write_to(out): engine.output(out) config_file = Path(config.config_file) if not config_file.is_file(): click.echo('No file {} '.format(config_file), err=True) sys.exit() library = KeyLibrary(config.key_directory) with config_file.open() as fd: e... |
def ftr_get_config(website_url, exact_host_match=False): """ Download the Five Filters config from centralized repositories. Repositories can be local if you need to override siteconfigs. The first entry found is returned. If no configuration is found, `None` is returned. If :mod:`cacheops` is installed, the result wil... |
unicode string) and the hostname matched (unicode string too). :raises: :class:`SiteConfigNotFound` if no config could be found. .. note:: Whatever ``exact_host_match`` value is, the ``www`` part is always removed from the URL or domain name. .. todo:: there is currently no merging/cascading of site configs. In the ori... |
= split_url(website_url) except: host_and_port = website_url host_domain_parts = host_and_port.split(u'.') # we don't store / use the “www.” part of domain name in siteconfig. if host_domain_parts[0] == u'www': host_domain_parts = host_domain_parts[1:] if exact_host_match: domain_names = [u'.'.join(host_domain_parts)] ... |
return result.text, txt_siteconfig_name[:-4] else: filename = os.path.join(repository, txt_siteconfig_name) if os.path.exists(filename): LOGGER.info(u'Using local siteconfig for domain ' u'%s from %s.', domain_name, filename, extra={ 'siteconfig': domain_name}) with codecs.open(filename, 'rb', encoding='utf8') as f: re... |
def ftr_string_to_instance(config_string): """ Return a :class:`SiteConfig` built from a ``config_string``. Simple syntax errors are just plainly ignored, and logged as warnings. :param config_string: a full site config file, raw-loaded from storage with something like ``config_string = open('path/to/site/config.txt', ... |
value and key != 'replace_string'): LOGGER.warning(u'Empty key or value in “%s” on line #%s.', line_content, line_number) continue # Commands for which we accept multiple statements. elif key in ( 'title', 'body', 'author', 'date', 'strip', 'strip_id_or_class', 'strip_image_src', 'single_page_link', 'single_page_link_i... |
# These 2 are lists, not sets. config.find_string.append(key[15:-1]) config.replace_string.append(value) else: LOGGER.warning(u'Unsupported directive “%s” on line #%s.', line_content, line_number) find_count = len(config.find_string) replace_count = len(config.replace_string) if find_count != replace_count: raise Inval... |
def reset(self): """ (re)set all attributes to defaults (eg. empty sets or ``None``). """ # Use first matching element as title (0 or more xpath expressions) self.title = OrderedSet() # Use first matching element as body (0 or more xpath expressions) self.body = OrderedSet() # Use first matching element as author (0 or... |
or class attribute. self.strip_id_or_class = OrderedSet() # Strip 0 or more images which contain # these strings in the src attribute. self.strip_image_src = OrderedSet() # Additional HTTP headers to send # NOT YET USED self.http_header = OrderedSet() # For those 3, None means that default will be used. But we need # N... |
pages tend to display the first # page with links to the other pages at the bottom. # # Often there is also a link to a page which displays the entire # article on one page (e.g. 'print view'). # # `single_page_link` should be an XPath expression identifying the # link to that single page. If present and we find a matc... |
# either `libxml` (PHP) / `lxml` (Python) or `html5lib`. Defaults # to `lxml` if None. self.parser = None # Strings to search for in HTML before processing begins. Goes by # pairs with `replace_string`. Not a set because we can have more # than one of the same, to be replaced by different values. self.find_string = [] ... |
def load(self, host, exact_host_match=False): """ Load a config for a hostname or url. This method calls :func:`ftr_get_config` and :meth`append` internally. Refer to their docs for details on parameters. """ # Can raise a SiteConfigNotFound, intentionally bubbled. config_string, host_string = ftr_get_config(host, exac... |
def append(self, newconfig): """ Append another site config to current instance. All ``newconfig`` attributes are appended one by one to ours. Order matters, eg. current instance values will come first when merging. Thus, if you plan to use some sort of global site config with more generic directives, append it last fo... |
# Too bad ordered set has no .union() method. current_set.add(val) setattr(self, attr_name, current_set) # Check for single statement commands; # we do not overwrite existing values. for attr_name in ( 'parser', 'tidy', 'prune', 'autodetect_on_failure' ): if getattr(self, attr_name) is None: if getattr(newconfig, attr_... |
def write_moc_json(moc, filename=None, file=None): """Write a MOC in JSON encoding. Either a filename, or an open file object can be specified. """ moc.normalize() obj = {} for (order, cells) in moc: obj['{0}'.format(order)] = sorted(cells) if file is not None: _write_json(obj, file) else: with open(filename, 'wb') as ... |
def read_moc_json(moc, filename=None, file=None): """Read JSON encoded data into a MOC. Either a filename, or an open file object can be specified. """ if file is not None: obj = _read_json(file) else: with open(filename, 'rb') as f: obj = _read_json(f) for (order, cells) in obj.items(): moc.add(order, cells) |
def normalize(xs): ''' Restrict xs into the interval (0, 1) via a linear transformation as long as len(xs) > 1, 0 and 1 will be elements of the resulting array ''' x_min, x_max = np.min(xs), np.max(xs) return (xs - x_min) / (x_max - x_min) |
def gloss(alignments, prefixes=None, postfixes=None, width=None, toksep=' ', linesep='\n', groupsep='\n'): ''' Creates an interlinear gloss (for pairs of tokens/types, POS-tags, labels, etc.) Take a list of [('a', 'DET'), ('beluga', 'N')] and return a string covering multiples lines, like: a beluga DET N each item in `... |
postfixes: lines = [line + postfix for postfix, line in zip(postfixes, lines)] groups.append(linesep.join(lines)) return [[] for _ in alignments[0]] # the line_buffer is an N-long list of lists of tokens (strings) # [[e1, e2, e3], [f1, f2, f3], [g1, g2, g3]] line_buffer = flush_buffer([]) # the line_buffer_width is jus... |
def get_queryset(self): """ For reducing the query count the queryset is expanded with `prefetch_related` and `select_related` depending on the specified fields and nested fields """ self.queryset = super(CustomFieldsMixin, self).get_queryset() serializer_class = self.get_serializer_class() if hasattr(serializer_class.... |
async def read(self, *_id): """Read data from database table. Accepts ids of entries. Returns list of results if success or string with error code and explanation. read(*id) => [(result), (result)] (if success) read(*id) => [] (if missed) read() => {"error":400, "reason":"Missed required fields"} """ if not _id: return... |
async def insert(self, **kwargs): """ Accepts request object, retrieves data from the one`s body and creates new account. """ if kwargs: # Create autoincrement for account pk = await self.autoincrement() kwargs.update({"id": pk}) # Create account with received data and autoincrement await self.collection.insert_one(kwa... |
async def find(self, **kwargs): """Find all entries with given search key. Accepts named parameter key and arbitrary values. Returns list of entry id`s. find(**kwargs) => document (if exist) find(**kwargs) => {"error":404,"reason":"Not found"} (if does not exist) find() => {"error":400, "reason":"Missed required fields... |
async def update(self, _id=None, **new_data): """Updates fields values. Accepts id of sigle entry and fields with values. update(id, **kwargs) => {"success":200, "reason":"Updated"} (if success) update(id, **kwargs) => {"error":400, "reason":"Missed required fields"} (if error) """ if not _id or not new_data: return {"... |
async def delete(self, _id=None): """Delete entry from database table. Accepts id. delete(id) => 1 (if exists) delete(id) => {"error":404, "reason":"Not found"} (if does not exist) delete() => {"error":400, "reason":"Missed required fields"} """ if not _id: return {"error":400, "reason":"Missed required fields"} docume... |
def parse_refresh_header(self, refresh): """ >>> parse_refresh_header("1; url=http://example.com/") (1.0, 'http://example.com/') >>> parse_refresh_header("1; url='http://example.com/'") (1.0, 'http://example.com/') >>> parse_refresh_header("1") (1.0, None) >>> parse_refresh_header("blah") # doctest: +IGNORE_EXCEPTION_D... |
def extract(self, html): "Extract http-equiv refresh url to follow." extracted = {} soup = BeautifulSoup(html, parser) for meta_tag in soup.find_all('meta'): if self.key_attr in meta_tag.attrs and 'content' in meta_tag.attrs and \ meta_tag[self.key_attr].lower() == self.val_attr: refresh = meta_tag.attrs['content'] try... |
def request(self, *args, **kwargs): """Overrided method. Returns jsonrpc response or fetches exception? returns appropriate data to client and response mail to administrator. """ try: import settings with open(os.path.join(settings.BASE_DIR, "keys.json")) as f: keys = json.load(f) privkey = keys["privkey"] message = js... |
def verify(self): """Abstract method. Signature verifying logic. """ logging.debug("\n\n") logging.debug("[+] -- Verify debugging") logging.debug("\n\n") if self.request.body: logging.debug("\n Request body") logging.debug(self.request.body) data = json.loads(self.request.body) message = json.dumps(data.get("message"))... |
403 error code if not all([message, public_key, signature]): raise tornado.web.HTTPError(403) # If exist - call verifying static method try: logging.debug("\n[] Try block. Verifying") logging.debug(message) logging.debug(signature) logging.debug(public_key) flag = Qtum.verify_message(message, signature, public_key) exc... |
def cli_frontend(ctx, verbose): """ Boussole is a commandline interface to build Sass projects using libsass. Every project will need a settings file containing all needed settings to build it. """ printout = True if verbose == 0: verbose = 1 printout = False # Verbosity is the inverse of logging levels levels = [item ... |
def get_backend_engine(self, name, **kwargs): """ Get backend engine from given name. Args: (string): Path to validate. Raises: boussole.exceptions.SettingsBackendError: If given backend name does not match any available engine. Returns: object: Instance of selected backend engine. """ if name not in self._engines: msg... |
def valid_paths(self, *args): """ Validate that given paths are not the same. Args: (string): Path to validate. Raises: boussole.exceptions.SettingsInvalidError: If there is more than one occurence of the same path. Returns: bool: ``True`` if paths are validated. """ for i, path in enumerate(args, start=0): cp = list(a... |
def expand(self, basedir, config, sourcedir, targetdir, cwd): """ Validate that given paths are not the same. Args: basedir (string): Project base directory used to prepend relative paths. If empty or equal to '.', it will be filled with current directory path. config (string): Settings file path. sourcedir (string): S... |
os.path.isabs(expanded_config): expanded_config = os.path.join(expanded_basedir, expanded_config) if not os.path.isabs(expanded_sourcedir): expanded_sourcedir = os.path.join(expanded_basedir, expanded_sourcedir) if not os.path.isabs(expanded_targetdir): expanded_targetdir = os.path.join(expanded_basedir, expanded_targe... |
def commit(self, sourcedir, targetdir, abs_config, abs_sourcedir, abs_targetdir): """ Commit project structure and configuration file Args: sourcedir (string): Source directory path. targetdir (string): Compiled files target directory path. abs_config (string): Configuration file absolute path. abs_sourcedir (string): ... |
def init(self, basedir, config, sourcedir, targetdir, cwd='', commit=True): """ Init project structure and configuration from given arguments Args: basedir (string): Project base directory used to prepend relative paths. If empty or equal to '.', it will be filled with current directory path. config (string): Settings ... |
required directory structure if commit: self.commit(sourcedir, targetdir, abs_config, abs_sourcedir, abs_targetdir) return { 'basedir': abs_basedir, 'config': abs_config, 'sourcedir': abs_sourcedir, 'targetdir': abs_targetdir, } |
def get_web_drivers(cls, conf, global_capabilities=None): """Prepare 1 selenium driver instance per request browsers :param conf: :param global_capabilities: :return: """ web_drivers = [] if not global_capabilities: global_capabilities = {} else: global_capabilities = deepcopy(global_capabilities) grid_conf = deepcopy(... |
def init_logger(level, printout=True): """ Initialize app logger to configure its level/handler/formatter/etc.. Todo: * A mean to raise click.Abort or sys.exit when CRITICAL is used; Args: level (str): Level name (``debug``, ``info``, etc..). Keyword Arguments: printout (bool): If False, logs will never be outputed. Re... |
def move_if_not_on_dow(original, replacement, dow_not_orig, dow_replacement): """ Return a lambda function. Lambda checks that either the original day does not fall on a given weekday, or that the replacement day does fall on the expected weekday. """ return lambda x: ( (x.hdate.day == original and x.gdate.weekday() !=... |
def create_table(table, data): """ Create table with defined name and fields :return: None """ fields = data['fields'] query = '(' indexed_fields = '' for key, value in fields.items(): non_case_field = value[0][0:value[0].find('(')] if non_case_field == 'int': sign = value[0][value[0].find(',') + 1:-1:].strip() if sign... |
+ f",date Date) ENGINE = MergeTree(date, ({indexed_fields} date), 8192)" client.execute(f"CREATE TABLE {table} {query}") |
def insert_into_table(table, data): """ SQL query for inserting data into table :return: None """ fields = data['fields'] fields['date'] = datetime.datetime.now().date() query = '(' for key in fields.keys(): query += key + ',' query = query[:-1:] + ")" client.execute(f"INSERT INTO {table} {query} VALUES", [tuple(fields... |
def select_from_table(fields, table, query): """ SQL query for selecting data from certain table :return: selected data """ select_data = client.execute(f"SELECT {fields} FROM {table} {query}", with_column_types=True) keys = [i[0] for i in select_data[1]] result = [] for i in range(len(select_data[0])): tmp = [] for j ... |
def plot_moc(moc, order=None, antialias=0, filename=None, projection='cart', color='blue', title='', coord_sys='C', graticule=True, **kwargs): """Plot a MOC using Healpy. This generates a plot of the MOC at the specified order, or the MOC's current order if this is not specified. The MOC is flattened at an order of `or... |
`healpy.visufunc.gnomview`) :param color: color scheme. One of: * `'blue'` * `'green'` * `'red'` * `'black'` :param title: title of the plot. :param coord_sys: Healpy coordinate system code for the desired plot coordinates. One of: * `'C'` --- Celestial (equatorial) * `'G'` --- Galactic * `'E'` --- Ecliptic :param grat... |
plotargs['cmap'] = LinearSegmentedColormap.from_list( 'white-red', ['#FFFFFF', '#FF0000']) elif color == 'black': plotargs['cmap'] = LinearSegmentedColormap.from_list( 'white-black', ['#FFFFFF', '#000000']) else: raise ValueError('Unknown color: {0}'.format(color)) if coord_sys == 'C': pass elif coord_sys == 'G': plota... |
def getTauLambert(n): """Returns a list containing first n digits of Pi """ myTau = tauGenLambert() result = [] if n > 0: result += [next(myTau) for i in range(n)] myTau.close() return result |
def post(self): """Accepts jsorpc post request. Retrieves data from request body. """ # type(data) = dict data = json.loads(self.request.body.decode()) # type(method) = str method = data["method"] # type(params) = dict params = data["params"] if method == "sendmail": response = dispatch([sendmail],{'jsonrpc': '2.0', 'm... |
def make_server(function, port, authkey, qsize=None): """Create a manager containing input and output queues, and a function to map inputs over. A connecting client can read the stored function, apply it to items in the input queue and post back to the output queue :param function: function to apply to inputs :param po... |
def make_client(ip, port, authkey): """Create a manager to connect to our server manager :param ip: ip address of server :param port: port over which to server :param authkey: authorization key """ QueueManager.register('get_job_q') QueueManager.register('get_result_q') QueueManager.register('get_function') QueueManage... |
def compile_command(context, backend, config): """ Compile Sass project sources to CSS """ logger = logging.getLogger("boussole") logger.info(u"Building project") # Discover settings file try: discovering = Discover(backends=[SettingsBackendJson, SettingsBackendYaml]) config_filepath, config_engine = discovering.search... |
Ensure correct exit code if error has occured if errors: raise click.Abort() |
def _checksum(self, packet): '''calculate the XOR checksum of a packet in string format''' xorsum = 0 for s in packet: xorsum ^= ord(s) return xorsum |
def was_packet_accepted(self, packet): '''parse the "command" byte from the response packet to get a "response code"''' self._validatepacket(packet) cmd = ord(packet[2]) if cmd == Vendapin.ACK: # Accepted/Positive Status return True elif cmd == Vendapin.NAK: # Rejected/Negative Status print('NAK - Rejected/Negative Sta... |
def parsedata(self, packet): '''parse the data section of a packet, it can range from 0 to many bytes''' data = [] datalength = ord(packet[3]) position = 4 while position < datalength + 4: data.append(packet[position]) position += 1 return data |
def sendcommand(self, command, datalength=0, data=None): '''send a packet in the vendapin format''' packet = chr(Vendapin.STX) + chr(Vendapin.ADD) + chr(command) + chr(datalength) if datalength > 0: packet += chr(data) packet += chr(Vendapin.ETX) sendpacket = packet + chr(self._checksum(packet)) self._printpacket(sendp... |
def request_status(self): '''request the status of the card dispenser and return the status code''' self.sendcommand(Vendapin.REQUEST_STATUS) # wait for the reply time.sleep(1) response = self.receivepacket() if self.was_packet_accepted(response): return Vendapin.READY else: return self.parsedata(response)[0] |
def dispense(self): '''dispense a card if ready, otherwise throw an Exception''' self.sendcommand(Vendapin.DISPENSE) # wait for the reply time.sleep(1) # parse the reply response = self.receivepacket() print('Vendapin.dispense(): ' + str(response)) if not self.was_packet_accepted(response): raise Exception('DISPENSE pa... |
def reset(self, hard=False): '''reset the card dispense, either soft or hard based on boolean 2nd arg''' if hard: self.sendcommand(Vendapin.RESET, 1, 0x01) time.sleep(2) else: self.sendcommand(Vendapin.RESET) time.sleep(2) # parse the reply response = self.receivepacket() print('Vendapin.reset(soft): ' + str(response)) |
def _validate(self): """ Confirm that we can run terraform (by calling its version action) and then validate the configuration. """ try: out = self._run_tf('version') except: raise Exception('ERROR: executing \'%s version\' failed; is ' 'terraform installed and is the path to it (%s) ' 'correct?' % (self.tf_path, self.... |
try: self._run_tf('validate', ['.']) except Exception as ex: logger.critical("Terraform config validation failed. " "This is almost certainly a bug in " "webhook2lambda2sqs; please re-run with '-vv' and " "open a bug at <https://github.com/jantman/" "webhook2lambda2sqs/issues>. Exception: %s", ex) raise Exception( 'ERR... |
def _args_for_remote(self): """ Generate arguments for 'terraform remote config'. Return None if not present in configuration. :return: list of args for 'terraform remote config' or None :rtype: :std:term:`list` """ conf = self.config.get('terraform_remote_state') if conf is None: return None args = ['-backend=%s' % co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.