Example application that opens a serial device and prints messages to the terminal.
431051
def main():
    
    try:
        # Retrieve the specified serial device.
        device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))

        # Set up an event handler and open the device
        device.on_message += handle_message

        # Override the default SerialDevice baudrate since we're using a USB device
        # over serial in this example.
        with device.open(baudrate=BAUDRATE):
            while True:
                time.sleep(1)

    except Exception as ex:
        print('Exception:', ex)
1062669
async function terminal(initialCommand=null){
    _terminallogger.log('Starting Terminal Mode - press ctrl+c to exit');

    // run initial command before starting terminal session ?
    // start
    await _serialTerminal.passthrough(_options.device, _options.baudrate, initialCommand);
}
207291
def println(msg):
    
    sys.stdout.write(msg)
    sys.stdout.flush()
    sys.stdout.write('\x08' * len(msg))
    sys.stdout.flush()
858619
def main():
    
    my_name = os.path.basename(sys.argv[0])
    if not my_name:
        my_name = "yhsm-validation-server"
    syslog.openlog(my_name, syslog.LOG_PID, syslog.LOG_LOCAL0)

    global args
    args = parse_args()
    args_fixup()

    global hsm
    try:
        hsm = pyhsm.YHSM(device = args.device, debug = args.debug)
    except serial.SerialException, e:
        my_log_message(args, syslog.LOG_ERR, 'Failed opening YubiHSM device "%s" : %s' %(args.device, e))
        return 1

    write_pid_file(args.pid_file)

    try:
        run()
    except KeyboardInterrupt:
        print ""
        print "Shutting down"
        print ""
655238
def _write_to_device_and_return(cmd, ack, device_connection):
    ''''''
    log.debug('Write -> {}'.format(cmd.encode()))
    device_connection.write(cmd.encode())
    response = device_connection.read_until(ack.encode())
    log.debug('Read <- {}'.format(response))
    if ack.encode() not in response:
        raise SerialNoResponse(
            'No response from serial port after {} second(s)'.format(
                device_connection.timeout))
    clean_response = _parse_serial_response(response, ack.encode())
    if clean_response:
        return clean_response.decode()
    return ''
1141436
def run(self, oneshot=False):
        
        if not self.xbee:
            raise ValueError("Either a serial port or an XBee must be provided \
                             to __init__ to execute run()")

        while True:
            self.dispatch(self.xbee.wait_read_frame())

            if oneshot:
                break
102263
def complete_serial_ports(self, text):
        ''''''
        ports = mavutil.auto_detect_serial(preferred_list=preferred_ports)
        return [ p.device for p in ports ]
693576
def get_local_serial():
    ''' 
    '''
    return [x for x in [subprocess.Popen("system_profiler SPHardwareDataType |grep -v tray |awk '/Serial/ {print $4}'", shell=True, stdout=subprocess.PIPE).communicate()[0].strip()] if x]
563411
def _emit_message(cls, message):
        """"""
        sys.stdout.write(message)
        sys.stdout.flush()
831307
def _print_message(self, text, fd=None):
        '''
        
        '''
        # Since we have the async->sync->async problem, queue up and print at exit
        self.root.mesgs.extend(text.split('\n'))
274830
def send_message(adu, serial_port):
    
    serial_port.write(adu)
    serial_port.flush()

    # Check exception ADU (which is shorter than all other responses) first.
    exception_adu_size = 5
    response_error_adu = recv_exactly(serial_port.read, exception_adu_size)
    raise_for_exception_adu(response_error_adu)

    expected_response_size = \
        expected_response_pdu_size_from_request_pdu(adu[1:-2]) + 3
    response_remainder = recv_exactly(
        serial_port.read, expected_response_size - exception_adu_size)

    return parse_response_adu(response_error_adu + response_remainder, adu)
248849
def main():
    """"""

    # Squelch SSL warnings
    logging.captureWarnings(True)
    if six.PY3:
        # These ones get triggered even when capturing warnings is turned on
        warnings.simplefilter('ignore', ResourceWarning)  # pylint:disable=E0602

    # Set the terminal title
    if os.getenv('DISPLAY'):
        title = 'rtv {0}'.format(__version__)
        sys.stdout.write('\x1b]2;{0}\x07'.format(title))
        sys.stdout.flush()

    args = Config.get_args()
    fargs, bindings = Config.get_file(args.get('config'))

    # Apply the file config first, then overwrite with any command line args
    config = Config()
    config.update(**fargs)
    config.update(**args)

    # If key bindings are supplied in the config file, overwrite the defaults
    if bindings:
        config.keymap.set_bindings(bindings)

    if config['copy_config']:
        return copy_default_config()
    if config['copy_mailcap']:
        return copy_default_mailcap()
    if config['list_themes']:
        return Theme.print_themes()

    # Load the browsing history from previous sessions
    config.load_history()

    # Load any previously saved auth session token
    config.load_refresh_token()
    if config['clear_auth']:
        config.delete_refresh_token()

    if config['log']:
        # Log request headers to the file (print hack only works on python 3.x)
        # from http import client
        # _http_logger = logging.getLogger('http.client')
        # client.HTTPConnection.debuglevel = 2
        # def print_to_file(*args, **_):
        #     if args[0] != "header:":
        #         _http_logger.info(' '.join(args))
        # client.print = print_to_file
        logging.basicConfig(
            level=logging.DEBUG,
            filename=config['log'],
            format='%(asctime)s:%(levelname)s:%(filename)s:%(lineno)d:%(message)s')
    else:
        # Add an empty handler so the logger doesn't complain
        logging.root.addHandler(logging.NullHandler())

    # Make sure the locale is UTF-8 for unicode support
    default_locale = locale.setlocale(locale.LC_ALL, '')
    try:
        encoding = locale.getlocale()[1] or locale.getdefaultlocale()[1]
    except ValueError:
        # http://stackoverflow.com/a/19961403
        # OS X on some terminals will set the LC_CTYPE to "UTF-8"
        # (as opposed to something like "en_US.UTF-8") and python
        # doesn't know how to handle it.
        _logger.warning('Error parsing system locale: `%s`,'
                        ' falling back to utf-8', default_locale)
        encoding = 'UTF-8'

    if not encoding or encoding.lower() != 'utf-8':
        text = ('System encoding was detected as (%s) instead of UTF-8'
                ', falling back to ascii only mode' % encoding)
        warnings.warn(text)
        config['ascii'] = True

    if packages.__praw_bundled__:
        praw_info = 'packaged, commit {}'.format(packages.__praw_hash__[:12])
    else:
        praw_info = 'system installed v{}'.format(praw.__version__)

    # Update the webbrowser module's default behavior
    patch_webbrowser()
    if webbrowser_import_warning:
        _logger.warning('webbrowser module was unexpectedly imported before'
                        '$BROWSER could be overwritten')

    # Construct the reddit user agent
    user_agent = docs.AGENT.format(version=__version__)

    debug_info = [
        'rtv version: rtv {}'.format(__version__),
        'rtv module path: {}'.format(os.path.abspath(__file__)),
        'python version: {}'.format(sys.version.replace('\n', ' ')),
        'python executable: {}'.format(sys.executable),
        'praw version: {}'.format(praw_info),
        'locale, encoding: {}, {}'.format(default_locale, encoding),
        'Environment Variables']
    for name, value in [
        ('BROWSER', BROWSER),
        ('DISPLAY', os.getenv('DISPLAY')),
        ('EDITOR', os.getenv('EDITOR')),
        ('LANG', os.getenv('LANG')),
        ('PAGER', os.getenv('PAGER')),
        ('RTV_BROWSER', RTV_BROWSER),
        ('RTV_EDITOR', os.getenv('RTV_EDITOR')),
        ('RTV_PAGER', os.getenv('RTV_PAGER')),
        ('RTV_URLVIEWER', os.getenv('RTV_URLVIEWER')),
        ('TERM', os.getenv('TERM')),
        ('VISUAL', os.getenv('VISUAL')),
        ('XDG_CONFIG_HOME', os.getenv('XDG_CONFIG_HOME')),
        ('XDG_DATA_HOME', os.getenv('XDG_DATA_HOME')),
    ]:
        debug_info.append('  {:<16}: {}'.format(name, value or ''))
    debug_info.append('')
    debug_text = '\n'.join(debug_info)

    _logger.info(debug_text)
    if config['debug_info']:
        print(debug_text)
        return

    try:
        with curses_session() as stdscr:

            term = Terminal(stdscr, config)

            if config['monochrome'] or config['theme'] == 'monochrome':
                _logger.info('Using monochrome theme')
                theme = Theme(use_color=False)
            elif config['theme'] and config['theme'] != 'default':
                _logger.info('Loading theme: %s', config['theme'])
                theme = Theme.from_name(config['theme'])
            else:
                # Set to None to let the terminal figure out which theme
                # to use depending on if colors are supported or not
                theme = None
            term.set_theme(theme)

            with term.loader('Initializing', catch_exception=False):
                reddit = praw.Reddit(user_agent=user_agent,
                                     decode_html_entities=False,
                                     disable_update_check=True,
                                     timeout=10,  # 10 second request timeout
                                     handler=RequestHeaderRateLimiter())

            # Dial the request cache up from 30 seconds to 5 minutes
            # I'm trying this out to make navigation back and forth
            # between pages quicker, it may still need to be fine tuned.
            reddit.config.api_request_delay = 300

            # Authorize on launch if the refresh token is present
            oauth = OAuthHelper(reddit, term, config)
            if config['autologin'] and config.refresh_token:
                oauth.authorize(autologin=True)

            # Open the supplied submission link before opening the subreddit
            if config['link']:
                # Expand shortened urls like https://redd.it/
                # Praw won't accept the shortened versions, add the reddit
                # headers to avoid a 429 response from reddit.com
                url = requests.head(
                    config['link'],
                    headers=reddit.http.headers,
                    allow_redirects=True
                ).url

                page = None
                with term.loader('Loading submission'):
                    try:
                        page = SubmissionPage(reddit, term, config, oauth, url)
                    except Exception as e:
                        _logger.exception(e)
                        raise SubmissionError('Unable to load {0}'.format(url))
                while page:
                    page = page.loop()

            page = None
            name = config['subreddit']
            with term.loader('Loading subreddit'):
                try:
                    page = SubredditPage(reddit, term, config, oauth, name)
                except Exception as e:
                    # If we can't load the subreddit that was requested, try
                    # to load the "popular" page instead so at least the
                    # application still launches. This used to use the user's
                    # front page, but some users have an empty front page.
                    _logger.exception(e)
                    page = SubredditPage(reddit, term, config, oauth, 'popular')
                    raise SubredditError('Unable to load {0}'.format(name))

            # Launch the subreddit page
            while page:
                page = page.loop()

    except ConfigError as e:
        _logger.exception(e)
        print(e)
    except Exception as e:
        _logger.exception(e)
        import traceback
        exit_message = '\n'.join([
            debug_text,
            traceback.format_exc(),
            'rtv has crashed. Please report this traceback at:',
            'https://github.com/michael-lazar/rtv/issues\n'])
        sys.stderr.write(exit_message)
        return 1  # General error exception code
    except KeyboardInterrupt:
        pass
    finally:
        # Try to save the browsing history
        config.save_history()
        # Ensure sockets are closed to prevent a ResourceWarning
        if 'reddit' in locals():
            reddit.handler.http.close()
320421
def main(args=None):
    """"""

    Config.options, Config.args = parse(args)

    logger()

    if Config.options.aeidon or Config.options.fix:
        start_aeidon()
    else:
        start_srt()

    if Config.options.fix:
        sys.exit(0)

    if not Config.results:
        basenames = [os.path.basename(os.path.abspath(x)) for x in Config.args]
        print('Search of', basenames, 'returned no results.')

        # leave the terminal open long enough to read message
        if Config.options.gui:
            from time import sleep
            sleep(2)
117071
function terminal(devicePath, exitCallback) {
  if (!args.quiet) log("Connecting to '"+devicePath+"'");
  var hadCtrlC = false;
  var hadCR = false;
  var ideServer = undefined;
  process.stdin.setRawMode(true);
  Espruino.Core.Serial.startListening(function(data) {
    data = new Uint8Array(data);
    var dataStr = String.fromCharCode.apply(null, data);
    if (ideServer) ideServer.write(dataStr);

    process.stdout.write(dataStr);
    /* If Espruino responds after a Ctrl-C with anything other
     than a blank prompt, make sure the next Ctrl-C will exit */
    for (var i=0;i<data.length;i++) {
      var ch = data[i];
      if (ch==8) hadCR = true;
      else {
        if (hadCtrlC && (ch!=62 /*>*/ || !hadCR)) {
          //process.stdout.write("\nCTRLC RESET BECAUSE OF "+JSON.stringify(String.fromCharCode.apply(null, data))+"  "+hadCR+" "+ch+"\n");
          hadCtrlC = false;
        }
        hadCR = false;
      }
    }
  });
  Espruino.Core.Serial.open(devicePath, function(status) {
    if (status === undefined) {
      console.error("Unable to connect!");
      return exitCallback();
    }
    if (!args.quiet) log("Connected");
    process.stdin.on('readable', function() {
      var chunk = process.stdin.read();
      if (chunk !== null) {
        chunk = chunk.toString();
        Espruino.Core.Serial.write(chunk);
        // Check for two Ctrl-C in a row (without Espruino doing anything inbetween)
        for (var i=0;i<chunk.length;i++) {
          var ch = chunk.charCodeAt(i);
          if (ch==3) {
            if (hadCtrlC) {
              process.stdout.write("\r\n");
              exitCallback();
            } else {
              // if we had ctrl-c, but didn't receive anything
              setTimeout(function() {
                if (hadCtrlC) process.stdout.write("\nPress Ctrl-C again to exit\n>");
              }, 200);
            }
            hadCtrlC = true;
          }
        }
      }
    });
    process.stdin.on('end', function() {
      console.log("STDIN ended. exiting...");
      exitCallback();
    });

    if (args.ideServer)
      ideServer = startWebIDEServer(function(data) {
        Espruino.Core.Serial.write(data);
      });

    // figure out what code we need to send (if any)
    sendCode(function() {
      if (args.watchFile) sendOnFileChanged();
    });

   }, function() {
     log("\nDisconnected.");
     exitCallback();
   });
}
1057468
def main():
    """"""
    import sys

    output = []
    line = sys.stdin.readline()

    while line:
        line = line.strip("\n")
        output.append(transform(line))

        line = sys.stdin.readline()
    output.reverse()
    print("\n".join(output))
981981
def main():
    """"""
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--url', help='QSUSB URL [http://127.0.0.1:2020]',
                        default='http://127.0.0.1:2020')
    parser.add_argument('--file', help='a test file from /&devices')
    parser.add_argument('--test_ids', help='List of test IDs',
                        default='@0c2700,@0ac2f0')
    args = parser.parse_args()

    if args.file:
        with open(args.file) as data_file:
            data = json.load(data_file)
        qsusb = pyqwikswitch.QSDevices(
            print_devices_change_callback, print_devices_change_callback)
        print_bad_data(data)
        qsusb.set_qs_values(data)
        return

    print('Execute a basic test on server: {}\n'.format(args.url))

    def qs_to_value(key, new):
        print(" --> New value: {}={}".format(key, new))

    qsusb = QSUsb(args.url, 1, qs_to_value)
    print('Version: ' + qsusb.version())
    qsusb.set_qs_values()

    qsusb.listen(print_item_callback, timeout=5)
    print("Started listening")
    try:
        # Do some test while listening
        if args.test_ids and len(args.test_ids) > 0:
            test_devices_set(qsusb.devices, args.test_ids.split(','))

        print("\n\nListening for 60 seconds (test buttons now)\n")
        sleep(60)
    except KeyboardInterrupt:
        pass
    finally:
        qsusb.stop()  # Close all threads
        print("Stopped listening")
476054
function setup() {
  createCanvas(windowWidth, windowHeight);

  // Instantiate our SerialPort object
  serial = new p5.SerialPort();

  // Get a list the ports available
  // You should have a callback defined to see the results
  serial.list();

  // Assuming our Arduino is connected, let's open the connection to it
  // Change this to the name of your arduino's serial port
  serial.open("/dev/cu.usbmodem1411");

  // Here are the callbacks that you can register

  // When we connect to the underlying server
  serial.on('connected', serverConnected);

  // When we get a list of serial ports that are available
  serial.on('list', gotList);
  // OR
  //serial.onList(gotList);

  // When we some data from the serial port
  serial.on('data', gotData);
  // OR
  //serial.onData(gotData);

  // When or if we get an error
  serial.on('error', gotError);
  // OR
  //serial.onError(gotError);

  // When our serial port is opened and ready for read/write
  serial.on('open', gotOpen);
  // OR
  //serial.onOpen(gotOpen);

  // Callback to get the raw data, as it comes in for handling yourself
  //serial.on('rawdata', gotRawData);
  // OR
  //serial.onRawData(gotRawData);
}