Example #1
0
import pdb
try:
    import Tool80211
except ImportError:
    # Tool80211 not installed
    # assuming were running out of source directory
    sys.path.append('../')
    try:
        import Tool80211
    except ImportError, e:
        print e
        sys.exit(-1)

if __name__ == "__main__":
    print "Airdrop-ng Rule Auto Writer"
    parser = optparse.OptionParser("%prog options [-i]")
    parser.add_option("-i",
                      "--interface",
                      dest="card",
                      nargs=1,
                      help="Interface to sniff from")
    parser.add_option("-c",
                      "--channel",
                      dest="channel",
                      nargs=1,
                      default=False,
                      help="Interface to sniff from")
    parser.add_option("-e",
                      "--essid",
                      dest="essid",
                      default=None,
Example #2
0
 print "    using VASP as a back-end."
 print ""
 print "    Contributors: Alexandr Fonari  (Georgia Tech)"
 print "                  Shannon Stauffer (UT Austin)"
 print "    MIT License, 2013"
 print "    URL: http://raman-sc.github.io"
 print "    Started at: "+datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
 print ""
 #
 description  = "Before run, set environment variables:\n"
 description += "    VASP_RAMAN_RUN='mpirun vasp'\n"
 description += "    VASP_RAMAN_PARAMS='[first-mode]_[last-mode]_[nderiv]_[step-size]'\n\n"
 description += "bash one-liner is:\n"
 description += "VASP_RAMAN_RUN='mpirun vasp' VASP_RAMAN_PARAMS='1_2_2_0.01' python vasp_raman.py"
 #
 parser = optparse.OptionParser(description=description)
 parser.add_option('-g', '--gen', help='Generate POSCAR only', action='store_true')
 parser.add_option('-u', '--use_poscar', help='Use provided POSCAR in the folder, USE WITH CAUTION!!', action='store_true')
 (options, args) = parser.parse_args()
 #args = vars(parser.parse_args())
 args = vars(options)
 #
 VASP_RAMAN_RUN = os.environ.get('VASP_RAMAN_RUN')
 if VASP_RAMAN_RUN == None:
     print "[__main__]: ERROR Set environment variable 'VASP_RAMAN_RUN'"
     print ""
     parser.print_help()
     sys.exit(1)
 print "[__main__]: VASP_RAMAN_RUN='"+VASP_RAMAN_RUN+"'"
 #
 VASP_RAMAN_PARAMS = os.environ.get('VASP_RAMAN_PARAMS')
Example #3
0
import os
import sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)

import makerbot_driver

import optparse
import time
import subprocess

parser = optparse.OptionParser()
parser.add_option("-m", "--machine", dest="machine",
                help="machine to upload to", default="The Replicator")
parser.add_option("-v", "--version", dest="version", 
                help="version to upload", default="5.5")
parser.add_option("-p", "--port", dest="port",
                help="port machine is connected to (OPTIONAL)", default=None)
(options, args) = parser.parse_args()

if options.port == None:
  md = makerbot_driver.MachineDetector()
  md.scan(options.machine)
  port = md.get_first_machine()
  if port is None:
    print "Cant Find %s" %(options.machine)
    sys.exit()
else:
  port = options.port

machine_name = options.machine.replace(' ', '')
Example #4
0
    def main(cmd_args):
        import optparse
        global options, PSYCO
        usage = "\n%prog [options] command [input-file-patterns]\n" + cmd_doc
        oparser = optparse.OptionParser(usage)
        oparser.add_option("-l",
                           "--logfilename",
                           default="",
                           help="contains error messages")
        oparser.add_option(
            "-v",
            "--verbosity",
            type="int",
            default=0,
            help="level of information and diagnostics provided")
        oparser.add_option(
            "-m",
            "--mmap",
            type="int",
            default=-1,
            help="1: use mmap; 0: don't use mmap; -1: accept heuristic")
        oparser.add_option("-e",
                           "--encoding",
                           default="",
                           help="encoding override")
        oparser.add_option("-f",
                           "--formatting",
                           type="int",
                           default=0,
                           help="0 (default): no fmt info\n"
                           "1: fmt info (all cells)\n")
        oparser.add_option(
            "-g",
            "--gc",
            type="int",
            default=0,
            help=
            "0: auto gc enabled; 1: auto gc disabled, manual collect after each file; 2: no gc"
        )
        oparser.add_option(
            "-s",
            "--onesheet",
            default="",
            help="restrict output to this sheet (name or index)")
        oparser.add_option("-u",
                           "--unnumbered",
                           action="store_true",
                           default=0,
                           help="omit line numbers or offsets in biff_dump")
        oparser.add_option("-d",
                           "--on-demand",
                           action="store_true",
                           default=0,
                           help="load sheets on demand instead of all at once")
        oparser.add_option("-t",
                           "--suppress-timing",
                           action="store_true",
                           default=0,
                           help="don't print timings (diffs are less messy)")
        oparser.add_option("-r",
                           "--ragged-rows",
                           action="store_true",
                           default=0,
                           help="open_workbook(..., ragged_rows=True)")
        options, args = oparser.parse_args(cmd_args)
        if len(args) == 1 and args[0] in ("version", ):
            pass
        elif len(args) < 2:
            oparser.error("Expected at least 2 args, found %d" % len(args))
        cmd = args[0]
        xlrd_version = getattr(xlrd, "__VERSION__", "unknown; before 0.5")
        if cmd == 'biff_dump':
            xlrd.dump(args[1], unnumbered=options.unnumbered)
            sys.exit(0)
        if cmd == 'biff_count':
            xlrd.count_records(args[1])
            sys.exit(0)
        if cmd == 'version':
            print("xlrd: %s, from %s" % (xlrd_version, xlrd.__file__))
            print("Python:", sys.version)
            sys.exit(0)
        if options.logfilename:
            logfile = LogHandler(open(options.logfilename, 'w'))
        else:
            logfile = sys.stdout
        mmap_opt = options.mmap
        mmap_arg = xlrd.USE_MMAP
        if mmap_opt in (1, 0):
            mmap_arg = mmap_opt
        elif mmap_opt != -1:
            print('Unexpected value (%r) for mmap option -- assuming default' %
                  mmap_opt)
        fmt_opt = options.formatting | (cmd in ('xfc', ))
        gc_mode = options.gc
        if gc_mode:
            gc.disable()
        for pattern in args[1:]:
            for fname in glob.glob(pattern):
                print("\n=== File: %s ===" % fname)
                if logfile != sys.stdout:
                    logfile.setfileheading("\n=== File: %s ===\n" % fname)
                if gc_mode == 1:
                    n_unreachable = gc.collect()
                    if n_unreachable:
                        print("GC before open:", n_unreachable,
                              "unreachable objects")
                if PSYCO:
                    import psyco
                    psyco.full()
                    PSYCO = 0
                try:
                    t0 = time.time()
                    bk = xlrd.open_workbook(
                        fname,
                        verbosity=options.verbosity,
                        logfile=logfile,
                        use_mmap=mmap_arg,
                        encoding_override=options.encoding,
                        formatting_info=fmt_opt,
                        on_demand=options.on_demand,
                        ragged_rows=options.ragged_rows,
                    )
                    t1 = time.time()
                    if not options.suppress_timing:
                        print("Open took %.2f seconds" % (t1 - t0, ))
                except xlrd.XLRDError as e:
                    print("*** Open failed: %s: %s" % (type(e).__name__, e))
                    continue
                except KeyboardInterrupt:
                    print("*** KeyboardInterrupt ***")
                    traceback.print_exc(file=sys.stdout)
                    sys.exit(1)
                except BaseException as e:
                    print("*** Open failed: %s: %s" % (type(e).__name__, e))
                    traceback.print_exc(file=sys.stdout)
                    continue
                t0 = time.time()
                if cmd == 'hdr':
                    bk_header(bk)
                elif cmd == 'ov':  # OverView
                    show(bk, 0)
                elif cmd == 'show':  # all rows
                    show(bk)
                elif cmd == '2rows':  # first row and last row
                    show(bk, 2)
                elif cmd == '3rows':  # first row, 2nd row and last row
                    show(bk, 3)
                elif cmd == 'bench':
                    show(bk, printit=0)
                elif cmd == 'fonts':
                    bk_header(bk)
                    show_fonts(bk)
                elif cmd == 'names':  # named reference list
                    show_names(bk)
                elif cmd == 'name_dump':  # named reference list
                    show_names(bk, dump=1)
                elif cmd == 'labels':
                    show_labels(bk)
                elif cmd == 'xfc':
                    count_xfs(bk)
                else:
                    print("*** Unknown command <%s>" % cmd)
                    sys.exit(1)
                del bk
                if gc_mode == 1:
                    n_unreachable = gc.collect()
                    if n_unreachable:
                        print("GC post cmd:", fname, "->", n_unreachable,
                              "unreachable objects")
                if not options.suppress_timing:
                    t1 = time.time()
                    print("\ncommand took %.2f seconds\n" % (t1 - t0, ))

        return None
Example #5
0
    elif req.path == '/tiles':
        # Used cached map and projection if instance exists
        if not MAP_CACHE:
            MAP_CACHE = MapResponse(req.values, mapfile)
        resp = MAP_CACHE(req.values)
    else:
        resp = not_found(req)

    return resp(environ, start_response)


if __name__ == '__main__':

    parser = optparse.OptionParser(
        usage="""python nikserv.py <mapfile.xml> [options]
    
    Usage:
        $ python nikserv.py /path/to/mapfile.xml
    """)

    #parser.add_option('-b', '--bbox', dest='bbox_projected')

    (options, args) = parser.parse_args()
    import sys
    if len(args) < 1:
        if not mapfile:
            sys.exit('\nPlease provide the path to a mapnik mml or xml \n')
    else:
        mapfile = args[0]

    # set up for optional command line args from nik2img
    #for k,v in vars(options).items():
Example #6
0
def _ParseOptions(argv):
  parser = optparse.OptionParser()
  build_utils.AddDepfileOption(parser)

  parser.add_option(
      '--src-gendirs',
      help='Directories containing generated java files.')
  parser.add_option(
      '--java-srcjars',
      action='append',
      default=[],
      help='List of srcjars to include in compilation.')
  parser.add_option(
      '--bootclasspath',
      action='append',
      default=[],
      help='Boot classpath for javac. If this is specified multiple times, '
      'they will all be appended to construct the classpath.')
  parser.add_option(
      '--classpath',
      action='append',
      help='Classpath for javac. If this is specified multiple times, they '
      'will all be appended to construct the classpath.')
  parser.add_option(
      '--incremental',
      action='store_true',
      help='Whether to re-use .class files rather than recompiling them '
           '(when possible).')
  parser.add_option(
      '--javac-includes',
      default='',
      help='A list of file patterns. If provided, only java files that match'
      'one of the patterns will be compiled.')
  parser.add_option(
      '--jar-excluded-classes',
      default='',
      help='List of .class file patterns to exclude from the jar.')
  parser.add_option(
      '--chromium-code',
      type='int',
      help='Whether code being compiled should be built with stricter '
      'warnings for chromium code.')
  parser.add_option(
      '--use-errorprone-path',
      help='Use the Errorprone compiler at this path.')
  parser.add_option('--jar-path', help='Jar output path.')
  parser.add_option('--stamp', help='Path to touch on success.')

  options, args = parser.parse_args(argv)
  build_utils.CheckOptions(options, parser, required=('jar_path',))

  bootclasspath = []
  for arg in options.bootclasspath:
    bootclasspath += build_utils.ParseGypList(arg)
  options.bootclasspath = bootclasspath

  classpath = []
  for arg in options.classpath:
    classpath += build_utils.ParseGypList(arg)
  options.classpath = classpath

  java_srcjars = []
  for arg in options.java_srcjars:
    java_srcjars += build_utils.ParseGypList(arg)
  options.java_srcjars = java_srcjars

  if options.src_gendirs:
    options.src_gendirs = build_utils.ParseGypList(options.src_gendirs)

  options.javac_includes = build_utils.ParseGypList(options.javac_includes)
  options.jar_excluded_classes = (
      build_utils.ParseGypList(options.jar_excluded_classes))
  return options, args
Example #7
0
            m_doppler = doppler
    return m_metric, m_code, m_doppler


#
# main program
#

parser = optparse.OptionParser(
    usage=
    """acquire-glonass-l1.py [options] input_filename sample_rate carrier_offset

Acquire GLONASS L1 signals

Examples:
  Acquire all GLONASS channels using standard input with sample rate 69.984 MHz and carrier (channel 0) offset 17.245125 MHz:
    acquire-glonass-l1.py /dev/stdin 69984000 17245125

Arguments:
  input_filename    input data file, i/q interleaved, 8 bit signed
  sample_rate       sampling rate in Hz
  carrier_offset    offset to GLONASS L1 carrier (channel 0) in Hz (positive or negative)"""
)

parser.disable_interspersed_args()

parser.add_option(
    "--channel",
    default="-7:7",
    help="channels to search, e.g. -6,-4,-1:2,7 (default %default)")
parser.add_option(
Example #8
0
File: dns.py Project: jelmer/samba
import os
import sys
import struct
import random
import socket
import samba.ndr as ndr
from samba import credentials, param
from samba.tests import TestCase
from samba.dcerpc import dns, dnsp, dnsserver
from samba.netcmd.dns import TXTRecord, dns_record_match, data_to_dns_record
from samba.tests.subunitrun import SubunitOptions, TestProgram
import samba.getopt as options
import optparse

parser = optparse.OptionParser("dns.py <server name> <server ip> [options]")
sambaopts = options.SambaOptions(parser)
parser.add_option_group(sambaopts)

# This timeout only has relevance when testing against Windows
# Format errors tend to return patchy responses, so a timeout is needed.
parser.add_option("--timeout",
                  type="int",
                  dest="timeout",
                  help="Specify timeout for DNS requests")

# use command line creds if available
credopts = options.CredentialsOptions(parser)
parser.add_option_group(credopts)
subunitopts = SubunitOptions(parser)
parser.add_option_group(subunitopts)
Example #9
0
def main():
    parser = optparse.OptionParser(
        'usage%porg -m <model> -u <url> -p <port> -c <cookies>')
    parser.add_option('-m',
                      dest='model',
                      type='string',
                      help='specify target model portscan or webscan')
    parser.add_option('-u',
                      dest='url',
                      type='string',
                      help='specify target url')
    parser.add_option('-p',
                      dest='port',
                      type='string',
                      help='specify target port')
    parser.add_option('-c',
                      dest='cookies',
                      type='string',
                      help='specify target cookies')
    parser.add_option('-t',
                      dest='thread_count',
                      type='int',
                      help='specify scan thread')
    (option, args) = parser.parse_args()
    '''
    model = option.model
    host = option.url
    port = option.port
    cookies = option.cookies
    thread_count = option.thread_count
    '''
    model = 'webscan'
    host = "http://jwc.ntu.edu.cn/"
    port = 80
    cookies = ""
    thread_count = None

    #对model参数进行判定
    if (model == None):
        print(parser.usage)
        exit()
    if (model != 'portscan' and model != 'webscan'):
        print("-m 'portscan' or -m 'webscan'")
        exit()

    #对线程数进行设置
    if (thread_count == None):
        thread_count = 8

    #对url参数进行拆分
    if (host.startswith("https://")):
        host = host.split("https://")[1].split('/')[0]
    if (host.startswith("http://")):
        host = host.split("http://")[1].split('/')[0]

    #启用端口扫描模块
    if (model == 'portscan'):
        pass
        #portscan(host, thread_count)

    #启用web扫描模块
    if (model == 'webscan'):
        print("[+]webscan model running .....")
        Start.webscan(host, thread_count, cookies)
Example #10
0
import optparse
import concatenate
import symbols
import shutil
import datetime
import zipfile

if __name__ == '__main__':

    #command line parsing

    usage = "%prog [options]"
    description = """It downloads the fusion genes from article: Hu et al., TumorFusions: an integrative resource for cancer-associated transcript fusions, Nucleic Acids Research, Nov. 2017, https://doi.org/10.1093/nar/gkx1018"""
    version = "%prog 0.12 beta"

    parser = optparse.OptionParser(usage=usage,description=description,version=version)

    parser.add_option("--organism","-g",
                      action = "store",
                      type = "string",
                      dest = "organism",
                      default = "homo_sapiens",
                      help="""The name of the organism for which the known fusion genes are downloaded, e.g. homo_sapiens, mus_musculus, etc. Default is '%default'.""")

    parser.add_option("--output","-o",
                      action="store",
                      type="string",
                      dest="output_directory",
                      default = '.',
                      help="""The output directory where the known fusion genes are stored. Default is '%default'.""")
def main():
    MSGLEN = 4096
    parser = optparse.OptionParser()

    parser.add_option("--ConfigFile", dest="config_file", help="")
    (options, args) = parser.parse_args()
    try:
        config_file = ConfigParser.RawConfigParser()
        config_file.read(options.config_file)

        ip_address = config_file.get('network', 'ip')
        port = config_file.getint('network', 'port')
        socket_timeout = config_file.getint('network', 'socket_timeout')

        output_directory = config_file.get('output', 'directory')
        output_daps = config_file.getboolean('output', 'output_daps')
        output_damsnt = config_file.getboolean('output', 'output_damsnt')

        app_logging = config_file.get('logging', 'app')
        socket_logging = config_file.get('logging', 'socket')

        logging.config.fileConfig(app_logging)
        logger = logging.getLogger("DAMSNT")
        logger.info('Logging file opened.')

    except Exception as e:
        traceback.print_exc()
    else:
        graceful_exit_handler = GracefulKiller()

        message_queue = Queue()
        #ip_address, port, data_queue, message_length):
        logger.info('Starting DAMS Comm client.')
        dams_sock = DAMSComm(ip_address=ip_address,
                             port=port,
                             data_queue=message_queue,
                             message_length=MSGLEN,
                             socket_timeout=socket_timeout,
                             socket_log_conf=socket_logging)
        dams_sock.start()
        rec_count = 0
        now_time = datetime.now()
        #We want to create a new raw file each new day.
        today = datetime(year=now_time.year,
                         month=now_time.month,
                         day=now_time.day,
                         hour=0,
                         minute=0,
                         second=0)
        daps_output_file = None
        one_day_delta = timedelta(days=1)

        message_processor = DAMSNTMessageHandler()
        #while dams_sock.is_alive():
        while not graceful_exit_handler.kill_now:
            if dams_sock.is_alive():
                data_rec = message_queue.get()
                try:
                    dcp_msgs = message_processor.process_buffer(data_rec)
                except Exception as e:
                    logger.error("Error processing buffer.")
                    logger.exception(e)
                #print(data_rec)

                #dcp_message = DCPMessage(raw_message=None)
                for dcp_message in dcp_msgs:
                    #if dcp_message.decipher_raw(data_rec):
                    new_file = False
                    #Check if we're in a new day every hundred records.
                    if (rec_count % 100) == 0:
                        #If it's the next day, we want to create a new output file.
                        if datetime.now() - today > one_day_delta:
                            logger.info('Day changed, now: %s from %s' %\
                                        (datetime.now(), today))

                            new_file = True
                            now_time = datetime.now()
                            today = datetime(year=now_time.year,
                                             month=now_time.month,
                                             day=now_time.day,
                                             hour=0,
                                             minute=0,
                                             second=0)
                    if output_daps:
                        if new_file or daps_output_file is None:
                            try:
                                if daps_output_file is not None:
                                    daps_output_file.close()
                                daps_output_filename = os.path.join(
                                    output_directory, "daps_%s.RAW" %
                                    (now_time.strftime('%Y%m%d_%H%M%S')))
                                logger.info('Opening new output file: %s' %
                                            (daps_output_filename))
                                daps_output_file = open(
                                    daps_output_filename, "w")
                            except Exception as e:
                                traceback.print_exc(e)
                                daps_output_file = None
                        daps_output(dcp_message, daps_output_file)
                rec_count += 1

        logger.info("Closing DAMS NT Comm client.")
        dams_sock.close()
        if daps_output_file is not None:
            logger.info("Closing DAPS output file.")
            daps_output_file.close()
        logger.info("Waiting for DAMS NT client to terminate.")
        dams_sock.join()
        logger.info("Terminating program.")
    return
Example #12
0
    def main(self):
        import optparse

        parser = optparse.OptionParser(usage="%prog [options]")
        parser.add_option("--nocleanup", dest="nocleanup", default=False, action="store_true",
                          help="Leave edends and test.* datadir on exit or error")
        parser.add_option("--noshutdown", dest="noshutdown", default=False, action="store_true",
                          help="Don't stop edends after the test execution")
        parser.add_option("--srcdir", dest="srcdir", default="../../src",
                          help="Source directory containing edend/eden-cli (default: %default)")
        parser.add_option("--tmpdir", dest="tmpdir", default=tempfile.mkdtemp(prefix="test"),
                          help="Root directory for datadirs")
        parser.add_option("--tracerpc", dest="trace_rpc", default=False, action="store_true",
                          help="Print out all RPC calls as they are made")
        parser.add_option("--coveragedir", dest="coveragedir",
                          help="Write tested RPC commands into this directory")
        self.add_options(parser)
        (self.options, self.args) = parser.parse_args()

        if self.options.trace_rpc:
            import logging
            logging.basicConfig(level=logging.DEBUG)

        if self.options.coveragedir:
            enable_coverage(self.options.coveragedir)

        os.environ['PATH'] = self.options.srcdir+":"+self.options.srcdir+"/qt:"+os.environ['PATH']

        check_json_precision()

        success = False
        try:
            if not os.path.isdir(self.options.tmpdir):
                os.makedirs(self.options.tmpdir)
            self.setup_chain()

            self.setup_network()

            self.run_test()

            success = True

        except JSONRPCException as e:
            print("JSONRPC error: "+e.error['message'])
            traceback.print_tb(sys.exc_info()[2])
        except AssertionError as e:
            print("Assertion failed: "+ str(e))
            traceback.print_tb(sys.exc_info()[2])
        except Exception as e:
            print("Unexpected exception caught during testing: " + repr(e))
            traceback.print_tb(sys.exc_info()[2])

        if not self.options.noshutdown:
            print("Stopping nodes")
            stop_nodes(self.nodes)
            wait_bitcoinds()
        else:
            print("Note: edends were not stopped and may still be running")

        if not self.options.nocleanup and not self.options.noshutdown:
            print("Cleaning up")
            shutil.rmtree(self.options.tmpdir)

        if success:
            print("Tests successful")
            sys.exit(0)
        else:
            print("Failed")
            sys.exit(1)
            if flag == 1:
                start_frame = end_frame # set new start frame
                flag = 0

    if current_stim is not None:
        if opts.singlefile:
            write_clip('sound', '', opts.output_dir, num_channels, sample_rate, audio_buf)
        else:
            write_clip(current_stim, current_stim_time, opts.output_dir, num_channels, sample_rate, audio_buf)

    bag.close()


if __name__ == "__main__":
    usage = "usage: %prog [options] clipfile"
    parser = optparse.OptionParser(usage=usage)
    parser.add_option('-i', '--input-directory', help='Directory containing bagfiles to have snippets extracted', dest='input_dir', default = '.')
    parser.add_option('-o', '--output-directory', help='Directory where new Ultrasound snippets will be saved', dest='output_dir', default = '.')
#    parser.add_option('-b', '--bag-directory', help='directory containing bagfiles to have sound extracted', dest='bagname')
#    parser.add_option('-d', '--out-directory', help='path where new soundfiles will go', dest='dirname', default = '.')
    parser.add_option('-a', '--after', help='amount of audio after click to include', dest='time_after', type='int', default = 8)
    parser.add_option('-s', '--single-file', help='Don''t split sound into clips', dest='singlefile', default=False, action='store_true')
    (opts, args) = parser.parse_args()

    if opts.time_after < 1:
        opts.time_after = 1
    if opts.singlefile:
        print "Storing as a single file."
    if opts.input_dir is None:
        print "input-directory option must be input on command line"
        parser.print_help()