def dformat(data, indent=0): padding = ' ' * indent from uio import StringIO buffer = StringIO() for key in sorted(data.keys()): value = data[key] buffer.write('{}{}: {}\n'.format(padding, key, value)) return buffer.getvalue()
def pack_map_pairs(self, pairs): self._pack_map_pairs(len(pairs), pairs) ret = self._buffer.getvalue() if self._autoreset: self._buffer = StringIO() elif USING_STRINGBUILDER: self._buffer = StringIO(ret) return ret
def print_bootscreen(self): """ Print bootscreen. This contains important details about your device and the operating system running on it. """ if not self.settings.get('main.logging.enabled', False): return # Todo: Maybe refactor to TerkinDatalogger. from uio import StringIO buffer = StringIO() def add(item=''): buffer.write(item) buffer.write('\n') # Program name and version. title = '{} {}'.format(self.name, self.version) add() add('=' * len(title)) add(title) add('=' * len(title)) # Machine runtime information. add('CPU freq {} MHz'.format(machine.freq() / 1000000)) add('Device id {}'.format(self.device_id)) add() # System memory info (in bytes) if hasattr(machine, 'info'): machine.info() add() # TODO: Python runtime information. add('{:8}: {}'.format('Python', sys.version)) """ >>> import os; os.uname() (sysname='FiPy', nodename='FiPy', release='1.20.0.rc7', version='v1.9.4-2833cf5 on 2019-02-08', machine='FiPy with ESP32', lorawan='1.0.2', sigfox='1.0.1') """ runtime_info = os.uname() for key in dir(runtime_info): if key == '__class__': continue value = getattr(runtime_info, key) #print('value:', value) add('{:8}: {}'.format(key, value)) add() add() # Todo: Add program authors, contributors and credits. log.info('\n' + buffer.getvalue())
def exception_str(e): from uio import StringIO s = StringIO() sys.print_exception(e, s) s = s.getvalue().split('\n') l = len(s) line = s[l - 3].split(',')[1].strip() error = s[l - 2].strip() return "Error in " + line + "\n" + error
def pack_map_header(self, n): if n >= 2**32: raise PackValueError self._pack_map_header(n) ret = self._buffer.getvalue() if self._autoreset: self._buffer = StringIO() elif USING_STRINGBUILDER: self._buffer = StringIO(ret) return ret
def ddformat(data, indent=0): padding = ' ' * indent from uio import StringIO buffer = StringIO() for key in sorted(data.keys()): item = data[key] value = item['value'] text = item.get('description', '') buffer.write('{}{:<40}{:>10} {}\n'.format(padding, key, value, text)) return buffer.getvalue()
def readUntil(self, ch): res = b'' while True: rx_ch = self.read(1) if ord(rx_ch) == 0: return StringIO('null') else: if ord(rx_ch) == ord(ch): return StringIO(res) res += rx_ch
def pack(self, obj): try: self._pack(obj) except: self._buffer = StringIO() # force reset raise ret = self._buffer.getvalue() if self._autoreset: self._buffer = StringIO() elif USING_STRINGBUILDER: self._buffer = StringIO(ret) return ret
def ddformat(data, indent=0): """ :param data: :param indent: (Default value = 0) """ padding = ' ' * indent from uio import StringIO buffer = StringIO() for key in sorted(data.keys()): item = data[key] value = item['value'] text = item.get('description', '') buffer.write('{}{:<35}{:>25} {:>25}\n'.format(padding, key, value, text)) return buffer.getvalue()
def __init__(self, default=None, encoding=None, unicode_errors=None, use_single_float=False, autoreset=True, use_bin_type=False, strict_types=False): if encoding is None: encoding = 'utf_8' else: print("encoding is deprecated, Use raw=False instead.", PendingDeprecationWarning) if unicode_errors is None: unicode_errors = 'strict' self._strict_types = strict_types self._use_float = use_single_float self._autoreset = autoreset self._use_bin_type = use_bin_type self._encoding = encoding self._unicode_errors = unicode_errors self._buffer = StringIO() if default is not None: if not callable(default): raise TypeError("default must be callable") self._default = default
def __check(self): import utime from uio import StringIO from uos import dupterm, dupterm_notify exec_fime = "execfile('" + self.name + "')\r\n" dupterm(StringIO(exec_fime)) dupterm_notify(None) bak, last_time = self.__file_time(), utime.ticks_ms() while (self.state): if (utime.ticks_ms() > last_time + 2000): tmp, last_time = self.__file_time(), utime.ticks_ms() if (bak != tmp and lock.acquire()): bak = tmp dupterm(StringIO("\x03\x43")) dupterm_notify(None) dupterm(StringIO(exec_fime)) dupterm_notify(None) lock.release() _thread.exit()
def checkError(type_msg, message): try: s = StringIO() err = sys.print_exception(message, s) msg_complete = str(type_msg) + " - " + str(s.getvalue()) print("Error control: " + str(msg_complete)) saveErrorInFlash(str(type_msg) + str(msg_complete)) utime.sleep(5) if 'I2C bus error' in str(msg_complete): #TODO Sometimes when reading the battery level it says I2C Bus Error. Check solution pass # machine.reset() if 'memory' in str(msg_complete): machine.reset() except BaseException as e: err = sys.print_exception(e, s) saveErrorInFlash("Error managing error issuer: " + str(s.getvalue())) utime.sleep(5) machine.reset()
def _check_file(): import utime from uio import StringIO from uos import dupterm, dupterm_notify global _file, _state, _time run_cmd = "execfile('%s')\r\n" % (_file) dupterm(StringIO(run_cmd)) dupterm_notify(None) bak, last_time = _file_time(_file), utime.time() while (_state): if (utime.time() > last_time + _time): tmp, last_time = _file_time(_file), utime.time() if (bak != tmp and lock.acquire()): bak = tmp dupterm(StringIO("\x03\x43")) dupterm_notify(None) dupterm(StringIO(run_cmd)) dupterm_notify(None) lock.release() _thread.exit()
def packtabs(self, s): sb = StringIO() for i in range(0, len(s), 8): c = s[i:i + 8] cr = c.rstrip(" ") if (len(c) - len(cr)) > 1: sb.write(cr + "\t") else: sb.write(c) return sb.getvalue()
def parse(xml_str): LINES_TO_STRIP = [ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" ' '"http://www.apple.com/DTDs/PropertyList-1.0.dtd">' ] for line in LINES_TO_STRIP: xml_str = xml_str.replace(line, '') tokenizer = xmltok.tokenize(StringIO(xml_str)) for tok in tokenizer: if tok[0] == xmltok.START_TAG: return read_tag(tokenizer, tok) raise ValueError('Did not get a start tag')
def packtabs(self, s): try: from uio import StringIO except: from _io import StringIO sb = StringIO() for i in range(0, len(s), 8): c = s[i:i + 8] cr = c.rstrip(" ") if (len(c) - len(cr)) > 1: sb.write(cr + "\t") ## Spaces at the end of a section else: sb.write(c) return sb.getvalue()
def test_concat(self): "Test that we can concatenate output and retrieve the objects back out." self._oso(self.test_objects) fob = StringIO() for ob in self.test_objects: dump(ob, fob) fob.seek(0) obs2 = [] try: while True: obs2.append(load(fob)) except EOFError: pass assert obs2 == self.test_objects
def packtabs(self, s): sb = StringIO() for i in range(0, len(s), 8): c = s[i:i + 8] cr = c.rstrip(" ") if (len(c) - len(cr)) > 1: sb.write(cr + "\t") else: sb.write(c) return sb.getvalue()
def expandtabs(s, tab_size=8): if '\t' in s: sb = StringIO() pos = 0 for c in s: if c == '\t': ## tab is seen sb.write(" " * (tab_size - pos % tab_size)) ## replace by space pos += tab_size - pos % tab_size else: sb.write(c) pos += 1 return sb.getvalue(), True else: return s, False
def expandtabs(s): if '\t' in s: sb = StringIO() pos = 0 for c in s: if c == '\t': sb.write(" " * (8 - pos % 8)) pos += 8 - pos % 8 else: sb.write(c) pos += 1 return sb.getvalue(), True else: return s, False
def expandtabs(self, s): if '\t' in s: self.write_tabs = True sb = StringIO() pos = 0 for c in s: if c == '\t': ## tab is seen sb.write(" " * (8 - pos % 8)) ## replace by space pos += 8 - pos % 8 else: sb.write(c) pos += 1 return sb.getvalue() else: return s
def expandtabs(s): if '\t' in s: Editor.tab_seen = 'y' sb = StringIO() pos = 0 for c in s: if c == '\t': ## tab is seen sb.write(" " * (8 - pos % 8)) ## replace by space pos += 8 - pos % 8 else: sb.write(c) pos += 1 return sb.getvalue() else: return s
def to_line_protocol(self): from uio import StringIO stream = StringIO() stream.write(self.name) stream.write(',') def formatDict(dict): first = True for key, value in dict.items(): if not first: stream.write(',') else: first = False arg = '{0}={1}'.format(key, value) stream.write(arg) formatDict(self.tags) stream.write(' ') formatDict(self.fields) return stream.getvalue()
def expandtabs(s): from uio import StringIO if '\t' in s: sb = StringIO() pos = 0 for c in s: if c == '\t': ## tab is seen sb.write(" " * (8 - pos % 8)) ## replace by space pos += 8 - pos % 8 else: sb.write(c) pos += 1 return sb.getvalue() else: return s
def expandtabs(s): if '\t' in s: sb = StringIO() pos = 0 for c in s: if c == '\t': sb.write(" " * (8 - pos % 8)) pos += 8 - pos % 8 else: sb.write(c) pos += 1 return sb.getvalue(), True else: return s, False
def expandtabs(s): try: from uio import StringIO except: from _io import StringIO if '\t' in s: sb = StringIO() pos = 0 for c in s: if c == '\t': sb.write(" " * (8 - pos % 8)) pos += 8 - pos % 8 else: sb.write(c) pos += 1 return sb.getvalue() else: return s
def expandtabs(s): try: from uio import StringIO except: from _io import StringIO if "\t" in s: Editor.tab_seen = "y" sb = StringIO() pos = 0 for c in s: if c == "\t": sb.write(" " * (8 - pos % 8)) pos += 8 - pos % 8 else: sb.write(c) pos += 1 return sb.getvalue() else: return s
def expandtabs(s): try: from uio import StringIO except: from _io import StringIO if '\t' in s: #ifndef BASIC Editor.tab_seen = 'y' #endif sb = StringIO() pos = 0 for c in s: if c == '\t': ## tab is seen sb.write(" " * (8 - pos % 8)) ## replace by space pos += 8 - pos % 8 else: sb.write(c) pos += 1 return sb.getvalue() else: return s
def read_request(request: HttpRequest): # Observations show request payloads are capped at ~4308 bytes. # https://github.com/jczic/MicroWebSrv/issues/51 from uio import StringIO buffer = StringIO() while True: try: log.info('Reading 4000 bytes from network') payload = request.Content if not payload: log.info('Reading finished') raise StopIteration() log.info('Writing {} bytes to buffer'.format(len(payload))) buffer.write(payload) except: break log.info('Rewinding buffer') buffer.seek(0) return buffer
def generate_public_contents(): # Generate public details about wallet. # # simple text format: # key = value # or #comments # but value is JSON from main import settings from public_constants import AF_CLASSIC num_rx = 5 chain = chains.current_chain() with stash.SensitiveValues() as sv: yield ('''\ # Coldcard Wallet Summary File ## For wallet with master key fingerprint: {xfp} Wallet operates on blockchain: {nb} For BIP44, this is coin_type '{ct}', and internally we use symbol {sym} for this blockchain. ## IMPORTANT WARNING Do **not** deposit to any address in this file unless you have a working wallet system that is ready to handle the funds at that address! ## Top-level, 'master' extended public key ('m/'): {xpub} What follows are derived public keys and payment addresses, as may be needed for different systems. '''.format(nb=chain.name, xpub=chain.serialize_public(sv.node), sym=chain.ctype, ct=chain.b44_cointype, xfp=xfp2str(sv.node.my_fingerprint()))) for name, path, addr_fmt in chains.CommonDerivations: if '{coin_type}' in path: path = path.replace('{coin_type}', str(chain.b44_cointype)) if '{' in name: name = name.format(core_name=chain.core_name) show_slip132 = ('Core' not in name) yield ('''## For {name}: {path}\n\n'''.format(name=name, path=path)) yield ( '''First %d receive addresses (account=0, change=0):\n\n''' % num_rx) submaster = None for i in range(num_rx): subpath = path.format(account=0, change=0, idx=i) # find the prefix of the path that is hardneded if "'" in subpath: hard_sub = subpath.rsplit("'", 1)[0] + "'" else: hard_sub = 'm' if hard_sub != submaster: # dump the xpub needed if submaster: yield "\n" node = sv.derive_path(hard_sub, register=False) yield ("%s => %s\n" % (hard_sub, chain.serialize_public(node))) if show_slip132 and addr_fmt != AF_CLASSIC and ( addr_fmt in chain.slip132): yield ( "%s => %s ##SLIP-132##\n" % (hard_sub, chain.serialize_public(node, addr_fmt))) submaster = hard_sub node.blank() del node # show the payment address node = sv.derive_path(subpath, register=False) yield ('%s => %s\n' % (subpath, chain.address(node, addr_fmt))) node.blank() del node yield ('\n\n') from multisig import MultisigWallet if MultisigWallet.exists(): yield '\n# Your Multisig Wallets\n\n' from uio import StringIO for ms in MultisigWallet.get_all(): fp = StringIO() ms.render_export(fp) print("\n---\n", file=fp) yield fp.getvalue() del fp
def render_backup_contents(): # simple text format: # key = value # or #comments # but value is JSON from main import settings, pa rv = StringIO() def COMMENT(val=None): if val: rv.write('\n# %s\n' % val) else: rv.write('\n') def ADD(key, val): rv.write('%s = %s\n' % (key, ujson.dumps(val))) rv.write('# Coldcard backup file! DO NOT CHANGE.\n') chain = chains.current_chain() COMMENT('Private key details: ' + chain.name) with stash.SensitiveValues(for_backup=True) as sv: if sv.mode == 'words': ADD('mnemonic', tcc.bip39.from_data(sv.raw)) if sv.mode == 'master': ADD('bip32_master_key', b2a_hex(sv.raw)) ADD('chain', chain.ctype) ADD('xprv', chain.serialize_private(sv.node)) ADD('xpub', chain.serialize_public(sv.node)) # BTW: everything is really a duplicate of this value ADD('raw_secret', b2a_hex(sv.secret).rstrip(b'0')) if pa.has_duress_pin(): COMMENT('Duress Wallet (informational)') dpk = sv.duress_root() ADD('duress_xprv', chain.serialize_private(dpk)) ADD('duress_xpub', chain.serialize_public(dpk)) if version.has_608: # save the so-called long-secret ADD('long_secret', b2a_hex(pa.ls_fetch())) COMMENT('Firmware version (informational)') date, vers, timestamp = version.get_mpy_version()[0:3] ADD('fw_date', date) ADD('fw_version', vers) ADD('fw_timestamp', timestamp) ADD('serial', version.serial_number()) COMMENT('User preferences') # user preferences for k, v in settings.current.items(): if k[0] == '_': continue # debug stuff in simulator if k == 'xpub': continue # redundant, and wrong if bip39pw if k == 'xfp': continue # redundant, and wrong if bip39pw ADD('setting.' + k, v) if version.has_fatram: import hsm if hsm.hsm_policy_available(): ADD('hsm_policy', hsm.capture_backup()) rv.write('\n# EOF\n') return rv.getvalue()
try: from uio import StringIO import ujson as json except: try: from io import StringIO import json except ImportError: print("SKIP") raise SystemExit s = StringIO() json.dump(False, s) print(s.getvalue()) s = StringIO() json.dump({"a": (2, [3, None])}, s) print(s.getvalue()) # dump to a small-int not allowed try: json.dump(123, 1) except (AttributeError, OSError): # CPython and uPy have different errors print('Exception') # dump to an object not allowed try: json.dump(123, {}) except (AttributeError, OSError): # CPython and uPy have different errors print('Exception')
try: from uio import StringIO import ujson as json except: try: from io import StringIO import json except ImportError: print("SKIP") raise SystemExit s = StringIO() json.dump(False, s) print(s.getvalue()) s = StringIO() json.dump({"a": (2, [3, None])}, s) print(s.getvalue())