Run the Simple Packet Printer Example
320228
def run(iface_name=None, bpf=None, summary=None, max_packets=50):
    """"""

    # Create the classes
    streamer = packet_streamer.PacketStreamer(iface_name=iface_name, bpf=bpf, max_packets=max_packets)
    meta = packet_meta.PacketMeta()
    rdns = reverse_dns.ReverseDNS()
    tags = packet_tags.PacketTags()
    tmeta = transport_meta.TransportMeta()
    printer = packet_summary.PacketSummary()

    # Set up the chain
    meta.link(streamer)
    rdns.link(meta)
    tags.link(rdns)
    tmeta.link(tags)
    printer.link(tmeta)

    # Pull the chain
    printer.pull()
774253
def main():
    ""

    actions = """
        {LWIN}
        {PAUSE .25}
        r
        {PAUSE .25}
        Notepad.exe{ENTER}
        {PAUSE 1}
        Hello{SPACE}World!
        {PAUSE 1}
        %{F4}
        {PAUSE .25}
        n
        """
    SendKeys(actions, pause = .1)

    keys = parse_keys(actions)
    for k in keys:
        print(k)
        k.Run()
        time.sleep(.1)

    test_strings = [
        "\n"
        "(aa)some text\n",
        "(a)some{ }text\n",
        "(b)some{{}text\n",
        "(c)some{+}text\n",
        "(d)so%me{ab 4}text",
        "(e)so%me{LEFT 4}text",
        "(f)so%me{ENTER 4}text",
        "(g)so%me{^aa 4}text",
        "(h)some +(asdf)text",
        "(i)some %^+(asdf)text",
        "(j)some %^+a text+",
        "(k)some %^+a tex+{&}",
        "(l)some %^+a tex+(dsf)",
        "",
        ]

    for s in test_strings:
        print(repr(s))
        keys = parse_keys(s, with_newlines = True)
        print(keys)

        for k in keys:
            k.Run()
            time.sleep(.1)
        print()
28000
def _printer(self, *out, **kws):
        """"""
        flush = kws.pop('flush', True)
        fileh = kws.pop('file', self.writer)
        sep = kws.pop('sep', ' ')
        end = kws.pop('sep', '\n')

        print(*out, file=fileh, sep=sep, end=end)
        if flush:
            fileh.flush()
653911
def pprint(object, stream=None, indent=1, width=80, depth=None):
    """"""
    printer = PrettyPrinter(
        stream=stream, indent=indent, width=width, depth=depth)
    printer.pprint(object)
146398
def run():
    '''  '''
    
    # Grab server args
    args = client_helper.grab_server_args()

    # Start up workbench connection
    workbench = zerorpc.Client(timeout=300, heartbeat=60)
    workbench.connect('tcp://'+args['server']+':'+args['port'])

    # Call help methods
    print workbench.help()
    print workbench.help('basic')
    print workbench.help('commands')
    print workbench.help('store_sample')
    print workbench.help('workers')
    print workbench.help('meta')

    # Call a test worker
    print workbench.test_worker('meta')
568993
def print_results(self):
        """"""
        # Updates
        if self.package_data.get('updates'):
            print('\n{}{}Updates:'.format(c.Style.BRIGHT, c.Fore.BLUE))
            for p in self.package_data['updates']:
                print(
                    '{!s:<20}{}{} {!s:<50}'.format(
                        p.get('action'), c.Style.BRIGHT, c.Fore.CYAN, p.get('output')
                    )
                )

        # Packaging
        print('\n{}{}Package:'.format(c.Style.BRIGHT, c.Fore.BLUE))
        for p in self.package_data['package']:
            if isinstance(p.get('output'), list):
                n = 5
                list_data = p.get('output')
                print(
                    '{!s:<20}{}{} {!s:<50}'.format(
                        p.get('action'), c.Style.BRIGHT, c.Fore.CYAN, ', '.join(p.get('output')[:n])
                    )
                )
                del list_data[:n]
                for data in [
                    list_data[i : i + n] for i in range(0, len(list_data), n)  # noqa: E203
                ]:
                    print(
                        '{!s:<20}{}{} {!s:<50}'.format(
                            '', c.Style.BRIGHT, c.Fore.CYAN, ', '.join(data)
                        )
                    )

            else:
                print(
                    '{!s:<20}{}{} {!s:<50}'.format(
                        p.get('action'), c.Style.BRIGHT, c.Fore.CYAN, p.get('output')
                    )
                )

        # Bundle
        if self.package_data.get('bundle'):
            print('\n{}{}Bundle:'.format(c.Style.BRIGHT, c.Fore.BLUE))
            for p in self.package_data['bundle']:
                print(
                    '{!s:<20}{}{} {!s:<50}'.format(
                        p.get('action'), c.Style.BRIGHT, c.Fore.CYAN, p.get('output')
                    )
                )

        # ignore exit code
        if not self.args.ignore_validation:
            print('\n')  # separate errors from normal output
            # print all errors
            for error in self.package_data.get('errors'):
                print('{}{}'.format(c.Fore.RED, error))
                self.exit_code = 1
59222
def _run():
    """"""
    args = parse_args()

    # register signal handler
    signal.signal(signal.SIGTERM, signal_handler)
    signal.signal(signal.SIGINT, signal_handler)

    # set up logging
    log_formatter = logging.Formatter("%(asctime)s %(filename)s(line %(lineno)d) "
                                      "%(levelname)s: %(message)s")
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.INFO)
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(log_formatter)
    root_logger.addHandler(console_handler)

    # add file handler if specified
    if args.log_file:
        file_handler = logging.FileHandler(args.log_file)
        file_handler.setFormatter(log_formatter)
        root_logger.addHandler(file_handler)

    # check vm_num and vm_index value
    if args.vm_num < 1:
        print "vm_num value cannot be negative!"
        return
    if args.vm_index < 1 or args.vm_index > args.vm_num:
        print "vm_index value cannot be negative or greater than vm_num!"
        return

    if args.create_conf_dir:
        if args.create_HMA:
            hma_dir = return_abs_path(args.create_conf_dir, 'vpns')
            hma.create_config_files(hma_dir)
        elif args.create_IPVANISH:
            ipvanish_dir = return_abs_path(args.create_conf_dir, 'vpns')
            ipvanish.create_config_files(ipvanish_dir)
        elif args.create_PUREVPN:
            purevpn_dir = return_abs_path(args.create_conf_dir, 'vpns')
            purevpn.create_config_files(purevpn_dir)
        elif args.create_VPNGATE:
            vpngate_dir = return_abs_path(args.create_conf_dir, 'vpns')
            vpngate.create_config_files(vpngate_dir)
        # create the config files for the openvpn config files
        create_config_files(args.create_conf_dir)
    else:
        # sanity check tls_auth and key_direction
        if (args.tls_auth is not None and args.key_direction is None) or \
                (args.tls_auth is None and args.key_direction is not None):
            logging.error("tls_auth and key_direction must be specified "
                          "together!")
            return

        scan_vpns(directory=args.directory, auth_file=args.auth_file,
                  crt_file=args.crt_file, tls_auth=args.tls_auth,
                  key_direction=args.key_direction, exclude_list=args.exclude_list,
                  shuffle_lists=args.shuffle_lists, vm_num=args.vm_num,
                  vm_index=args.vm_index, reduce_vp=args.reduce_vp)
883317
def htmlprint(*values, plain=None, **options):
    
    print(*[htmlrender(x, plain=plain) for x in values], **options)
989119
def _main(args):
    

    if not args.apikey:
        print("\nPlease provide TinyPNG API key")
        print("To obtain key visit https://api.tinypng.com/developers\n")
        sys.exit(1)

    input_dir = realpath(args.input)

    if not args.output:
        output_dir = input_dir + "-output"
    else:
        output_dir = realpath(args.output)

    if input_dir == output_dir:
        print("\nPlease specify different output directory\n")
        sys.exit(1)

    handler = ScreenHandler()

    try:
        process_directory(input_dir, output_dir, args.apikey, handler)
    except KeyboardInterrupt:
        handler.on_finish(output_dir=output_dir)
572806
def printer(self):
        """"""
        for key in self.statediag:
            if key.trans is not None and len(key.trans) > 0:
                print '****** ' + repr(key.id) + '(' + repr(key.type)\
                      + ' on sym ' + repr(key.sym) + ') ******'
                print key.trans
963789
def main(argv=sys.argv[1:], loop=None):
    """"""
    args = docopt(__doc__, argv=argv,
                  version=pkg_resources.require('rflink')[0].version)

    level = logging.ERROR
    if args['-v']:
        level = logging.INFO
    if args['-v'] == 2:
        level = logging.DEBUG
    logging.basicConfig(level=level)

    if not loop:
        loop = asyncio.get_event_loop()

    if args['--ignore']:
        ignore = args['--ignore'].split(',')
    else:
        ignore = []

    command = next((c for c in ALL_COMMANDS if args[c] is True), None)

    if command:
        protocol = PROTOCOLS['command']
    else:
        protocol = PROTOCOLS[args['-m']]

    conn = create_rflink_connection(
        protocol=protocol,
        host=args['--host'],
        port=args['--port'],
        baud=args['--baud'],
        loop=loop,
        ignore=ignore,
    )

    transport, protocol = loop.run_until_complete(conn)

    try:
        if command:
            for _ in range(int(args['--repeat'])):
                loop.run_until_complete(
                    protocol.send_command_ack(
                        args['<id>'], command))
        else:
            loop.run_forever()
    except KeyboardInterrupt:
        # cleanup connection
        transport.close()
        loop.run_forever()
    finally:
        loop.close()
420599
def main():
    
    try:

        # Open serial port
        ser = serial.Serial('/dev/ttyUSB0', 9600)

        # Create XBee Series 1 object
        xbee = XBee(ser)


        # Send AT packet
        xbee.send('at', frame_id='A', command='DH')

        # Wait for response
        response = xbee.wait_read_frame()
        print response

        # Send AT packet
        xbee.send('at', frame_id='B', command='DL')

        # Wait for response
        response = xbee.wait_read_frame()
        print response

        # Send AT packet
        xbee.send('at', frame_id='C', command='MY')

        # Wait for response
        response = xbee.wait_read_frame()
        print response

        # Send AT packet
        xbee.send('at', frame_id='D', command='CE')

        # Wait for response
        response = xbee.wait_read_frame()
        print response
    except KeyboardInterrupt:
        pass
    finally:
        ser.close()
1335264
def dump(self):
        """"""
        print "-----MqttPkt------"
        print "command = ", self.command
        print "have_remaining = ", self.have_remaining
        print "remaining_count = ", self.remaining_count
        print "mid = ", self.mid
        print "remaining_mult = ", self.remaining_mult
        print "remaining_length = ", self.remaining_length
        print "packet_length = ", self.packet_length
        print "to_process = ", self.to_process
        print "pos = ", self.pos
        print "payload = ", self.payload
        print "------------------"
95172
def run_example(path):
    
    cmd = "{0} {1}".format(sys.executable, path)
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    res = proc.communicate()
    if proc.returncode:
        print(res[1].decode())
    return proc.returncode
380792
def mdprint(*values, plain=None, **options):
    
    print(*[mdrender(x, plain=plain) for x in values], **options)
902232
def run():
    """"""
    
    # Grab server args
    args = client_helper.grab_server_args()

    # Start up workbench connection
    workbench = zerorpc.Client(timeout=300, heartbeat=60)
    workbench.connect('tcp://'+args['server']+':'+args['port'])
    
    # Grab all the filenames from the data directory
    data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),'../data')
    file_list = all_files_in_directory(data_dir)

    # Upload the files into workbench
    md5_list = []
    for path in file_list:

        # Skip OS generated files
        if '.DS_Store' in path: 
            continue

        with open(path,'rb') as f:
            filename = os.path.basename(path)

            # Here we're going to save network traffic by asking
            # Workbench if it already has this md5
            raw_bytes = f.read()
            md5 = hashlib.md5(raw_bytes).hexdigest()
            md5_list.append(md5)
            if workbench.has_sample(md5):
                print 'Workbench already has this sample %s' % md5
            else:
                # Store the sample into workbench
                md5 = workbench.store_sample(raw_bytes, filename, 'unknown')
                print 'Filename %s uploaded: type_tag %s, md5 %s' % (filename, 'unknown', md5)

    # Okay now explode any container types
    zip_files = workbench.generate_sample_set('zip')
    _foo = workbench.set_work_request('unzip', zip_files); list(_foo) # See Issue #306
    pcap_files = workbench.generate_sample_set('pcap')
    _foo = workbench.set_work_request('pcap_bro', pcap_files); list(_foo) # See Issue #306
    mem_files = workbench.generate_sample_set('mem')
    _foo = workbench.set_work_request('mem_procdump', mem_files); list(_foo) # See Issue #306


    # Make sure all files are properly identified
    print 'Info: Ensuring File Identifications...'
    type_tag_set = set()
    all_files = workbench.generate_sample_set()
    meta_all = workbench.set_work_request('meta', all_files)
    for meta in meta_all:
        type_tag_set.add(meta['type_tag'])
        if meta['type_tag'] in ['unknown', 'own']:
            print meta
    pprint.pprint(type_tag_set)
843426
def print_examples(self, full=False):
        
        msg = []
        i = 1
        for key in sorted(self.DEMOS.keys()):
            example = self.DEMOS[key]
            if full or example["show"]:
                msg.append(u"Example %d (%s)" % (i, example[u"description"]))
                msg.append(u"  $ %s %s" % (self.invoke, key))
                msg.append(u"")
                i += 1
        self.print_generic(u"\n" + u"\n".join(msg) + u"\n")
        return self.HELP_EXIT_CODE