internal serial generator
508193
def _generate_serial2(func, args_gen, kw_gen=None, ntasks=None, progkw={},
                      verbose=None, nTasks=None):
    
    if verbose is None:
        verbose = 2
    if ntasks is None:
        ntasks = nTasks
    if ntasks is None:
        ntasks = len(args_gen)
    if verbose > 0:
        print('[ut._generate_serial2] executing %d %s tasks in serial' %
                (ntasks, get_funcname(func)))

    # kw_gen can be a single dict applied to everything
    if kw_gen is None:
        kw_gen = [{}] * ntasks
    if isinstance(kw_gen, dict):
        kw_gen = [kw_gen] * ntasks

    # Get iterator with or without progress
    if verbose > 1:
        lbl = '(sergen) %s: ' % (get_funcname(func),)
        progkw_ = dict(freq=None, bs=True, adjust=False, freq_est='between')
        progkw_.update(progkw)
        args_gen = util_progress.ProgIter(args_gen, length=ntasks, lbl=lbl,
                                          **progkw_)

    for args, kw in zip(args_gen, kw_gen):
        result = func(*args, **kw)
        yield result
46332
def mavlink_packet(self, m):
        ''''''
        if m.get_type() == 'SERIAL_CONTROL':
            data = m.data[:m.count]
            if m.count > 0:
                s = ''.join(str(chr(x)) for x in data)
                if self.mpstate.system == 'Windows':
                    # strip nsh ansi codes
                    s = s.replace("\033[K","")
                sys.stdout.write(s)
                self.last_packet = time.time()
1200834
def frame_generator(self):
        """"""
        if self.input_rate == self.RATE_PROCESS:
            while True:
                yield self.read()
        else:
            while True:
                yield self.read_resampled()
972476
def r12_serial_port(port):
    '''  '''
    return serial.Serial(port, baudrate=BAUD_RATE, parity=PARITY,
                         stopbits=STOP_BITS, bytesize=BYTE_SIZE)
1182723
def gen_blocks(output, ascii_props=False, append=False, prefix=""):
    """"""

    with codecs.open(output, 'a' if append else 'w', 'utf-8') as f:
        if not append:
            f.write(HEADER)
        f.write('%s_blocks = {' % prefix)
        no_block = []
        last = -1

        max_range = MAXASCII if ascii_props else MAXUNICODE
        formatter = bytesformat if ascii_props else uniformat

        with codecs.open(os.path.join(HOME, 'unicodedata', UNIVERSION, 'Blocks.txt'), 'r', 'utf-8') as uf:
            for line in uf:
                if not line.startswith('#'):
                    data = line.split(';')
                    if len(data) < 2:
                        continue
                    block = [int(i, 16) for i in data[0].strip().split('..')]
                    if block[0] > last + 1:
                        if (last + 1) <= max_range:
                            endval = block[0] - 1 if (block[0] - 1) < max_range else max_range
                            no_block.append((last + 1, endval))
                    last = block[1]
                    name = format_name(data[1])
                    inverse_range = []
                    if block[0] > max_range:
                        if ascii_props:
                            f.write('\n    "%s": "",' % name)
                            f.write('\n    "^%s": "%s-%s",' % (name, formatter(0), formatter(max_range)))
                        continue
                    if block[0] > 0:
                        inverse_range.append("%s-%s" % (formatter(0), formatter(block[0] - 1)))
                    if block[1] < max_range:
                        inverse_range.append("%s-%s" % (formatter(block[1] + 1), formatter(max_range)))
                    f.write('\n    "%s": "%s-%s",' % (name, formatter(block[0]), formatter(block[1])))
                    f.write('\n    "^%s": "%s",' % (name, ''.join(inverse_range)))
            if last < max_range:
                if (last + 1) <= max_range:
                    no_block.append((last + 1, max_range))
            last = -1
            no_block_inverse = []
            if not no_block:
                no_block_inverse.append((0, max_range))
            else:
                for piece in no_block:
                    if piece[0] > last + 1:
                        no_block_inverse.append((last + 1, piece[0] - 1))
                    last = piece[1]
            for block, name in ((no_block, 'noblock'), (no_block_inverse, '^noblock')):
                f.write('\n    "%s": "' % name)
                for piece in block:
                    if piece[0] == piece[1]:
                        f.write(formatter(piece[0]))
                    else:
                        f.write("%s-%s" % (formatter(piece[0]), formatter(piece[1])))
                f.write('",')
            f.write('\n}\n')
939791
def raw_on(serial):
    

    def flush_to_msg(serial, msg):
        """Read the rx serial data until we reach an expected message."""
        data = serial.read_until(msg)
        if not data.endswith(msg):
            if COMMAND_LINE_FLAG:
                print(data)
            raise IOError('Could not enter raw REPL.')

    def flush(serial):
        """Flush all rx input without relying on serial.flushInput()."""
        n = serial.inWaiting()
        while n > 0:
            serial.read(n)
            n = serial.inWaiting()

    raw_repl_msg = b'raw REPL; CTRL-B to exit\r\n>'
    # Send CTRL-B to end raw mode if required.
    serial.write(b'\x02')
    # Send CTRL-C three times between pauses to break out of loop.
    for i in range(3):
        serial.write(b'\r\x03')
        time.sleep(0.01)
    flush(serial)
    # Go into raw mode with CTRL-A.
    serial.write(b'\r\x01')
    flush_to_msg(serial, raw_repl_msg)
    # Soft Reset with CTRL-D
    serial.write(b'\x04')
    flush_to_msg(serial, b'soft reboot\r\n')
    # Some MicroPython versions/ports/forks provide a different message after
    # a Soft Reset, check if we are in raw REPL, if not send a CTRL-A again
    data = serial.read_until(raw_repl_msg)
    if not data.endswith(raw_repl_msg):
        serial.write(b'\r\x01')
        flush_to_msg(serial, raw_repl_msg)
    flush(serial)
619282
def generate_binary(outputfname, format_, progname='', binary_files=None, headless_binary_files=None):
    
    global AUTORUN_ADDR

    org, binary = MEMORY.dump()
    if gl.has_errors:
        return

    if binary_files is None:
        binary_files = []

    if headless_binary_files is None:
        headless_binary_files = []

    bin_blocks = []
    for fname in binary_files:
        with api.utils.open_file(fname) as f:
            bin_blocks.append((os.path.basename(fname), f.read()))

    headless_bin_blocks = []
    for fname in headless_binary_files:
        with api.utils.open_file(fname) as f:
            headless_bin_blocks.append(f.read())

    if AUTORUN_ADDR is None:
        AUTORUN_ADDR = org

    if not progname:
        progname = os.path.basename(outputfname)[:10]

    if OPTIONS.use_loader.value:
        import basic  # Minimalist basic tokenizer

        program = basic.Basic()
        if org > 16383:  # Only for zx48k: CLEAR if below 16383
            program.add_line([['CLEAR', org - 1]])
        program.add_line([['LOAD', '""', program.token('CODE')]])

        if OPTIONS.autorun.value:
            program.add_line([['RANDOMIZE', program.token('USR'), AUTORUN_ADDR]])
        else:
            program.add_line([['REM'], ['RANDOMIZE', program.token('USR'), AUTORUN_ADDR]])

    if format_ in ('tap', 'tzx'):
        t = {'tap': outfmt.TAP, 'tzx': outfmt.TZX}[format_]()

        if OPTIONS.use_loader.value:
            t.save_program('loader', program.bytes, line=1)  # Put line 0 to protect against MERGE

        t.save_code(progname, org, binary)
        for name, block in bin_blocks:
            t.save_code(name, 0, block)
        for block in headless_bin_blocks:
            t.standard_block(block)

        t.dump(outputfname)

    else:
        with open(outputfname, 'wb') as f:
            f.write(bytearray(binary))
1123963
def dumps(self, obj):
        '''
        
        '''
        return self.encrypt(self.PICKLE_PAD + self.serial.dumps(obj))
910505
def serialize_transaction(inputs, outputs, lock_time=0, version=1):
    

    # add in the inputs
    serialized_inputs = ''.join([serialize_input(input) for input in inputs])

    # add in the outputs
    serialized_outputs = ''.join([serialize_output(output) for output in outputs])

    return ''.join([
        # add in the version number
        hexlify(struct.pack('<I', version)),
        # add in the number of inputs
        hexlify(variable_length_int(len(inputs))),
        # add in the inputs
        serialized_inputs,
        # add in the number of outputs
        hexlify(variable_length_int(len(outputs))),
        # add in the outputs
        serialized_outputs,
        # add in the lock time
        hexlify(struct.pack('<I', lock_time)),
    ])
468961
def writeGenerator(self, gen):
        
        n = getattr(gen, 'next')

        while True:
            try:
                self.writeElement(n())
            except StopIteration:
                break
87392
def _int_generator(descriptor, bitwidth, unsigned):
    ''
    vals = list(values.get_integers(bitwidth, unsigned))
    return gen.IterValueGenerator(descriptor.name, vals)
834513
def _normalized_serial(self):
        
        if self._serial is None:
            return None
        normalized_serial = self._serial.replace(' ', '_')
        normalized_serial = normalized_serial.replace(':', '-')
        return normalized_serial
38692
def MAVOL_serial(self,days,rev=0):
    
    return self.make_serial(self.stock_vol,days,rev=0)
1053731
def open
			@serial ||= SerialPort.new @port, @rate
			@serial_input = Enumerator.new { |y| loop do
				y.yield @serial.readbyte
			end }
			@connected = true
		end
1057477
def output_capturing():
    """"""
    out = sys.stdout

    sys.stdout = StringIO()

    try:
        yield

    finally:
        sys.stdout = out
117048
def gen_posix(output, is_bytes=False, append=False, prefix=""):
    """"""

    posix_table = {}

    # `Alnum: [a-zA-Z0-9]`
    s = set([x for x in range(0x30, 0x39 + 1)])
    s |= set([x for x in range(0x41, 0x5a + 1)])
    s |= set([x for x in range(0x61, 0x7a + 1)])
    posix_table["alnum"] = list(s)

    # `Alpha: [a-zA-Z]`
    s = set([x for x in range(0x41, 0x5a)])
    s |= set([x for x in range(0x61, 0x7a)])
    posix_table["alpha"] = list(s)

    # `ASCII: [\x00-\x7F]`
    s = set([x for x in range(0, 0x7F + 1)])
    posix_table["ascii"] = list(s)

    # `Blank: [ \t]`
    s = set([0x20, 0x09])
    posix_table["blank"] = list(s)

    # `Cntrl: [\x00-\x1F\x7F]`
    s = set([x for x in range(0, 0x1F + 1)] + [0x7F])
    posix_table["cntrl"] = list(s)

    # `Digit: [0-9]`
    s = set([x for x in range(0x30, 0x39 + 1)])
    posix_table["digit"] = list(s)

    # `Graph: [\x21-\x7E]`
    s = set([x for x in range(0x21, 0x7E + 1)])
    posix_table["graph"] = list(s)

    # `Lower: [a-z]`
    s = set([x for x in range(0x61, 0x7a + 1)])
    posix_table["lower"] = list(s)

    # `Print: [\x20-\x7E]`
    s = set([x for x in range(0x20, 0x7E + 1)])
    posix_table["print"] = list(s)

    # `Punct: [!\"\#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]`
    s = set([x for x in range(0x21, 0x2f + 1)])
    s |= set([x for x in range(0x3a, 0x40 + 1)])
    s |= set([x for x in range(0x5b, 0x60 + 1)])
    s |= set([x for x in range(0x7b, 0x7e + 1)])
    posix_table["punct"] = list(s)

    # `Space: [ \t\r\n\v\f]`
    s = set([x for x in range(0x09, 0x0d + 1)] + [0x20])
    posix_table["space"] = list(s)

    # `Upper: [A-Z]`
    s = set([x for x in range(0x41, 0x5a + 1)])
    posix_table["upper"] = list(s)

    # `XDigit: [A-Fa-f0-9]`
    s = set([x for x in range(0x30, 0x39 + 1)])
    s |= set([x for x in range(0x41, 0x46 + 1)])
    s |= set([x for x in range(0x61, 0x66 + 1)])
    posix_table["xdigit"] = list(s)

    # Convert characters values to ranges
    char2range(posix_table, is_bytes=is_bytes)

    with codecs.open(output, 'a' if append else 'w', 'utf-8') as f:
        if not append:
            f.write(HEADER)
        # Write out the Unicode properties
        f.write('%s_posix_properties = {\n' % prefix)
        count = len(posix_table) - 1
        i = 0
        for k1, v1 in sorted(posix_table.items()):
            f.write('    "%s": "%s"' % (k1, v1))
            if i == count:
                f.write('\n}\n')
            else:
                f.write(',\n')
            i += 1
373528
def json_serial(cls, obj):
        """"""

        if isinstance(obj, datetime):
            serial = obj.isoformat()

        elif issubclass(obj.__class__, enum.Enum):
            serial = obj.value

        elif isinstance(obj, timedelta):
            serial = str(obj)

        elif isinstance(obj, set):
            serial = list(x for x in obj)

        elif isinstance(obj, uuid.UUID):
            serial = str(obj)

        # FIXME: if you want to add one more custom serializer, think twice about `singledispatch`

        else:
            raise TypeError("Type not serializable %s in %s" % (type(obj), obj))

        return serial