示例#1
1
def main():

    parser = GooeyParser(
        prog='', 
        description="Detecting rare cell-types from single-cell "
            "gene expression data", 
        epilog="Contributors: Lan Jiang, "
            "Qian Zhu and Gregory Giecold.\nFor further help or information, "
            "please contact us at [email protected],"
            "[email protected] or [email protected]")
                    
    subparsers = parser.add_subparsers(dest='datatype', 
        help="Type of your input genomics dataset")
    
    qPCR_parser = subparsers.add_parser('qpcr')
    qPCR_parser.add_argument('Input', type=str, widget='FileChooser',
        help='Select a file to process:')
    qPCR_parser.add_argument('-e', '--epsilon', nargs='?',
        type=float, const=0.25, default=0.25, 
        help='DBSCAN epsilon parameter:')
    qPCR_parser.add_argument('-m', '--minPts', nargs='?',
        type=int, const=5, default=5,
        help='DBSCAN minPts parameter:')
    qPCR_parser.add_argument('-O', '--Output', nargs='?', type=str,
        default=path.join(getcwd(), 'GiniClust_results'),
        help="Specify GiniClust's output directory:")
    
    RNASeq_parser = subparsers.add_parser('rna')
    RNASeq_parser.add_argument('Input', type=str, widget='FileChooser',
        help='Select a file to process:')
    RNASeq_parser.add_argument('-e', '--epsilon', nargs='?',
        type=float, const=0.5, default=0.5, 
        help='DBSCAN epsilon parameter:')
    RNASeq_parser.add_argument('-m', '--minPts', nargs='?',
        type=int, const=3, default=3,
        help='DBSCAN minPts parameter:')
    RNASeq_parser.add_argument('-O', '--Output', nargs='?', type=str,
        default=path.join(getcwd(), 'GiniClust_results'),
        help="Specify GiniClust's output directory:")
    
    command = 'Rscript'
    path2Rscript = path.join(getcwd(), 'GiniClust_Main.R')

    args = parser.parse_args()
    
    if args.datatype == 'qpcr':
        datatype_str = 'qPCR'
    else:
        datatype_str = 'RNA-seq'
        
    cmd = [command, path2Rscript]
    cmd += ['-f', args.Input, '-t', datatype_str, '-o', args.Output, '-e', str(args.epsilon), '-m', str(args.minPts)]
    subprocess.check_output(cmd, universal_newlines=True)
def arbitrary_function():
    desc = u"\u041f\u0440\u0438\u043c\u0435\u0440 \u043f\u0440\u0438\u043b\u043e\u0436\u0435\u043d\u0438\u044f \u002c \u0447\u0442\u043e\u0431\u044b \u043f\u043e\u043a\u0430\u0437\u0430\u0442\u044c "
    file_help_msg = u"\u0418\u043c\u044f \u0444\u0430\u0439\u043b\u0430\u002c \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u0432\u044b \u0445\u043e\u0442\u0438\u0442\u0435 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c"

    my_cool_parser = GooeyParser(description=desc)

    my_cool_parser.add_argument(
        'foo',
        metavar=u"\u0432\u044b\u0431\u043e\u0440\u0430\u0444\u0430\u0439\u043b\u043e\u0432",
        help=file_help_msg,
        widget="FileChooser")

    my_cool_parser.add_argument(
        'bar',
        metavar=u"\u041d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u0444\u0430\u0439\u043b\u043e\u0432 \u0421\u043e\u0445\u0440\u0430\u043d\u0438\u0442\u044c",
        help=file_help_msg,
        widget="MultiFileChooser")

    my_cool_parser.add_argument(
        '-d',
        metavar=u'--\u043f\u0440\u043e\u0434\u043e\u043b\u0436\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u044c',
        default=2,
        type=int,
        help=u'\u041f\u0440\u043e\u0434\u043e\u043b\u0436\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u044c \u0028 \u0432 \u0441\u0435\u043a\u0443\u043d\u0434\u0430\u0445 \u0029 \u043d\u0430 \u0432\u044b\u0445\u043e\u0434\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u044b')

    my_cool_parser.add_argument(
        '-s',
        metavar=u'--\u043a\u0440\u043e\u043d \u002d \u0433\u0440\u0430\u0444\u0438\u043a',
        help=u'\u0414\u0430\u0442\u0430',
        widget='DateChooser')

    args = my_cool_parser.parse_args()
    main(args)
示例#3
0
def main():
    desc = "Example application to show Gooey's various widgets"
    parser = GooeyParser(prog="example_progress_bar_1")
    _ = parser.parse_args(sys.argv[1:])

    import time
    time.sleep(1)
    print('Success')
def main():
    parser = GooeyParser(prog="example_progress_bar_1")
    _ = parser.parse_args(sys.argv[1:])

    for i in range(100):
        print("progress: {}%".format(i + 1))
        sys.stdout.flush()
        sleep(0.1)
示例#5
0
def _parser():
    parser = GooeyParser(description='Look up an object in VizieR'
                                                 ' and print mean/median'
                                                 ' values of given parameters')
    parser.add_argument('object', help='Object, e.g. HD20010', nargs='+')
    parser.add_argument('-p', '--params', default=True, action='store_true',
                        help='List of parameters (Teff, logg, [Fe/H] be default)')
    parser.add_argument('-m', '--method', choices=['median', 'mean', 'both'], default='both',
                        help='Which method to print values (mean or median). Default is both')
    parser.add_argument('-c', '--coordinate', default=False, action='store_true',
                        help='Return the RA and DEC (format for NOT\'s visibility plot)')
    return parser.parse_args()
示例#6
0
def _parser():
    '''The argparse stuff'''

    parser = GooeyParser(description='CRIRES spectrum to an 1D spectrum')
    parser.add_argument('fname', action='store', widget='FileChooser', help='Input fits file')
    parser.add_argument('--output', default=False,
                        help='Output to this name. If nothing is given, output will be: "wmin-wmax.fits"')
    parser.add_argument('-u', '--unit', default='angstrom',
                        choices=['angstrom', 'nm'],
                        help='The unit of the output wavelength')
    parser.add_argument('-c', '--clobber', default=True, action='store_false',
                        help='Do not overwrite existing files.')
    args = parser.parse_args()
    return args
示例#7
0
def main():
    parser = GooeyParser(description="PowerPoint Exporter")
    parser.add_argument('powerpoint', widget="FileChooser")
    parser.add_argument('output', help="Folder to place resulting images", widget="DirChooser")
    parser.add_argument('width', help="Width of resulting image (0-3072)")
    parser.add_argument('height', help="Height of resulting image (0-3072)")
    args = parser.parse_args()

    if not (os.path.isfile(args.powerpoint) and os.path.isdir(args.output)):
        raise "Invalid paths!"

    export_presentation(args.powerpoint, args.output, args.width, args.height)

    print "Done!"
示例#8
0
def main():

    print 'minUP GUI'
    desc = \
        'A program to analyse minION fast5 files in real-time or post-run.'
    print desc

    parser = GooeyParser(description=desc)
    for x in xs[1:]:
        if len(x) > 1:
            mkWidget(parser, x, settings)

  # This is updated every time to update the values of the variables...

    try:
        vs = vars(parser.parse_args())
        with open('settings.json', 'w') as f:

          # print json.dumps(vs, indent=4, sort_keys=True)

            f.write(json.dumps(vs, indent=4, sort_keys=True))
    except:
        return ()

  # Build a dict of the var:vals

    print '------------------'
    ps = []
    for k in vs:
        ps.append(('-' + lut[k], toStr(vs[k])))

    ps = map(fixAligner, ps)
    aligner = vs['Aligner_to_Use']
    ps = map(lambda o: fixAlignerOpts(aligner, o), ps)
    ps = sorted(filter(isActive, ps))
    params = ' '.join(map(showParam, ps))

  # cmd = 'ls /a'
  # cmd = 'c:\Python27\python.exe .\minup.v0.63.py ' +params

    cmd = '.\\minUP.exe ' + params  # + ' 2>&1'
    print cmd

    '''
    fl = open("cmd.sh", 'w')
    fl.write(cmd)
    fl.close()
    '''
    run(cmd)
示例#9
0
def parse_args_gooey():
  '''parse command line arguments'''
  parser = GooeyParser(description="Convert pgm image to png or jpg")    
    
  parser.add_argument("directory", default=None,
                    help="directory containing PGM image files", widget='DirChooser')
  parser.add_argument("--output-directory", default=None,
                    help="directory to use for converted files", widget='DirChooser')
  parser.add_argument("--format", default='png', choices=['png', 'jpg'], help="type of file to convert to (png or jpg)")
  return parser.parse_args()
示例#10
0
def main():

    # get some settings from setting file
    settings = SettingFileReader()
    defaultOutput = settings.getSetting("defaultSettings", "output")
    defaultWidth = settings.getSetting("defaultSettings", "width")
    defaultFramerate = settings.getSetting("defaultSettings", "framerate")
    defaultBitrateKb = settings.getSetting("defaultSettings", "bitratekb")



    description = "Download tracks and playlists from Youtube."

    #parser = argparse.ArgumentParser(description=description)
    parser = GooeyParser(description=description)

    parser.add_argument('-output', required=True, help='Folder to save the tracks' , widget="DirChooser")

    parser.add_argument('-track', required=False, default=None, help='Youtube track ID' )
    parser.add_argument('-playlist', required=False, default=None, help='Youtube playlist ID' )
    parser.add_argument('-audio', action="store_true", default=False, help="Download only the audio part (usualy m4a format)")

    args = parser.parse_args()


    # the user must have chosen between a track and a Playlist.
    # Though none of them is mandatory, so we have to check.
    if(not args.track and not args.playlist):
        print("[ERROR] You must fill at least one of those fields:\n\t- Track - to download a single track\n\t- Playlist - to download a entire playlist")


    else:
        pw = PafyWrapper()

        # download a track
        if(args.track):
            try:
                pw.downloadTrack(args.track, path=args.output, audio=args.audio)
            except ValueError as e:
                print("[INVALID URL]" + e)

        if(args.playlist):
            #try:
            print(args.playlist)
            pw.downloadPlaylist(args.playlist,  path=args.output, audio=args.audio)
示例#11
0
def main():
    my_cool_parser = GooeyParser(description='This Demo will raise an error!')
    my_cool_parser.add_argument(
        "explode",
        metavar='Should I explode?',
        help="Determines whether or not to raise the error",
        choices=['Yes', 'No'],
        default='Yes')

    args = my_cool_parser.parse_args()
    if 'yes' in args.explode.lower():
        print('Will throw error in')
        for i in range(5, 0, -1):
            print(i)
            time.sleep(.7)
        raise Exception(BOOM)

    print(NO_BOOM)
    print('No taste for danger, eh?')
示例#12
0
文件: DAR.py 项目: eylabs/DAR
def main():
	parser = GooeyParser(description="Compares Images!")
	parser.add_argument('directoryName', help="Name of the directory to process.", widget = "DirChooser")
	parser.add_argument('masterName', help="Name of the master image. Please put master image in the chosen directory.", widget = "FileChooser")
	parser.add_argument('--showOriginalImage', help = "(optional), default is False", nargs = "?", default = False)
	parser.add_argument('--showRegionOfInterest', help = "(optional), default is true", nargs = "?", default = True)
	parser.add_argument('--verbose', help = "Show Full Information, default is False", nargs = "?", default = False)
	# parser.add_argument('outputFileName', help="name of the output file")
	# parser.add_argument('extension', help = "(optional)name of extension (ex: JPG)")
	args = parser.parse_args()
	test_dirj = args.directoryName
	masterName = args.masterName
	showOriginalImage = args.showOriginalImage
	showRegionOfInterest = args.showRegionOfInterest
	if showOriginalImage == False:
		showOriginalImage = False
	else:
		showOriginalImage = True

	if showRegionOfInterest == True or showRegionOfInterest == "True" or showRegionOfInterest == "true":
		showRegionOfInterest = True
	else:
		showRegionOfInterest = False

	verbose = args.verbose
	if verbose != False or verbose != "false" or verbose != "False":
		verbose = True
	else:
		verbose = False


	# extensionFinal = pconfig.extension if (extension == "") else ("*" + extension)
	extensionFinal = pconfig.extension
	controlInfo = imageProcessor(masterName, test_dirj, showOriginalImage, showRegionOfInterest, verbose = verbose, control = True)
	controlScore = controlInfo[1]
	info = []
	for fileName in glob.glob(os.path.join(test_dirj, extensionFinal)):
		if fileName.lower() != os.path.join(test_dirj, masterName).lower():
			imageInfo = imageProcessor(fileName, test_dirj, showOriginalImage, showRegionOfInterest, controlScore = controlScore)
			info.append(imageInfo)
	print "Output File Name:" + writeInfo(info,test_dirj, controlInfo)
	print "done"
示例#13
0
def main():
  parser = GooeyParser(description='Package your Gooey applications into standalone executables')
  parser.add_argument(
    "program_name",
    metavar='Program Name',
    help='Destination name for the packaged executable'
  )
  parser.add_argument(
    "source_path",
    metavar="Program Source",
    help='The main source file of your program',
    widget="FileChooser"
  )

  parser.add_argument(
    "output_dir",
    metavar="Output Directory",
    help='Location to store the generated files',
    widget="DirChooser"
  )

  args = parser.parse_args()

  if not os.path.exists(args.source_path):
    raise IOError('{} does not appear to be a valid file path'.format(args.source_path))

  if not os.path.exists(args.output_dir):
    raise IOError('{} does not appear to be a valid directory'.format(args.output_dir))

  with open(os.path.join(local_path(), 'build_template'), 'r') as f:
    spec_details = f.read().format(program_name=args.program_name, source_path=args.source_path)

  fileno, path = tempfile.mkstemp(prefix='gooeybuild', suffix='.spec')
  with open(path, 'w') as f:
    f.write(spec_details)

  cmd = 'pyinstaller "{0}" --distpath="{1}"'.format(path, args.output_dir)
  print cmd
  from pexpect.popen_spawn import PopenSpawn
  child = PopenSpawn(cmd)
  child.logfile = sys.stdout
  child.wait()
  print dedent('''
  ___  _ _  ______                 _
 / _ \| | | |  _  \               | |
/ /_\ \ | | | | | |___  _ __   ___| |
|  _  | | | | | | / _ \| '_ \ / _ \ |
| | | | | | | |/ / (_) | | | |  __/_|
\_| |_/_|_| |___/ \___/|_| |_|\___(_)
  ''')
  print 'Wrote Executable file to {}'.format(args.output_dir)
示例#14
0
def main():
    desc = 'Converts *.spc binary files to text using the spc module'
    parser = GooeyParser(description=desc)
    parser.add_argument('filefolder', widget='DirChooser', help='Input directory containing spc file')
    fformat = parser.add_mutually_exclusive_group()
    fformat.add_argument('-c', '--csv', help='Comma separated output file (.csv) [default]',
                         action='store_true')
    fformat.add_argument('-t', '--txt', help='Tab separated output file (.txt)',
                         action='store_true')
    args = parser.parse_args()

    if args.txt:
        exten = '.txt'
        delim = '\t'
    else:
        # defaults
        exten = '.csv'
        delim = ','

    flist = []

    # only directory here
    ffn = os.path.abspath(args.filefolder)
    for f in os.listdir(ffn):
        flist.append(os.path.join(ffn, f))

    # process files
    for fpath in flist:
        if fpath.lower().endswith('spc'):

            foutp = fpath[:-4] + exten
            try:
                print(fpath, end=' ')
                f = spc.File(fpath)
                f.write_file(foutp, delimiter=delim)
                print('Converted')
            except:
                print('Error processing %s' % fpath)
        else:
            print('%s not spc file, skipping' % fpath)
示例#15
0
def main():
    mk_savedir()  # Make directory to store user's save files

    parser = GooeyParser(
        description='An example of polling for updates at runtime')
    g = parser.add_argument_group()
    stuff = g.add_mutually_exclusive_group(
        required=True,
        gooey_options={
            'initial_selection': 0
        }
    )
    stuff.add_argument(
        '--save',
        metavar='Save Progress',
        action='store_true',
        help='Take a snap shot of your current progress!'
    )
    stuff.add_argument(
        '--load',
        metavar='Load Previous Save',
        help='Load a Previous save file',
        dest='filename',
        widget='Dropdown',
        choices=list_savefiles(),
        gooey_options={
            'validator': {
                'test': 'user_input != "Select Option"',
                'message': 'Choose a save file from the list'
            }
        }
    )

    args = parser.parse_args()

    if args.save:
        save_file()
    else:
        read_file(os.path.join('saves', args.filename))
        print('Finished reading file!')
示例#16
0
def parse_args():
    """ Use GooeyParser to build up the arguments we will use in our script
    Save the arguments in a default json file so that we can retrieve them
    every time we run the script.
    """
    stored_args = {}
    # get the script name without the extension & use it to build up
    # the json filename
    script_name = os.path.splitext(os.path.basename(__file__))[0]
    args_file = "{}-args.json".format(script_name)
    # Read in the prior arguments as a dictionary
    if os.path.isfile(args_file):
        with open(args_file) as data_file:
            stored_args = json.load(data_file)
    parser = GooeyParser(description='Create Quarterly Marketing Report')
    parser.add_argument('data_directory',
                        action='store',
                        default=stored_args.get('data_directory'),
                        widget='DirChooser',
                        help="Source directory that contains Excel files")
    parser.add_argument('output_directory',
                        action='store',
                        widget='DirChooser',
                        default=stored_args.get('output_directory'),
                        help="Output directory to save summary report")
    parser.add_argument('cust_file',
                        action='store',
                        default=stored_args.get('cust_file'),
                        widget='FileChooser',
                        help='Customer Account Status File')
    parser.add_argument('-d', help='Start date to include',
                        default=stored_args.get('d'),
                        widget='DateChooser')
    args = parser.parse_args()
    # Store the values of the arguments so we have them next time we run
    with open(args_file, 'w') as data_file:
        # Using vars(args) returns the data as a dictionary
        json.dump(vars(args), data_file)
    return args
def main():
    parser = GooeyParser(prog="example_progress_bar_1")
    _ = parser.parse_args(sys.argv[1:])

    print("Step 1")

    for i in range(1, 101):
        print("progress: {}%".format(i))
        sys.stdout.flush()
        sleep(0.05)

    print("Step 2")

    print("progress: -1%")  # pulse
    sys.stdout.flush()
    sleep(3)

    print("Step 3")

    for i in range(1, 101):
        print("progress: {}%".format(i))
        sys.stdout.flush()
        sleep(0.05)
示例#18
0
文件: ZeldaGUI.py 项目: K007024/Zelda
def main():
    parser = GooeyParser(description='Zelda clean this mess\nReorganize date/pod -> pod/date')
    parser.add_argument('pattern', nargs='?', default=r"""(.*)_(.*)_(.*)_(.*)_(.*)_(.*)-(.{8})-(.*).datx_(.*)""",
                        help="pattern which allow to get groups\nmoteur = mo.group(1)\nuseless = mo.group(2)\nbanc = mo.group(3)\npod = mo.group(4)\nuseless = mo.group(5)\nrun = mo.group(6)\ndate = mo.group(7)\nheure = mo.group(8)")
    parser.add_argument('srcDir', nargs='?', default=os.getcwd(), widget='FileChooser',
                        help='Engine directory : root/???/*.*')

    args = parser.parse_args()
    Zelda.trier(args.srcDir, args.pattern)
示例#19
0
def main():
  desc = "Example application to show Gooey's various widgets"
  my_cool_parser = GooeyParser(description=desc)
  my_cool_parser.add_argument("Example", help="fill ", widget="FileChooser")   # positional
  verbosity = my_cool_parser.add_mutually_exclusive_group()
  verbosity.add_argument('-t', '--verbozze', dest='verbose', action="store_true", help="Show more details")
  verbosity.add_argument('-q', '--quiet', dest='quiet', action="store_true", help="Only output on error")
  print my_cool_parser._actions
  print 'inside of main(), my_cool_parser =', my_cool_parser

  args = my_cool_parser.parse_args()
  print sys.argv
  print args.countdown
  print args.showtime

  start_time = _time()
  print 'Counting down from %s' % args.countdown
  while _time() - start_time < args.countdown:
    if args.showtime:
      print 'printing message at: %s' % _time()
    else:
      print 'printing message at: %s' % hashlib.md5(str(_time())).hexdigest()
    _sleep(.5)
  print 'Finished running the program. Byeeeeesss!'
def main():
    parser = GooeyParser(prog="example_progress_bar_2")
    parser.add_argument("steps", type=int, default=15)
    parser.add_argument("delay", type=int, default=1)
    args = parser.parse_args(sys.argv[1:])

    for i in range(args.steps):
        print("progress: {}/{}".format(i+1, args.steps))
        sys.stdout.flush()
        sleep(args.delay)
def get_params():
    parser = GooeyParser()
    parser.add_argument('search_term', help="The search term")
    parser.add_argument(
        dest='mode',
        widget='Dropdown',
        choices=['Director', 'IMDB Code', 'Keyword']
    )
    args = parser.parse_args()
    return args.mode, args.search_term
示例#22
0
def main():
    parser = GooeyParser(description='Process some integers.')

    parser.add_argument(
        'required_field',
        metavar='Some Field',
        help='Enter some text!')

    parser.add_argument(
        '-f', '--foo',
        metavar='Some Flag',
        action='store_true',
        help='I turn things on and off')

    args = parser.parse_args()
    print('Hooray!')
def _parser():
    """Take care of all the argparse stuff.

    :returns: the args
    """
    parser = GooeyParser(description='Wavelength Calibrate CRIRES Spectra')
    parser.add_argument('fname',
                        action='store',
                        widget='FileChooser',
                        help='Input fits file')
    parser.add_argument('-o', '--output',
                        default=False,
                        action='store',
                        widget='FileChooser',
                        help='Ouput Filename',)
    parser.add_argument('-t', '--telluric',
                        default=False,
                        action='store',
                        widget='FileChooser',
                        help='Telluric line Calibrator',)
    #parser.add_argument('-t', '--telluric',
    #                    help='Over plot telluric spectrum',
    #                    action='store_true')
    
    #parser.add_argument('-c', '--ccf',
    #                   default='none',
    #                    choices=['none', 'sun', 'model', 'telluric', 'both'],
    #                    help='Calculate the CCF for Sun/model or tellurics '
    #                    'or both.')
    #parser.add_argument('--ftype', help='Select which type the fits file is',
    #                    choices=['ARES', 'CRIRES'], default='ARES')
    #parser.add_argument('--fitsext', help='Select fits extention, Default 0.',
    #                    choices=['0', '1', '2', '3', '4'], default='0')
    #parser.add_argument('--fitsext', default=0, type=int, 
    #                    help='Select fits extention, 0 = Primary header')
    args = parser.parse_args()
    return args
示例#24
0
def parse_args(progress_regex=r"^progress: (\d+)%$",
       disable_stop_button=True):
    """ Use GooeyParser to build up the arguments we will use in our script
    Save the arguments in a default json file so that we can retrieve them
    every time we run the script.
    """
    
    stored_args = {}
    # get the script name without the extension & use it to build up
    # the json filename
    script_name = os.path.splitext(os.path.basename(__file__))[0]
    args_file = "{}-args.json".format(script_name)
    # Read in the prior arguments as a dictionary
    if os.path.isfile(args_file):
        with open(args_file) as data_file:
            stored_args = json.load(data_file)
    parser = GooeyParser(description='Mail Merge')
    parser.add_argument('data_directory',
                        action='store',
                        default=stored_args.get('data_directory'),
                        widget='DirChooser',
                        help="Source directory that contains Excel files")
    
    parser.add_argument('output_directory',
                        action='store',
                        widget='DirChooser',
                        default=stored_args.get('output_directory'),
                        help="Output directory to save merged files")

    #parser.add_argument("FileSaver", help="Name the output file you want to process", widget="FileSaver")
    #parser.add_argument("-o", "--overwrite", action="store_true", help="Overwrite output file (if present)")
    #parser.add_argument("-s", "--sheets", action="store_true", help="Would you like to ignore multiple sheets?")

    args = parser.parse_args()
    # Store the values of the arguments so we have them next time we run
    with open(args_file, 'w') as data_file:
        # Using vars(args) returns the data as a dictionary
        json.dump(vars(args), data_file)
    return args
示例#25
0
def parse_args():
    prog_descrip = "Apply sentiment analyis"

    parser = GooeyParser(description=prog_descrip)

    parser.add_argument(
        "datadir",
        metavar="Translated Twitter Data",
        help="Select the source twitter data folder",
        widget="DirChooser",
    )

    parser.add_argument(
        "city_name",
        metavar="City Name",
        help="Name of city to be analysed",
        type=str,
    )

    parser.add_argument(
        "--parallel_en",
        metavar="Enable Parallel compute",
        help="Uses multicore processing",
        action="store_true",
        default=True,
        widget="CheckBox",
    )

    parser.add_argument(
        "--save_pickle",
        metavar="Save files as pickles",
        help="Uses raw pandas dataframe format (faster)",
        action="store_true",
        default=True,
        widget="CheckBox",
    )

    parser.add_argument(
        "--save_excel",
        metavar="Save files as Excel",
        help="Uses Microsoft Excel file format",
        action="store_true",
        default=False,
        widget="CheckBox",
    )

    parser.add_argument(
        "--cpu_cores",
        metavar="Number of Cores to use",
        help=
        "If multicore processing is used, python will spawn multiple instances",
        type=int,
        default=8,
    )

    parser.add_argument(
        "--datacol",
        metavar="Data Column Name",
        help="Name of column where translated data is stored",
        type=str,
        default="translated_full_text",
    )

    return parser.parse_args()
示例#26
0
def _parser():
    """Take care of all the argparse stuff.

    :returns: the args
    """
    parser = GooeyParser(description='Plot 1D fits files with wavelength information in the header.')
    parser.add_argument('fname',
                        action='store',
                        widget='FileChooser',
                        help='Input fits file')
    parser.add_argument('-m', '--model',
                        default=False,
                        widget='FileChooser',
                        help='If not the Sun shoul be used as a model, put'
                        ' the model here (only support BT-Settl for the'
                        ' moment)',)
    parser.add_argument('-s', '--sun',
                        help='Over plot solar spectrum',
                        action='store_true')
    parser.add_argument('-t', '--telluric',
                        help='Over plot telluric spectrum',
                        action='store_true')
    parser.add_argument('-r', '--rv',
                        help='RV shift to observed spectra in km/s',
                        default=False,
                        type=float)
    parser.add_argument('-r1', '--rv1',
                        help='RV shift to model/solar spectrum in km/s',
                        default=False,
                        type=float)
    parser.add_argument('-r2', '--rv2',
                        help='RV shift to telluric spectra in km/s',
                        default=False,
                        type=float)
    parser.add_argument('-l', '--lines',
                        help='Lines to plot on top (multiple lines is an'
                        ' option). If multiple lines needs to be plotted, then'
                        ' separate with a space',
                        default=False,
                        nargs='+',
                        type=float)
    parser.add_argument('-c', '--ccf',
                        default='none',
                        choices=['none', 'sun', 'model', 'telluric', 'both'],
                        help='Calculate the CCF for Sun/model or tellurics '
                        'or both.')
    parser.add_argument('--ftype', help='Select which type the fits file is',
                        choices=['1D', 'CRIRES', 'GIANO'], default='1D')
    parser.add_argument('--fitsext', help='Select fits extention, Default 0.',
                        choices=['0', '1', '2', '3', '4'], default='0')
    parser.add_argument('--order', help='Select which GIANO order to be investigated',
                        choices=map(str, range(32,81)), default='77')
    return parser.parse_args()
def main():

    if CL_Flag == False:
        parser = GooeyParser(
            conflict_handler='resolve',
            description="Enter DNA or select or type a filename")

        parser.add_argument('input2',
                            type=str,
                            nargs='?',
                            help='Text',
                            widget="FileChooser")
        parser.add_argument('input0', type=int, nargs='?', help='K')
        parser.add_argument(
            'input1',
            type=str,
            nargs='*',
            help=
            'Profile: DNA without \' \" or , (s) or FileName of a properly formatted data dictionary',
            widget="FileChooser")

    if CL_Flag == True:
        parser = argparse.ArgumentParser(conflict_handler='resolve')
        parser.add_argument('input2',
                            type=str,
                            nargs='?',
                            help="Text file or raw")
        parser.add_argument('input0', type=int, nargs='?', help='K')
        parser.add_argument('input1',
                            type=str,
                            nargs='?',
                            help="Profile file or raw")

    args = parser.parse_args()
    valid_File = '/.tx'
    Flag_1 = False
    while Flag_1 == False:
        if args.input2 != None:
            s1 = args.input2
            if validSequence(s1) == True:
                Text = str(args.input2)
                Flag_1 = True
            if any(i in valid_File for i in str(args.input2)) == True:
                filename = str(args.input2)
                file = open(filename, "r")
                Text = file.read()
                Flag_1 = True

    Flag_1 = False
    while Flag_1 == False:
        if args.input1 != None:
            if len(str(args.input1)) < 30:
                if CL_Flag == False:
                    filename = str(args.input1[0])
                if CL_Flag == True:
                    filename = str(args.input1)
                file = open(filename, "r")
                Profile = file.read()
                Profile = eval(Profile)
                Flag_1 = True
            else:
                Profile = str(args.input1)
                Profile = Profile.replace('["{', '{')
                Profile = Profile.replace("]}']", "]}")
                Profile = Profile.replace(",', '", ", ")
                old = "\':\", \'["
                new = "\': ["
                Profile = Profile.replace(old, new)
                old = "],\', \""
                new = "] \'"
                Profile = Profile.replace(old, new)
                old = "] \'"
                new = "], "
                Profile = Profile.replace(old, new)
                Profile = eval(Profile)
                Flag_1 = True

    k = int(args.input0)
    print(ProfileMostProbableKmer(Text, k, Profile))
    return ProfileMostProbableKmer(Text, k, Profile)
示例#28
0
def param_parser():
    parser = GooeyParser(description="Tile Strip")
    sub_pars = parser.add_subparsers(help='commands', dest='command')
    main_parser = sub_pars.add_parser('Tilling', help='Tilling tool')
    main_parser.add_argument("input_folder",
                             metavar="Input Directory",
                             widget="DirChooser",
                             help="Select input las/laz files",
                             default='')
    main_parser.add_argument("output_dir",
                             metavar="Output Directory",
                             widget="DirChooser",
                             help="Output directory",
                             default="")
    main_parser.add_argument(
        "filepattern",
        metavar="Input File Pattern",
        help=
        "Provide a file pattern seperated by ';' for multiple patterns (*.laz or 123*_456*.laz;345*_789* )",
        default='*.las')
    main_parser.add_argument(
        "tile_size",
        metavar="Tile size",
        help="Select Size of Tile in meters [size x size]",
        choices=[
            '100', '250', '500', '1000', '2000', '5000', '10000', '20000'
        ],
        default='500')
    main_parser.add_argument(
        "datum",
        metavar="Datum",
        choices=['AGD84_AMG', 'AGD66_AMG', 'GDA94_MGA', 'GDA2020_MGA'],
        default='GDA94_MGA',
        help="NOTE: shifting function will not work for GDA2020")
    main_parser.add_argument(
        "zone",
        metavar="UTM Zone",
        choices=['49', '50', '51', '52', '53', '54', '55', '56'])
    main_parser.add_argument("-makeVLR",
                             metavar="Create VLR for header",
                             action='store_true',
                             default=False)
    main_parser.add_argument(
        "-VLRlocation",
        metavar="Output Directory for VLR",
        widget="DirChooser",
        help=
        "Please select the Correct project from \\10.10.10.142\projects\Projects"
    )
    shift_group = main_parser.add_argument_group(
        "Shift values",
        "* Keep blank if shifting is NOT required",
        gooey_options={
            'show_border': True,
            'columns': 3
        })
    shift_group.add_argument("--dx",
                             metavar="x shift",
                             type=float,
                             default=0.00)
    shift_group.add_argument("--dy",
                             metavar="y shift",
                             type=float,
                             default=0.00)
    shift_group.add_argument("--dz",
                             metavar="z shift",
                             type=float,
                             default=0.00)
    main_parser.add_argument("cores",
                             metavar="Number of Cores",
                             help="Number of cores",
                             type=int,
                             default=4)
    main_parser.add_argument("file_type",
                             metavar="Output File Type",
                             help="Select input file type",
                             choices=['las', 'laz'],
                             default='laz')
    main_parser.add_argument("-gen_block",
                             metavar="Generate Blocks",
                             help="Divide to blocks",
                             action='store_true',
                             default=False)
    main_parser.add_argument("-block_size",
                             metavar="Block size",
                             help="Block size",
                             type=int,
                             default=10000)
    vlr_gen_parser = sub_pars.add_parser('vlr_gen', help='Generate VLR')
    vlr_gen_parser.add_argument("inputfile",
                                metavar="LAS/Z file",
                                widget="FileChooser",
                                help="File with Correct Laz header",
                                default='')
    vlr_gen_parser.add_argument(
        "VLRlocation",
        metavar="Output Directory for VLR",
        widget="DirChooser",
        help=
        "Please select the Correct project from \\10.10.10.142\projects\Projects"
    )
    vlr_apply_parser = sub_pars.add_parser('vlr_apply', help='Apply VLR')
    vlr_apply_parser.add_argument(
        "inputfolder",
        metavar="Input Directory",
        widget="DirChooser",
        help="Directory with the inorrect Laz header files",
        default='')
    vlr_apply_parser.add_argument("outputfolder",
                                  metavar="Output Directory",
                                  widget="DirChooser",
                                  help="Output directory",
                                  default="")
    vlr_apply_parser.add_argument("filetype",
                                  metavar="Output File Type",
                                  help="Select input file type",
                                  choices=['las', 'laz'],
                                  default='laz')
    vlr_apply_parser.add_argument("VLRFile",
                                  metavar="Correct VLR File",
                                  widget="FileChooser",
                                  help="Please select the Correct VLR file")
    vlr_apply_parser.add_argument("cores",
                                  metavar="Number of Cores",
                                  help="Number of cores",
                                  type=int,
                                  default=8)
    args = parser.parse_args()
    return args
示例#29
0
def param_parser():

    stored_args = {}
    # get the script name without the extension & use it to build up
    # the json filename
    script_name = os.path.splitext(os.path.basename(__file__))[0]
    congifg_folder = AtlassGen.makedir("C:\\pythontools")
    args_file = os.path.join(congifg_folder,
                             "{}-args.json".format(script_name))
    # Read in the prior arguments as a dictionary
    if os.path.isfile(args_file):
        with open(args_file) as data_file:
            stored_args = json.load(data_file)

    parser = GooeyParser(description="Make Hydro Grids")
    sub_pars = parser.add_subparsers(help='commands', dest='command')
    step1_parser = sub_pars.add_parser(
        'Step_1', help='Preparation of Hydro voids as individual shp files')
    step1_parser.add_argument("laspath",
                              metavar="LAS files",
                              widget="DirChooser",
                              help="Select input las/laz file",
                              default=stored_args.get('laspath'))
    step1_parser.add_argument("filetype",
                              metavar="Input File type",
                              help="laz or las",
                              default='laz')
    step1_parser.add_argument("geojsonfile",
                              metavar="Input TileLayout file",
                              widget="FileChooser",
                              help="Select .json file",
                              default=stored_args.get('geojsonfile'))
    step1_parser.add_argument("deliverypath",
                              metavar="Output Directory",
                              widget="DirChooser",
                              help="Output directory(Storage Path)",
                              default=stored_args.get('deliverypath'))
    step1_parser.add_argument("workpath",
                              metavar="Working Directory",
                              widget="DirChooser",
                              help="Working directory",
                              default=stored_args.get('workpath'))
    step1_parser.add_argument("areaname",
                              metavar="AreaName",
                              default=stored_args.get('areaname'))
    step1_parser.add_argument("aoi",
                              metavar="Aoi Shp file",
                              widget="FileChooser",
                              default=stored_args.get('aoi'))
    step1_parser.add_argument("-s",
                              "--step",
                              metavar="Step",
                              help="Provide step",
                              type=float,
                              default=1.0)
    step1_parser.add_argument("-b",
                              "--buffer",
                              metavar="Buffer",
                              help="Provide buffer",
                              type=int,
                              default=200)
    step1_parser.add_argument("-k",
                              "--kill",
                              metavar="Kill",
                              help="Maximum triagulation length",
                              type=int,
                              default=250)
    step1_parser.add_argument("-co",
                              "--cores",
                              metavar="Cores",
                              help="No of cores to run in",
                              type=int,
                              default=8)
    step1_parser.add_argument("-hpfiles",
                              "--hydropointsfiles",
                              widget="MultiFileChooser",
                              metavar="Hydro Points Files",
                              help="Select files with Hydro points")
    output_group = step1_parser.add_argument_group(
        "Create the merge files only",
        "Run this only if the merge files does not get created in this step",
        gooey_options={
            'show_border': True,
            'columns': 3
        })
    output_group.add_argument("--createmerge",
                              metavar="Create Merge",
                              action='store_true',
                              default=False)
    output_group.add_argument(
        "--lazfiles",
        metavar="LAZ File Path",
        widget="DirChooser",
        help="Select folder of the laz files generated in step 1",
        default=stored_args.get('lazfiles'))
    step2_parser = sub_pars.add_parser(
        'Step_2',
        help=
        'Calculation of Elevation for each void- Run after global mapper step')
    step2_parser.add_argument(
        "shpfilepath",
        metavar="SHP File Path",
        widget="DirChooser",
        help="Select folder of the shp files generated from Global Mapper",
        default=stored_args.get('shpfilepath'))
    step2_parser.add_argument("demfolder",
                              metavar="DEM files",
                              widget="DirChooser",
                              help="Select the folder with the DEM files",
                              default=stored_args.get('demfolder'))
    step2_parser.add_argument("outputfolder",
                              metavar="Output folder",
                              widget="DirChooser",
                              help="Output folder for Hydro Laz file",
                              default=stored_args.get('outputdir'))
    step2_parser.add_argument("-co",
                              "--cores",
                              metavar="Cores",
                              help="No of cores to run in",
                              type=int,
                              default=8)
    step3_parser = sub_pars.add_parser(
        'Step_3',
        help=
        'Calculation of Elevation for each void- Run after global mapper step')
    step3_parser.add_argument("lazpath",
                              metavar="LAZ Path",
                              widget="DirChooser",
                              help="Select folder with Laz poly",
                              default=stored_args.get('lazpath'))
    step3_parser.add_argument("outputfolder",
                              metavar="Output folder",
                              widget="DirChooser",
                              help="Output folder for Hydro Laz file",
                              default=stored_args.get('outputdir'))
    step3_parser.add_argument("-co",
                              "--cores",
                              metavar="Cores",
                              help="No of cores to run in",
                              type=int,
                              default=8)

    args = parser.parse_args()

    # Store the values of the arguments so we have them next time we run
    with open(args_file, 'w') as data_file:
        # Using vars(args) returns the data as a dictionary
        json.dump(vars(args), data_file)

    return args
示例#30
0
def generate_trials_gui():
    # General information
    parser = GooeyParser(description='Create_general_experiment')
    parser.add_argument('Number_of_blocks', default=1, action='store', type=int, help='Number')
    parser.add_argument('Number_of_training_trials', default=4, action='store', type=int, help='Number')
    parser.add_argument('Number_of_experiment_trials', default=4, action='store', type=int, help='Number')
    parser.add_argument('File_name', default='experiment', type=str, help='Name of file with not personalized data')

    parser.add_argument('--Instruction', widget='FileChooser', help='Choose instruction file')
    parser.add_argument('--Instruction_show_time', default=5, action='store', type=int, help='Number')

    # Information about training
    parser.add_argument('--Training_task', default='letters',
                        choices=['letters', 'figures', 'symbols', 'numbers', 'greek_letters'],
                        help='Choose trial type')
    parser.add_argument('--Training_number', default=1, action='store', type=int, help='Number of relations')
    parser.add_argument('--Training_stim_time', default=1, action='store', type=int, help='Number')
    parser.add_argument('--Training_resp_time', default=1, action='store', type=int, help='Number')
    parser.add_argument('--Training_feedback', default=1, action='store', type=int, help='Number')
    parser.add_argument('--Training_feedback_time', default=1, action='store', type=int, help='Number')
    parser.add_argument('--Training_wait', default=1, action='store', type=int, help='Number')
    parser.add_argument('--Training_bin', default='1', choices=['1', '0'], help='Choose view type')
    parser.add_argument('--Training_trial_type', default='1', choices=['1', '2', '3', '4'], help='Choose view type')

    # Information about experiment
    parser.add_argument('--Experiment_task', default='letters',
                        choices=['letters', 'figures', 'symbols', 'numbers', 'greek_letters'],
                        help='Choose trial type')
    parser.add_argument('--Experiment_number', default=1, action='store', type=int, help='Number of relations')
    parser.add_argument('--Experiment_stim_time', default=1, action='store', type=int, help='Number')
    parser.add_argument('--Experiment_resp_time', default=1, action='store', type=int, help='Number')
    parser.add_argument('--Experiment_feedback', default=1, action='store', type=int, help='Number')
    parser.add_argument('--Experiment_feedback_time', default=1, action='store', type=int, help='Number')
    parser.add_argument('--Experiment_wait', default=1, action='store', type=int, help='Number')
    parser.add_argument('--Experiment_bin', default='1', choices=['1', '0'], help='Choose view type')
    parser.add_argument('--Experiment_trial_type', default='1', choices=['1', '2', '3', '4'], help='Choose view type')

    args = parser.parse_args()
    experiment = []

    name = args.Instruction.split('/')[-1]

    for block in range(args.Number_of_blocks):
        instruction = [block + 1, 'instruction', args.Instruction_show_time, name]
        experiment.append(instruction)
        for idx in range(0, args.Number_of_training_trials):
            trial = [block + 1, args.Training_task, args.Training_number, idx + 1, args.Training_stim_time,
                     args.Training_resp_time, args.Training_feedback, args.Training_feedback_time,
                     args.Training_wait, 0, int(args.Training_bin), int(args.Training_trial_type)]
            experiment.append(trial)
        for idx in range(0, args.Number_of_experiment_trials):
            trial = [block + 1, args.Experiment_task, args.Experiment_number, idx + 1, args.Experiment_stim_time,
                     args.Experiment_resp_time, args.Experiment_feedback, args.Experiment_feedback_time,
                     args.Experiment_wait, 1, int(args.Experiment_bin), int(args.Experiment_trial_type)]
            experiment.append(trial)

    save_to_xlsx(experiment, args.File_name)
示例#31
0
def main():
  desc = "Example application to show Gooey's various widgets"
  file_help_msg = "Name of the file you want to process"
  my_cool_parser = GooeyParser(description=desc)
  my_cool_parser.add_argument("FileChooser", help=file_help_msg, widget="FileChooser")   # positional
  my_cool_parser.add_argument("DirectoryChooser", help=file_help_msg, widget="DirChooser")   # positional
  my_cool_parser.add_argument("FileSaver", help=file_help_msg, widget="FileSaver")   # positional
  my_cool_parser.add_argument("MultiFileSaver", help=file_help_msg, widget="MultiFileChooser")   # positional
  my_cool_parser.add_argument("directory", help="Directory to store output")          # positional

  my_cool_parser.add_argument('-c', '--countdown', default=2, type=int, help='sets the time to count down from you see its quite simple!')
  my_cool_parser.add_argument('-j', '--cron-schedule', type=int, help='Set the datetime when the cron should begin', widget='DateChooser')
  my_cool_parser.add_argument("-s", "--showtime", action="store_true", help="display the countdown timer")
  my_cool_parser.add_argument("-d", "--delay", action="store_true", help="Delay execution for a bit")
  my_cool_parser.add_argument('-v', '--verbose', action='count')
  my_cool_parser.add_argument("-o", "--obfuscate", action="store_true", help="obfuscate the countdown timer!")
  my_cool_parser.add_argument('-r', '--recursive', choices=['yes', 'no'], help='Recurse into subfolders')
  my_cool_parser.add_argument("-w", "--writelog", default="No, NOT whatevs", help="write log to some file or something")
  my_cool_parser.add_argument("-e", "--expandAll", action="store_true", help="expand all processes")
  verbosity = my_cool_parser.add_mutually_exclusive_group()
  verbosity.add_argument('-t', '--verbozze', dest='verbose', action="store_true", help="Show more details")
  verbosity.add_argument('-q', '--quiet', dest='quiet', action="store_true", help="Only output on error")
  print my_cool_parser._actions
  print 'inside of main(), my_cool_parser =', my_cool_parser

  args = my_cool_parser.parse_args()
  print sys.argv
  print args.countdown
  print args.showtime

  start_time = _time()
  print 'Counting down from %s' % args.countdown
  while _time() - start_time < args.countdown:
    if args.showtime:
      print 'printing message at: %s' % _time()
    else:
      print 'printing message at: %s' % hashlib.md5(str(_time())).hexdigest()
    _sleep(.5)
  print 'Finished running the program. Byeeeeesss!'
示例#32
0
 def parse_args():
     parser = GooeyParser()
     parser.add_argument('study', choices=['nt', 'r01'])
     parser.add_argument('outdir',
                         widget='DirChooser',
                         help='where to store output CSV')
     parser.add_argument('db_password',
                         widget='PasswordField',
                         help='password for recruitment database')
     parser.add_argument('--from_date',
                         widget='DateChooser',
                         type=lambda d: datetime.strptime(d, '%Y-%m-%d'),
                         help='only check visits from this date on')
     return parser.parse_args()
示例#33
0
def parse_args(config, course_api_urls=None):
    def closest_name(choice):
        match = get_close_matches(choice.upper(), course_api_urls, 1, 0.2)
        if not match:
            raise ArgumentTypeError(
                "Could not find course in local database. "
                "Ensure that it has been downloaded at least once using URL.")
        return match[0]

    def validate_url(url):
        match = CATALOG_PAT.match(url)
        if not match:
            raise ArgumentTypeError("URL doesn't match required pattern.")
        return match["base"] + IMP_LECTURES_URL.format(match["subject"],
                                                       match["lec"])

    creds = config.get("creds", {})
    parser = GooeyParser(
        description=
        "A scraper for Impartus Lecture Capture videos for BITS Hyderabad")
    creds_group = parser.add_argument_group(
        "Credentials",
        ("Your impartus creds. (Only needed for login, "
         "you will be able download courses you aren't subscribed to.)"),
        gooey_options={"columns": 3},
    )
    creds_group.add_argument("-u", "--username", default=creds.get("username"))
    creds_group.add_argument("-p",
                             "--password",
                             default=creds.get("password"),
                             widget="PasswordField")
    creds_group.add_argument(
        "-s",
        "--save-creds",
        action="store_true",
        help=
        "Save credentials so that they can be automatically loaded in the future",
    )
    main_args = parser.add_argument_group(
        "Download options",
        gooey_options={"columns": 2 if course_api_urls else 1})
    if course_api_urls:
        course_group = main_args.add_mutually_exclusive_group(required=True)
        course_group.add_argument(
            "-n",
            "--name",
            choices=course_api_urls,
            type=closest_name,
            help="Name of previously downloaded course.",
        )
    else:
        course_group = main_args
    course_group.add_argument(
        "-c",
        "--course_url",
        type=validate_url,
        help=("Full impartus URL of course\n"
              "(Eg: http://172.16.3.20/ilc/#/course/12345/789)"),
        required=not course_api_urls,
    )
    range_group = main_args.add_mutually_exclusive_group()
    range_group.add_argument(
        "-r",
        "--range",
        default="",
        help="\n".join((
            "Range of lectures to be downloaded. Hint-",
            " 12 (Only 12 will be downloaded),",
            " 1:4 (1 included, 4 excluded),",
            " :10 (Download lecture numbers 1 to 9),",
            " 3: (Download all lectures from number 3 onwards).",
            "You can also specify multiple ranges using commas.",
            "Eg- 12, 4:6, 15:, :2 will download 1, 4, 5, 12, 15, 16, 17, ..."
            "Leave blank to download all.",
        )),
    )
    range_group.add_argument(
        "-o",
        "--only-new",
        action="store_true",
        help="Get all lectures after the last downloaded one.",
    )
    main_args.add_argument(
        "-a",
        "--angle",
        default="both",
        choices=ANGLE_CHOICES,
        help="The camera angle(s) to download",
    )
    main_args.add_argument(
        "-q",
        "--quality",
        default="720p",
        choices=["720p", "450p"],
        help="Video quality of the downloaded lectures",
    )
    main_args.add_argument(
        "-d",
        "--dest",
        default=config.get("save_fold", SCRIPT_DIR / "Impartus Lectures"),
        type=Path,
        help=f"Download folder",
        widget="DirChooser",
    )
    others = parser.add_argument_group("Other options",
                                       gooey_options={"columns": 4})
    others.add_argument(
        "-w",
        "--worker_processes",
        default=1,
        type=int,
        choices=[1, 2],  # no clear benefit of using more than 2 workers
        help="Maximum CPU cores to utilize (real number may vary).",
    )
    others.add_argument(
        "-f",
        "--force",
        action="store_true",
        help="Force overwrite downloaded lectures.",
    )
    others.add_argument(
        "-k",
        "--keep-no-class",
        action="store_true",
        help="Download lectures which have 'No class' in title.",
    )
    others.add_argument(
        "-R",
        "--rename",
        action="store_true",
        help=
        "Update downloaded lecture names with the current values from impartus",
    )
    return parser.parse_args()
示例#34
0
def parse_args_and_execute():
    """ Parse args and run bg-process(es) """
    global fw_name
    global mcu_name
    #
    parser = GooeyParser()
    #
    # Std.args NOT needing 'special handling':
    id_group = parser.add_argument_group(
        "System ID Options", "Customize product ID, serial number etc.")
    id_group.add_argument(
        '--serial',
        '-s',
        action="store",
        dest="ser_num",
        type=int,
        help='Serial number to be programmed into upper 4 bytes of Flash',
        gooey_options={
            'height': 100,
            'full_width': 10,
            'hide_heading': True,
            'columns': 1 - 100,
        })
    fw_group = parser.add_argument_group("Firmware Options", "Choose FW etc.")
    fw_group.add_argument(
        '--fw',
        action="store",
        dest="fw_name",
        type=str,
        default="",
        widget='FileChooser',
        help="Firmware HEX/SREC file name (default: 'firmware.hex')",
        gooey_options={
            'height': 100,
            'hide_heading': True,
            'columns': 1 - 100,
        })
    #
    device_group = parser.add_argument_group("Device Options",
                                             "Choose MCU type etc.")
    mcu_types_list = list(mcu_targets.keys())
    device_group.add_argument('--device',
                              '-d',
                              action="store",
                              dest="mcu_name",
                              choices=mcu_types_list,
                              type=str,
                              default="kl16z256",
                              widget='Dropdown',
                              help='Kinetis KL-family MCU type.',
                              gooey_options={
                                  'height': 100,
                                  'width': 8,
                                  'hide_heading': True,
                                  'columns': 1,
                              })
    #
    flash_group = parser.add_argument_group("Flash Options",
                                            "Erase-before-program etc.")
    flash_group.add_argument(
        "-e",
        "--erase",
        action="store_true",
        dest="erase_first",
        default=True,
        widget='CheckBox',
        help='Erase target (completely) before programming',
        gooey_options={
            'height': 100,
            'hide_heading': True,
            'columns': 1,
        })
    #
    cli_args = parser.parse_args(sys.argv[1:])
    # Assign program arguments to variables:
    # ======================================
    # FW serial number:
    if cli_args.ser_num is None:
        print(
            "Argument '-s' ('--serial') is required - a serial number MUST be specified!"
        )
        sys.exit(1)
    else:
        serial_num = cli_args.ser_num
    # FW file name:
    if cli_args.fw_name is None:
        # Should NEVER happen - maybe simplify this?
        print("Using 'firmware.hex' for default firmware-name ...")
        fw_name = 'firmware.hex'  # TODO: assess - rather have this as required field???
    else:
        fw_name = cli_args.fw_name
        print("Using %s as firmware-name ..." % fw_name)
    # MCU device:
    if cli_args.mcu_name is None:
        # Should NEVER happen - maybe simplify this?
        print("Using 'kl16z256' for default MCU device-name ...")
        mcu_name = 'kl16z256'  # TODO: assess - rather have this as required field???
    else:
        mcu_name = cli_args.mcu_name
        print("Using %s as MCU-name ..." % mcu_name)
    # Erase (via MassErase) target Flash first or not:
    erase_flash_first = cli_args.erase_first

    # Run:
    # ====
    # Test only:
    # ----------
    # ret_val = run_fw_programming(fw_name, serial_num, erase_flash_first, cleanup=False, debug=True)
    # ----------
    # Non-test environment:
    # ---------------------
    status1 = run_fw_programming(fw_name, serial_num, erase_flash_first)
    status2 = run_fw_verification(serial_num)
    #
    print("\r\n\r\n================================")
    if status1 and status2:
        print("PASS: successful programming.", flush=True)
    else:
        print("FAIL: programming error!!", flush=True)
    print("================================\r\n", flush=True)
    #
    print("Completed FW-programming.", flush=True)
示例#35
0
def copyright_main():
    parser = GooeyParser(description="automatically set the copyright for you")
    parser.add_argument("-p",
                        "--path",
                        widget="DirChooser",
                        help="choose the path you want to add the copyright")
    parser.add_argument("-t", "--title", help="add the copyright title")
    parser.add_argument("-l",
                        "--license",
                        help="add the license name for the copyright")
    parser.add_argument("-y",
                        "--year",
                        help="add the year the production was made")
    parser.add_argument("-o",
                        "--owner",
                        help="add the owner of the production")
    parser.add_argument("--config",
                        widget="FileChooser",
                        help="add the config file")
    parser.add_argument("-d",
                        "--description",
                        help="add description of the program")
    parser.add_argument("-c",
                        "--cversion",
                        help="add the version of the production")
    parser.add_argument("-u",
                        "--update",
                        help="add the latest time that you updated")
    parser.add_argument("-f",
                        "--file",
                        help="add the file name of the program")
    args = parser.parse_args()
    if args.config:
        try:
            with open(args.config, "r", encoding="utf-8") as f:
                content = f.read()
                info = json.loads(content)
                try:
                    args.path = info["path"]
                    args.title = info["title"]
                    args.license = info["license"]
                    args.year = info["year"]
                    args.owner = info["owner"]
                except Exception as e:
                    print("Argument not find!")
                    sys.exit()
                try:
                    args.description = info["description"]
                except Exception as e:
                    pass
                try:
                    args.cversion = info["cversion"]
                except Exception as e:
                    pass
                try:
                    args.update = info["update"]
                except Exception as e:
                    pass
                try:
                    args.file = info["file"]
                except Exception as e:
                    pass
        except Exception as e:
            print("File not exists!")
            sys.exit()
    data = '"""\n'
    data += "Copyright: Copyright (c) " + args.year + "\n"
    data += "License : " + args.license + "\n"
    data += "owner : " + args.owner + "\n"
    data += "title : " + args.title + "\n"
    if args.description:
        data += "description : " + args.description + "\n"
    if args.cversion:
        data += "version : " + args.cversion + "\n"
    if args.update:
        data += "time : " + args.update + "\n"
    if args.file:
        data += "file : " + args.file + "\n"
    data += '"""\n\n'

    for root, dirs, files in os.walk(args.path):
        for file in files:
            with open(root + "/" + file, "r+", encoding="utf-8") as f:
                old = f.read()
                f.seek(0)
                f.write(data)
                f.write(old)
示例#36
0
def main():


    if CL_Flag == False:
        parser = GooeyParser(conflict_handler='resolve', description="Enter DNA or select or type a filename")
        parser.add_argument('infile_1', nargs='?', help='Text: DNA or FileName' , widget="FileChooser")
        parser.add_argument('infile_2', nargs='?', help='Pattern: DNA or FileName' , widget="FileChooser")
        parser.add_argument('d', nargs='?', help='Number', type=int)        
        args = parser.parse_args()
        
    if CL_Flag == True:
        parser = argparse.ArgumentParser(conflict_handler='resolve')
        parser.add_argument('infile_1', nargs='?', help="Text" )
        parser.add_argument('infile_2', nargs='?', help="Pattern" )
        parser.add_argument('d', nargs='?', type=int, help="d" )
        args = parser.parse_args()
    
        
#    print("Debug 1"," args.infile_1:",args.infile_1," args.infile_2:", args.infile_2)
    valid_DNA = 'ACTGU'
    d = args.d
    Flag_1 = False
    while Flag_1 == False:
#        if args.infile_1 != None and  args.infile_2 != None:
           for letter in str(args.infile_1):
               if letter not in valid_DNA:
                   infile_lst_1 = args.infile_1
                   filename_1 = str(infile_lst_1)
                   file_1 = open(filename_1, "r")
                   Text = str(file_1.read())
                   Flag_1 = True
               elif all(i in valid_DNA for i in str(args.infile_1)) == True:
                   Text = str(args.infile_1)
                   Flag_1 = True
               else:
                   Text = args.infile_1
                   Flag_1 = True
                   
    Flag_2 = False
    while Flag_2 == False:
#        if args.infile_1 != None and  args.infile_2 != None:
           for letter in str(args.infile_2):
               if letter not in valid_DNA:
                   infile_lst_2 = args.infile_2
                   filename_2 = str(infile_lst_2)
                   file_2 = open(filename_2, "r")
                   Pattern = str(file_2.read())
                   Flag_2 = True
               elif all(i in valid_DNA for i in str(args.infile_2)) == True:
                   Pattern = str(args.infile_2)
                   Flag_2 = True        
               else:
                   Pattern = args.infile_2
                   Flag_2 = True
       
#    print("Debug 2"," q:",q," p:",p," args.infile_1:",args.infile_1," args.infile_2:", args.infile_2)
  
    
    
    print(ApproximatePatternCount(Pattern, Text, d))
    return ApproximatePatternCount(Pattern, Text, d)
示例#37
0
def cli():
    # simple converter takes command line arguments <folder path> <destination path> <subject-id> <session-id>
    parser = GooeyParser()
    parser.add_argument('folder',
                        type=str,
                        help="Folder path containing imaging data",
                        widget="DirChooser",
                        gooey_options=item_default)
    parser.add_argument('-m',
                        '--metadata-path',
                        type=str,
                        help="Path to metadata file for scan",
                        widget="FileChooser",
                        gooey_options=item_default)
    parser.add_argument(
        '-t',
        '--translation-script-path',
        widget='FileChooser',
        gooey_options=item_default,
        help=
        "Path to a script written to extract and transform metadata from a spreadsheet to BIDS"
        + " compliant text files (tsv and json)")
    parser.add_argument(
        '-d',
        '--destination-path',
        type=str,
        gooey_options=item_default,
        help=
        "Destination path to send converted imaging and metadata files to. If "
        +
        "omitted defaults to using the path supplied to folder path. If destination path "
        + "doesn't exist an attempt to create it will be made.",
        required=False,
        widget="DirChooser")
    parser.add_argument(
        '-i',
        '--subject-id',
        type=str,
        gooey_options=item_default,
        help=
        'user supplied subject id. If left blank will use PatientName from dicom header',
        required=False)
    parser.add_argument(
        '-s',
        '--session_id',
        type=str,
        gooey_options=item_default,
        help="User supplied session id. If left blank defaults to " +
        "None/null and omits addition to output")

    args = parser.parse_args()

    if not isdir(args.folder):
        raise FileNotFoundError(f"{args.folder} is not a valid path")

    converter = Convert(
        image_folder=args.folder,
        metadata_path=args.metadata_path,
        destination_path=args.destination_path,
        metadata_translation_script_path=args.translation_script_path,
        subject_id=args.subject_id,
        session_id=args.session_id)

    # convert it all!
    converter.run_dcm2niix()
    if args.metadata_path and args.translation_script_path:
        converter.bespoke()
        converter.write_out_jsons()
        converter.write_out_blood_tsv()
示例#38
0
def main():
    parser = GooeyParser()
    subs = parser.add_subparsers(help='commands', dest='command')

    parser_one = subs.add_parser('parser1', prog="Parser 1")
    parser_one.add_argument('--textfield', default=2, widget="TextField")
    parser_one.add_argument('--textarea',
                            default="oneline twoline",
                            widget='Textarea')
    parser_one.add_argument('--password',
                            default="hunter42",
                            widget='PasswordField')
    parser_one.add_argument('--commandfield',
                            default="cmdr",
                            widget='CommandField')
    parser_one.add_argument('--dropdown',
                            choices=["one", "two"],
                            default="two",
                            widget='Dropdown')
    parser_one.add_argument(
        '--listboxie',
        nargs='+',
        default=['Option three', 'Option four'],
        choices=['Option one', 'Option two', 'Option three', 'Option four'],
        widget='Listbox',
        gooey_options={
            'height': 300,
            'validate': '',
            'heading_color': '',
            'text_color': '',
            'hide_heading': True,
            'hide_text': True,
        })
    parser_one.add_argument('-c',
                            '--counter',
                            default=3,
                            action='count',
                            widget='Counter')
    #
    parser_one.add_argument("-o",
                            "--overwrite",
                            action="store_true",
                            default=True,
                            widget='CheckBox')

    ### Mutex Group ###
    verbosity = parser_one.add_mutually_exclusive_group(
        required=True, gooey_options={'initial_selection': 1})
    verbosity.add_argument('--mutexone',
                           default=True,
                           action='store_true',
                           help="Show more details")

    verbosity.add_argument('--mutextwo', default='mut-2', widget='TextField')

    parser_one.add_argument("--filechooser",
                            default="fc-value",
                            widget='FileChooser')
    parser_one.add_argument("--filesaver",
                            default="fs-value",
                            widget='FileSaver')
    parser_one.add_argument("--dirchooser",
                            default="dc-value",
                            widget='DirChooser')
    parser_one.add_argument("--datechooser",
                            default="2015-01-01",
                            widget='DateChooser')

    parser_two = subs.add_parser('parser2', prog="parser 2")
    parser_two.add_argument('--textfield', default=2, widget="TextField")
    parser_two.add_argument('--textarea',
                            default="oneline twoline",
                            widget='Textarea')
    parser_two.add_argument('--password',
                            default="hunter42",
                            widget='PasswordField')
    parser_two.add_argument('--commandfield',
                            default="cmdr",
                            widget='CommandField')
    parser_two.add_argument('--dropdown',
                            choices=["one", "two"],
                            default="two",
                            widget='Dropdown')
    parser_two.add_argument(
        '--listboxie',
        nargs='+',
        default=['Option three', 'Option four'],
        choices=['Option one', 'Option two', 'Option three', 'Option four'],
        widget='Listbox',
        gooey_options={
            'height': 300,
            'validate': '',
            'heading_color': '',
            'text_color': '',
            'hide_heading': True,
            'hide_text': True,
        })
    parser_two.add_argument('-c',
                            '--counter',
                            default=3,
                            action='count',
                            widget='Counter')
    #
    parser_two.add_argument("-o",
                            "--overwrite",
                            action="store_true",
                            default=True,
                            widget='CheckBox')

    ### Mutex Group ###
    verbosity = parser_two.add_mutually_exclusive_group(
        required=True, gooey_options={'initial_selection': 1})
    verbosity.add_argument('--mutexone',
                           default=True,
                           action='store_true',
                           help="Show more details")

    verbosity.add_argument('--mutextwo', default='mut-2', widget='TextField')

    parser_two.add_argument("--filechooser",
                            default="fc-value",
                            widget='FileChooser')
    parser_two.add_argument("--filesaver",
                            default="fs-value",
                            widget='FileSaver')
    parser_two.add_argument("--dirchooser",
                            default="dc-value",
                            widget='DirChooser')
    parser_two.add_argument("--datechooser",
                            default="2015-01-01",
                            widget='DateChooser')

    dest_vars = [
        'textfield', 'textarea', 'password', 'commandfield', 'dropdown',
        'listboxie', 'counter', 'overwrite', 'mutextwo', 'filechooser',
        'filesaver', 'dirchooser', 'datechooser'
    ]

    parser.parse_args()

    args = parser.parse_args()
    import time
    time.sleep(.6)
    for i in dest_vars:
        assert getattr(args, i) is not None
    print("Success")
def show_gui(p_input_file_argument):
    parser = GooeyParser(
        description="https://github.com/LeoFCardoso/pdf2pdfocr")
    #
    files_group = parser.add_argument_group("Files",
                                            gooey_options={'columns': 1})
    files_group.add_argument("-i",
                             dest="input_file",
                             metavar="Input file",
                             action="store",
                             required=True,
                             widget="FileChooser",
                             default=p_input_file_argument,
                             help="path for input file")
    files_group.add_argument(
        "-o",
        dest="output_file",
        metavar="Output file",
        action="store",
        required=False,
        widget="FileChooser",
        help="force output file to the specified location (optional)")
    #
    basic_options = parser.add_argument_group("Basic options")
    basic_options.add_argument(
        "-s",
        dest="safe_mode",
        metavar='Safe (-s)',
        action="store_true",
        default=False,
        help="Does not overwrite output [PDF | TXT] OCR file ")
    basic_options.add_argument(
        "-t",
        dest="check_text_mode",
        metavar='Check text (-t)',
        action="store_true",
        default=False,
        help="Does not process if source PDF already has text ")
    basic_options.add_argument(
        "-a",
        dest="check_protection_mode",
        metavar='Check encryption (-a)',
        action="store_true",
        default=False,
        help="Does not process if source PDF is protected ")
    basic_options.add_argument(
        "-b",
        dest="max_pages",
        metavar='Max pages (-b)',
        action="store",
        default=None,
        type=int,
        help="Does not process if number of pages is greater than this value ")
    basic_options.add_argument(
        "-d",
        dest="deskew_percent",
        metavar='Deskew (-d)',
        action="store",
        help=
        "Use imagemagick deskew before OCR. Should be a percent, e.g. '40%' ")
    basic_options.add_argument(
        "-w",
        dest="create_text_mode",
        metavar='Text file (-w)',
        action="store_true",
        default=False,
        help=
        "Create a text file at same location of PDF OCR file [tesseract only] "
    )
    basic_options.add_argument(
        "-u",
        dest="autorotate",
        metavar='Autorotate (-u)',
        action="store_true",
        default=False,
        help="Try to autorotate pages using 'psm 0' feature [tesseract only] ")
    basic_options.add_argument("-v",
                               dest="verbose_mode",
                               metavar='Verbose (-v)',
                               action="store_true",
                               default=True,
                               help="enable verbose mode ")
    #
    rebuild_options = parser.add_argument_group("Rebuild options",
                                                gooey_options={'columns': 1})
    rebuild_options.add_argument(
        "-f",
        dest="force_rebuild_mode",
        metavar='Force rebuild (-f)',
        action="store_true",
        default=False,
        help="Force PDF rebuild from extracted images ")
    option_g_help = """With images or '-f', use presets or force parameters when calling 'convert' to build the final PDF file
    Examples:
        -g fast -> a fast bitonal file ("-threshold 60% -compress Group4")
        -g best -> best quality, but bigger bitonal file ("-colors 2 -colorspace gray -normalize -threshold 60% -compress Group4")
        -g grayscale -> good bitonal file from grayscale documents ("-threshold 85% -morphology Dilate Diamond -compress Group4")
        -g jpeg -> keep original color image as JPEG ("-strip -interlace Plane -gaussian-blur 0.05 -quality 50% -compress JPEG")
        -g jpeg2000 -> keep original color image as JPEG2000 ("-quality 32% -compress JPEG2000")
        -g="-threshold 60% -compress Group4" -> direct apply these parameters (USE EQUAL SIGN AND QUOTATION MARKS)
        Note, without -g, preset 'best' is used
    """
    rebuild_options.add_argument(
        "-g",
        dest="convert_params",
        metavar='Force params (-g)',
        action="store",
        default="",
        help=option_g_help,
        widget="Dropdown",
        choices=["", "fast", "best", "grayscale", "jpeg", "jpeg2000"])
    #
    advanced_options = parser.add_argument_group("Advanced options")
    advanced_options.add_argument("-c",
                                  dest="ocr_engine",
                                  metavar='OCR engine (-c)',
                                  action="store",
                                  type=str,
                                  default="tesseract",
                                  help="select the OCR engine to use ",
                                  widget="Dropdown",
                                  choices=["tesseract", "cuneiform"])
    advanced_options.add_argument(
        "-j",
        dest="parallel_percent",
        metavar='Parallel (-j)',
        action="store",
        type=float,
        default=1.0,
        help=
        "run this percentual jobs in parallel (0 - 1.0]\nmultiply with the number of CPU cores, default = 1 [all "
        "cores] ")
    advanced_options.add_argument(
        "-r",
        dest="image_resolution",
        metavar='Resolution (-r)',
        action="store",
        default=300,
        type=int,
        help=
        "specify image resolution in DPI before OCR operation\nlower is faster, higher improves OCR quality, default "
        "is for quality = 300")
    advanced_options.add_argument(
        "-e",
        dest="text_generation_strategy",
        metavar='Text generation (-e)',
        action="store",
        default="tesseract",
        type=str,
        help=
        "specify how text is generated in final pdf file [tesseract only] ",
        widget="Dropdown",
        choices=["tesseract", "native"])
    advanced_options.add_argument(
        "-l",
        dest="tess_langs",
        metavar='Languages (-l)',
        action="store",
        required=False,
        default="por",
        help="force tesseract or cuneiform to use specific language ")
    advanced_options.add_argument(
        "-m",
        dest="tess_psm",
        metavar='Tesseract PSM (-m)',
        action="store",
        required=False,
        help=
        "force tesseract to use HOCR with specific \"pagesegmode\"\n(default: tesseract "
        "HOCR default = 1) [tesseract only]. Use with caution ")
    advanced_options.add_argument(
        "-x",
        dest="extra_ocr_flag",
        metavar='Extra OCR parameters (-x)',
        action="store",
        required=False,
        default="",
        help=
        "add extra command line flags in select OCR engine for all pages.\nUse with caution "
    )
    advanced_options.add_argument("-k",
                                  dest="keep_temps",
                                  metavar='Keep temps (-k)',
                                  action="store_true",
                                  default=False,
                                  help="keep temporary files for debug ")
    #
    return parser.parse_args()
示例#40
0
 def makeParser(self, **kwargs):
     parser = GooeyParser(description='description')
     parser.add_argument('--widget', widget="Listbox", nargs="*", **kwargs)
     return parser
def main():
    parser = GooeyParser(
        description=
        'Plot a single datasheet for a each raw file in a given directory.\nRequires "ms_datasheet", "pyextractMS", "MSFileReader", numpy, matplotlib'
    )
    parser.add_argument('directory',
                        type=str,
                        help='path to the directory to analyze',
                        widget='DirChooser')
    parser.add_argument('--display',
                        default=True,
                        action='store_false',
                        help='just display the plots, but do not save them')
    parser.add_argument('--extension',
                        default='.pdf',
                        type=str,
                        help='string for figure filetype (e.g. .pdf, .png)')
    parser.add_argument(
        '--spectra_rt_range',
        default='40,80',
        type=str,
        help=
        'RT range over which to calculate spectra histograms; format is start,end. e.g. --spectra_rt_range 1,120'
    )
    parser.add_argument(
        '--tic_rt_range',
        default='1,120',
        type=str,
        help=
        'RT range over which to plot tics; format is start,end. e.g. --tic_rt_range 1,120'
    )
    parser.add_argument(
        '--exclude_iRTs',
        default=False,
        action='store_true',
        help=
        'exclude XICs, MS1, MS2 spectra for standard iRT peptides at expected retention times. Default is to include this information.\
do not use this option unless you have not added pierce iRT peptides in your sample'
    )

    args = parser.parse_args()

    directory = vars(args)['directory']
    savefig = vars(args)['display']
    fig_extension = vars(args)['extension']
    spectra_rt_range = vars(args)['spectra_rt_range']
    tic_rt_range = vars(args)['tic_rt_range']
    exclude_iRTs = vars(args)['exclude_iRTs']

    all_files = glob.glob(directory + '/*.raw')

    print('****to do the same from the commandline, run the following:')
    command = 'python ms_datasheet_multi.py ' + directory + '/ --spectra_rt_range ' + spectra_rt_range + ' --tic_rt_range ' + tic_rt_range + ' --extension ' + fig_extension
    if not savefig:
        command += ' --display'
    if exclude_iRTs:
        command += ' --exclude_iRTs'

    print(command)

    print('/n*****analyzing the following files:')
    print(all_files)
    for file_name in all_files:
        print('****analyzing: ' + file_name + '...')
        ms_datasheet.plot_datapage(file_name,
                                   savefig=savefig,
                                   fig_extension=fig_extension,
                                   colors=cm.get_cmap(name='plasma'),
                                   spectra_rt_range=spectra_rt_range,
                                   tic_rt_range=tic_rt_range,
                                   exclude_iRTs=exclude_iRTs)
        print('****completed: ' + file_name)
示例#42
0
def main():
    desc = "Example application to show Gooey's various widgets"
    file_help_msg = "Name of the file you want to process"

    my_cool_parser = GooeyParser(description=desc)

    my_cool_parser.add_argument("FileChooser",
                                help=file_help_msg,
                                widget="FileChooser")
    my_cool_parser.add_argument("DirectoryChooser",
                                help=file_help_msg,
                                widget="DirChooser")
    my_cool_parser.add_argument("FileSaver",
                                help=file_help_msg,
                                widget="FileSaver")
    my_cool_parser.add_argument("MultiFileChooser",
                                nargs='*',
                                help=file_help_msg,
                                widget="MultiFileChooser")
    my_cool_parser.add_argument("directory", help="Directory to store output")

    my_cool_parser.add_argument(
        '-d',
        '--duration',
        default=2,
        type=int,
        help='Duration (in seconds) of the program output')
    my_cool_parser.add_argument('-s',
                                '--cron-schedule',
                                type=int,
                                help='datetime when the cron should begin',
                                widget='DateChooser')
    my_cool_parser.add_argument('--cron-time',
                                help='datetime when the cron should begin',
                                widget="TimeChooser")
    my_cool_parser.add_argument("-c",
                                "--showtime",
                                action="store_true",
                                help="display the countdown timer")
    my_cool_parser.add_argument("-p",
                                "--pause",
                                action="store_true",
                                help="Pause execution")
    my_cool_parser.add_argument('-v', '--verbose', action='count')
    my_cool_parser.add_argument("-o",
                                "--overwrite",
                                action="store_true",
                                help="Overwrite output file (if present)")
    my_cool_parser.add_argument('-r',
                                '--recursive',
                                choices=['yes', 'no'],
                                help='Recurse into subfolders')
    my_cool_parser.add_argument("-w",
                                "--writelog",
                                default="writelogs",
                                help="Dump output to local file")
    my_cool_parser.add_argument("-e",
                                "--error",
                                action="store_true",
                                help="Stop process on error (default: No)")
    verbosity = my_cool_parser.add_mutually_exclusive_group()
    verbosity.add_argument('-t',
                           '--verbozze',
                           dest='verbose',
                           action="store_true",
                           help="Show more details")
    verbosity.add_argument('-q',
                           '--quiet',
                           dest='quiet',
                           action="store_true",
                           help="Only output on error")

    my_cool_parser.parse_args()
    display_message()
示例#43
0
def parse_args():
    settings_msg = 'Bring torrents from one Gazelle instance to another'
    parser = GooeyParser(description=settings_msg)

    # --from <>
    parser.add_argument('--from',
                        choices=trackers,
                        required=True,
                        help="torrents from which Gazelle instance")

    # -to <>
    parser.add_argument("--to",
                        choices=trackers,
                        required=True,
                        help="sync to which Gazelle instance")

    # --album <> / --folder <>
    group = parser.add_mutually_exclusive_group(
        required=True, gooey_options={'initial_selection': 0})
    group.add_argument("--album",
                       help="the folder of the album",
                       widget="DirChooser")
    group.add_argument(
        "--folder",
        help=
        "the folder that contauins all albums. The album folder will be extracted from the site metadata",
        widget="DirChooser")

    # --tid <> / --link <> / --tpath <> / --tfolder <>
    group = parser.add_mutually_exclusive_group(
        required=True, gooey_options={'initial_selection': 0})
    group.add_argument(
        "--link",
        help="the whole permalinlk. The tool os smart enough to extract it")
    group.add_argument("--tid", help="the torrent ID")
    group.add_argument(
        "--tpath",
        help=
        "the path that points towards the .torrent file. The infohash will be computed",
        widget="FileChooser")
    group.add_argument("--tfolder",
                       help="the folder containing all the .torrent files",
                       widget="DirChooser")

    parser.add_argument(
        '-c',
        '--config',
        metavar='FILE',
        default=os.path.join(application_path, 'config.cfg'),
        help='config file with login details (default: config.cfg)',
        widget="FileChooser")

    return parser.parse_args()
示例#44
0
def add(parser: GooeyParser = GooeyParser()) -> GooeyParser:

    parser.add_argument('data_path',
                        widget='FileChooser',
                        metavar='Data Path',
                        help="Data path (file path of .txt format)")

    parser.add_argument(
        #Okt(previous Twitter)
        "--tagger_name",
        type=str,
        choices=['Kkma', 'Komoran', 'Hannaunm', 'Okt'],
        metavar='Tagger',
        default='Okt',
        help='Select a tagger for POS tagging')

    parser.add_argument("--tokenizer_fname",
                        metavar="Tokenizer file name(Train mode only)",
                        type=str,
                        default='tokenizer.pkl',
                        help='tokenizer will be saved with this name')

    parser.add_argument('--tokenizer_path',
                        widget='FileChooser',
                        metavar='Tokenizer path(Test mode only)',
                        help="please select a tokenizer file to use..")

    parser.add_argument("--rm_duplicate",
                        metavar='Remove duplicate data',
                        action="store_true",
                        default=True,
                        help='Check if you want to remove duplicate rows')

    parser.add_argument(
        "--threshold",
        type=int,
        metavar='threshold of word frequency',
        default=3,
        help='Minimum occurrence of a word to be included in the vocabulary')

    parser.add_argument(
        "--max_sentence_len",
        type=int,
        metavar=
        'max length of a sentence(should be exactly the same with model input size)',
        default=30)
    return parser
示例#45
0
def parse_cli():
    """Create Gooey GUI."""
    defs = GuiDefaultOptions()
    parser = GooeyParser(description="Download videos from coub.com",
                         usage="%(prog)s [OPTIONS] INPUT [INPUT]...")

    # Input
    input_ = parser.add_argument_group(
        "Input",
        description="Specify various input sources\n\n"
        "All input fields support several items (i.e. names, IDs, "
        "tags, etc.). Items must be comma-separated.",
        gooey_options={'columns': 1})
    input_.add_argument("--urls",
                        default="",
                        metavar="Direct URLs",
                        help="Provide direct URL input")
    input_.add_argument("--ids",
                        default="",
                        metavar="Coub IDs",
                        help="Download coubs with the given IDs")
    input_.add_argument("--channels",
                        default="",
                        metavar="Channels",
                        help="Download channels with the given names")
    input_.add_argument("--recoubs",
                        metavar="Recoubs",
                        default=defs.RECOUB_LABEL[defs.RECOUBS],
                        choices=["No Recoubs", "With Recoubs", "Only Recoubs"],
                        help="How to treat recoubs during channel downloads")
    input_.add_argument(
        "--tags",
        default="",
        metavar="Tags",
        help="Download coubs with at least one of the given tags")
    input_.add_argument("--searches",
                        default="",
                        metavar="Search Terms",
                        help="Download search results for the given terms")
    input_.add_argument("--communities",
                        default="",
                        metavar="Communities",
                        help="Download coubs from the given communities")
    input_.add_argument("--lists",
                        default="",
                        widget="MultiFileChooser",
                        metavar="Link Lists",
                        help="Read coub links from input lists",
                        gooey_options={'message': "Choose link lists"})
    input_.add_argument("--random",
                        action="count",
                        metavar="Random",
                        help="Download N*1000 randomly generated coubs")
    input_.add_argument("--hot",
                        action="store_true",
                        widget="BlockCheckbox",
                        metavar="Hot Section",
                        help="Download coubs from the hot section")

    # Common Options
    common = parser.add_argument_group("General", gooey_options={'columns': 1})
    common.add_argument("--prompt",
                        choices=["yes", "no"],
                        default=defs.PROMPT,
                        metavar="Prompt Behavior",
                        help="How to answer user prompts")
    common.add_argument("--repeat",
                        type=coub.positive_int,
                        default=defs.REPEAT,
                        metavar="Loop Count",
                        help="How often to loop the video stream")
    common.add_argument("--duration",
                        type=coub.valid_time,
                        default=defs.DURATION,
                        metavar="Limit duration",
                        help="Max. duration of the output (FFmpeg syntax)")
    common.add_argument("--preview",
                        default=defs.PREVIEW,
                        metavar="Preview Command",
                        help="Command to invoke to preview each finished coub")
    common.add_argument(
        "--archive",
        type=coub.valid_archive,
        default=defs.ARCHIVE,
        widget="FileSaver",
        metavar="Archive",
        gooey_options={'message': "Choose archive file"},
        help="Use an archive file to keep track of already downloaded coubs")
    common.add_argument(
        "--keep",
        action="store_const",
        const=True,
        default=defs.KEEP,
        widget="BlockCheckbox",
        metavar="Keep streams",
        help="Whether to keep the individual streams after merging")

    # Download Options
    download = parser.add_argument_group("Download",
                                         gooey_options={'columns': 1})
    download.add_argument(
        "--connections",
        type=coub.positive_int,
        default=defs.CONNECTIONS,
        metavar="Number of connections",
        help="How many connections to use (>100 not recommended)")
    download.add_argument(
        "--retries",
        type=int,
        default=defs.RETRIES,
        metavar="Retry Attempts",
        help="How often to reconnect to Coub after connection loss "
        "(<0 for infinite retries)")
    download.add_argument("--max-coubs",
                          type=coub.positive_int,
                          default=defs.MAX_COUBS,
                          metavar="Limit Quantity",
                          help="How many coub links to parse")

    # Format Selection
    formats = parser.add_argument_group("Format", gooey_options={'columns': 1})
    formats.add_argument("--v-quality",
                         choices=["Best quality", "Worst quality"],
                         default=defs.QUALITY_LABEL[defs.V_QUALITY],
                         metavar="Video Quality",
                         help="Which video quality to download")
    formats.add_argument("--a-quality",
                         choices=["Best quality", "Worst quality"],
                         default=defs.QUALITY_LABEL[defs.A_QUALITY],
                         metavar="Audio Quality",
                         help="Which audio quality to download")
    formats.add_argument(
        "--v-max",
        choices=["med", "high", "higher"],
        default=defs.V_MAX,
        metavar="Max. Video Quality",
        help="Cap the max. video quality considered for download")
    formats.add_argument(
        "--v-min",
        choices=["med", "high", "higher"],
        default=defs.V_MIN,
        metavar="Min. Video Quality",
        help="Cap the min. video quality considered for download")
    formats.add_argument(
        "--aac",
        default=defs.AAC_LABEL[defs.AAC],
        choices=["Only MP3", "No Bias", "Prefer AAC", "Only AAC"],
        metavar="Audio Format",
        help="How much to prefer AAC over MP3")
    formats.add_argument("--special",
                         choices=["None", "Share", "Video only", "Audio only"],
                         default=defs.SPECIAL_LABEL[(defs.SHARE, defs.V_ONLY,
                                                     defs.A_ONLY)],
                         metavar="Special Formats",
                         help="Use a special format selection")

    # Output
    output = parser.add_argument_group("Output", gooey_options={'columns': 1})
    output.add_argument("--output-list",
                        type=os.path.abspath,
                        widget="FileSaver",
                        default=defs.OUTPUT_LIST,
                        metavar="Output to List",
                        gooey_options={'message': "Save link list"},
                        help="Save all parsed links in a list (no download)")
    output.add_argument("--path",
                        type=os.path.abspath,
                        default=defs.PATH,
                        widget="DirChooser",
                        metavar="Output Directory",
                        help="Where to save downloaded coubs",
                        gooey_options={
                            'message': "Pick output destination",
                            'default_path': defs.PATH,
                        })
    output.add_argument(
        "--merge-ext",
        default=defs.MERGE_EXT,
        metavar="Output Container",
        choices=["mkv", "mp4", "asf", "avi", "flv", "f4v", "mov"],
        help="What extension to use for merged output files "
        "(has no effect if no merge is required)")
    output.add_argument("--name-template",
                        default=defs.NAME_TEMPLATE,
                        metavar="Name Template",
                        help=dedent(f"""\
                            Change the naming convention of output files

                            Special strings:
                              %id%        - coub ID (identifier in the URL)
                              %title%     - coub title
                              %creation%  - creation date/time
                              %community% - coub community
                              %channel%   - channel title
                              %tags%      - all tags (separated by _)

                            Other strings will be interpreted literally
                            This option has no influence on the file extension
                            """))

    # Advanced Options
    parser.set_defaults(
        verbosity=1,
        ffmpeg_path=defs.FFMPEG_PATH,
        coubs_per_page=defs.COUBS_PER_PAGE,  # allowed: 1-25
        tag_sep=defs.TAG_SEP,
        fallback_char=defs.FALLBACK_CHAR,
        write_method=defs.WRITE_METHOD,  # w -> overwrite, a -> append
        chunk_size=defs.CHUNK_SIZE,
    )

    args = parser.parse_args()
    args.input = []
    args.input.extend(
        [coub.mapped_input(u) for u in args.urls.split(",") if u])
    args.input.extend([i for i in args.ids.split(",") if i])
    args.input.extend([coub.LinkList(l) for l in args.lists.split(",") if l])
    args.input.extend([coub.Channel(c) for c in args.channels.split(",") if c])
    args.input.extend([coub.Tag(t) for t in args.tags.split(",") if t])
    args.input.extend([coub.Search(s) for s in args.searches.split(",") if s])
    args.input.extend(
        [coub.Community(c) for c in args.communities.split(",") if c])
    if args.hot:
        args.input.append(coub.HotSection())
    if args.random:
        for _ in range(args.random):
            args.input.append(coub.RandomCategory())

    # Read archive content
    if args.archive and os.path.exists(args.archive):
        with open(args.archive, "r") as f:
            args.archive_content = {l.strip() for l in f}
    else:
        args.archive_content = set()
    # The default naming scheme is the same as using %id%
    # but internally the default value is None
    if args.name_template == "%id%":
        args.name_template = None
    # Defining whitespace or an empty string in the config isn't possible
    # Instead translate appropriate keywords
    if args.tag_sep == "space":
        args.tag_sep = " "
    if args.fallback_char is None:
        args.fallback_char = ""
    elif args.fallback_char == "space":
        args.fallback_char = " "

    return translate_to_cli(args)
示例#46
0
def main():
    parser = GooeyParser(description='Example About Dialoge')
    parser.add_argument('filename', help="name of the file to process")
    args = parser.parse_args()
示例#47
0
文件: GUI.py 项目: Th3Tr1ckst3r/Volt
def main():
    try:
        global parser
        parser = GooeyParser(
            description=
            'A free, secure, and interactive AES256-bit encryption program.')
        modes = parser.add_argument_group(
            "Required Modes(Select One.)",
            gooey_options={'label_color': font_color})
        opt = parser.add_argument_group(
            "Required Options(All must be completed.)",
            gooey_options={'label_color': font_color})
        modes.add_argument('-e',
                           '--Encrypt',
                           widget="CheckBox",
                           action='store_true',
                           help='Encryption mode.',
                           gooey_options={
                               'label_color': font_color,
                               'label_bg_color': bg_color,
                               'help_color': font_color,
                               'help_bg_color': bg_color
                           })
        modes.add_argument('-d',
                           '--Decrypt',
                           widget="CheckBox",
                           action='store_true',
                           help='Decryption mode.',
                           gooey_options={
                               'label_color': font_color,
                               'label_bg_color': bg_color,
                               'help_color': font_color,
                               'help_bg_color': bg_color
                           })
        opt.add_argument('-f',
                         '--File',
                         widget='FileChooser',
                         help='File location.',
                         gooey_options={
                             'label_color': font_color,
                             'label_bg_color': bg_color,
                             'help_color': font_color,
                             'help_bg_color': bg_color
                         })
        opt.add_argument(
            '-p',
            '--Password',
            widget='PasswordField',
            help=
            'Password for the file. It can be anything you want, but CANNOT exceed 32 characters in length.',
            gooey_options={
                'label_color': font_color,
                'label_bg_color': bg_color,
                'help_color': font_color,
                'help_bg_color': bg_color
            })
        opt.add_argument(
            '-iv',
            '--IV',
            widget='PasswordField',
            gooey_options={
                'label_color': font_color,
                'label_bg_color': bg_color,
                'help_color': font_color,
                'help_bg_color': bg_color
            },
            help=
            'IV for the file encryption/decryption. Must be atleast 16 characters long. You may go less than 16, but it will be less secure. The more random, the better.'
        )
        args = parser.parse_args()
        engine(args)
    except KeyboardInterrupt:
        sys.exit(1)
示例#48
0
def get_args() -> Namespace:
    parser = GooeyParser(description='Process VMI counts and '
                         'create quote and OE Upload files')
    parser.add_argument(
        'count_file',
        default=INPUT_COUNT_FILE,
        widget='FileChooser',
        help='Provide a path to a count file to import (Excel or CSV)')
    parser.add_argument(
        'backorder_file',
        default=INPUT_BACKORDER_FILE,
        widget='FileChooser',
        help='Provide a path to a backorder file to import (Excel or CSV)')
    parser.add_argument(
        '--config',
        dest='config_file',
        default=os.path.join(BASE_PATH, CONFIG_FOLDER, CONFIG_FILE),
        widget='FileChooser',
        help='Provide a config file in JSON format; see example')
    parser.add_argument(
        '--product_data',
        dest='product_data_file',
        default=os.path.join(BASE_PATH, DATA_FOLDER, DATA_FILE),
        widget='FileChooser',
        help='Provide a product data file in CSV or Excel format; see example')
    parser.add_argument(
        '--path',
        '-P',
        dest='output_path',
        default=OUTPUT_PATH,
        widget='DirChooser',
        help='Provide a folder path for the ouput files')
    parser.add_argument(
        '--add_prices',
        '-A',
        dest='add_prices',
        action='store_true',
        widget='CheckBox',
        help='Toggle if you want to add prices to upload file')
    parser.add_argument(
        '--quote',
        '-Q',
        dest='quote_name',
        default=OUTPUT_QUOTE_FILE,
        help='Provide a filename prefix for output of Excel quotation file(s)')
    parser.add_argument(
        '--OEUpload',
        '-O',
        dest='OEUpload_name',
        default=OUTPUT_OEUPLOAD_FILE,
        help='Provide a filename for output of Excel OE upload template file')

    return parser.parse_args()
示例#49
0
def main(ini_name=''):
    if not ini_name:
        ini_name = pyw_name
    ini_name = ini_name.lower()

    # Load default value from .ini file.
    config_file = f'./config/{ini_name}.ini'
    config = configparser.ConfigParser(interpolation=None)
    try:
        config.read_file(codecs.open(config_file, "r", "utf8"))
    except FileNotFoundError:
        logger.info('Config file not exists, copy from ./config/template.ini')
        shutil.copy('./config/template.ini', config_file)
        config.read_file(codecs.open(config_file, "r", "utf8"))

    config = update_config_from_template(config, file=config_file)

    event_folder = [
        f for f in os.listdir('./campaign')
        if f.startswith('event_') and f.split('_')[-1] == server.server
    ]
    event_latest = sorted([f for f in event_folder], reverse=True)[0]
    event_folder = [dic_eng_to_true_eng.get(f, f) for f in event_folder][::-1]
    event_latest = dic_eng_to_true_eng.get(event_latest, event_latest)

    saved_config = {}
    for opt, option in config.items():
        for key, value in option.items():
            key = dic_eng_to_true_eng.get(key, key)
            if value in dic_eng_to_true_eng:
                value = dic_eng_to_true_eng.get(value, value)
            if value == 'None':
                value = ''

            saved_config[key] = value

    def default(name):
        """Get default value in .ini file.
        Args:
            name (str): option, in chinese.

        Returns:
            str: Default value, in chinese.
        """
        name = name.strip('-')
        return saved_config.get(name, '')

    def choice_list(total):
        return [str(index) for index in range(1, total + 1)]

    # Don't use checkbox in gooey, use drop box instead.
    # https://github.com/chriskiehl/Gooey/issues/148
    # https://github.com/chriskiehl/Gooey/issues/485

    parser = GooeyParser(
        description=
        f'AzurLaneAutoScript, An Azur Lane automation tool. Config: {config_file}'
    )
    subs = parser.add_subparsers(help='commands', dest='command')

    # ==========setting==========
    setting_parser = subs.add_parser('setting')

    # 选择关卡
    stage = setting_parser.add_argument_group(
        'Level settings', 'Need to run once to save options')
    stage.add_argument('--enable_stop_condition',
                       default=default('--enable_stop_condition'),
                       choices=['yes', 'no'])
    stage.add_argument('--enable_fast_forward',
                       default=default('--enable_fast_forward'),
                       choices=['yes', 'no'],
                       help='Enable or disable clearing mode')

    stop = stage.add_argument_group(
        'Stop condition',
        'After triggering, it will not stop immediately. It will complete the current attack first, and fill in 0 if it is not needed.'
    )
    stop.add_argument(
        '--if_count_greater_than',
        default=default('--if_count_greater_than'),
        help=
        'The previous setting will be used, and the number\n of deductions will be deducted after completion of the attack until it is cleared.'
    )
    stop.add_argument(
        '--if_time_reach',
        default=default('--if_time_reach'),
        help=
        'Use the time within the next 24 hours, the previous setting will be used, and it will be cleared\n after the trigger. It is recommended to advance about\n 10 minutes to complete the current attack. Format 14:59'
    )
    stop.add_argument('--if_oil_lower_than',
                      default=default('--if_oil_lower_than'))
    stop.add_argument(
        '--if_trigger_emotion_control',
        default=default('--if_trigger_emotion_control'),
        choices=['yes', 'no'],
        help=
        'If yes, wait for reply, complete this time, stop \nIf no, wait for reply, complete this time, continue'
    )
    stop.add_argument('--if_dock_full',
                      default=default('--if_dock_full'),
                      choices=['yes', 'no'])

    # 出击舰队
    fleet = setting_parser.add_argument_group(
        'Attack fleet',
        'No support for alternate lane squadrons, inactive map or weekly mode will ignore the step setting'
    )
    fleet.add_argument('--enable_fleet_control',
                       default=default('--enable_fleet_control'),
                       choices=['yes', 'no'])
    fleet.add_argument('--enable_map_fleet_lock',
                       default=default('--enable_map_fleet_lock'),
                       choices=['yes', 'no'])

    f1 = fleet.add_argument_group(
        'Mob Fleet',
        'Players can choose a formation before battle. Though it has no effect appearance-wise, the formations applies buffs to certain stats.\nLine Ahead: Increases Firepower and Torpedo by 15%, but reduces Evasion by 10% (Applies only to Vanguard fleet)\nDouble Line: Increases Evasion by 30%, but decreases Firepower and Torpedo by 5% (Applies only to Vanguard fleet)\nDiamond: Increases Anti-Air by 20% (no penalties, applies to entire fleet)'
    )
    f1.add_argument('--fleet_index_1',
                    default=default('--fleet_index_1'),
                    choices=['1', '2', '3', '4', '5', '6'])
    f1.add_argument('--fleet_formation_1',
                    default=default('--fleet_formation_1'),
                    choices=['Line Ahead', 'Double Line', 'Diamond'])
    f1.add_argument(
        '--fleet_step_1',
        default=default('--fleet_step_1'),
        choices=['1', '2', '3', '4', '5', '6'],
        help=
        'In event map, fleet has limit on moving, so fleet_step is how far can a fleet goes in one operation, if map cleared, it will be ignored'
    )

    f2 = fleet.add_argument_group('Boss Fleet')
    f2.add_argument('--fleet_index_2',
                    default=default('--fleet_index_2'),
                    choices=['do_not_use', '1', '2', '3', '4', '5', '6'])
    f2.add_argument('--fleet_formation_2',
                    default=default('--fleet_formation_2'),
                    choices=['Line Ahead', 'Double Line', 'Diamond'])
    f2.add_argument(
        '--fleet_step_2',
        default=default('--fleet_step_2'),
        choices=['1', '2', '3', '4', '5', '6'],
        help=
        'In event map, fleet has limit on moving, so fleet_step is how far can a fleet goes in one operation, if map cleared, it will be ignored'
    )

    f3 = fleet.add_argument_group('Alternate Mob Fleet')
    f3.add_argument('--fleet_index_3',
                    default=default('--fleet_index_3'),
                    choices=['do_not_use', '1', '2', '3', '4', '5', '6'])
    f3.add_argument('--fleet_formation_3',
                    default=default('--fleet_formation_3'),
                    choices=['Line Ahead', 'Double Line', 'Diamond'])
    f3.add_argument(
        '--fleet_step_3',
        default=default('--fleet_step_3'),
        choices=['1', '2', '3', '4', '5', '6'],
        help=
        'In event map, fleet has limit on moving, so fleet_step is how far can a fleet goes in one operation, if map cleared, it will be ignored'
    )

    f4 = fleet.add_argument_group('Auto-mode')
    f4.add_argument(
        '--combat_auto_mode',
        default=default('--combat_auto_mode'),
        choices=['combat_auto', 'combat_manual', 'stand_still_in_the_middle'])

    # 潜艇设置
    submarine = setting_parser.add_argument_group(
        'Submarine settings',
        'Only supported: hunt_only, do_not_use and every_combat')
    submarine.add_argument('--fleet_index_4',
                           default=default('--fleet_index_4'),
                           choices=['do_not_use', '1', '2'])
    submarine.add_argument('--submarine_mode',
                           default=default('--submarine_mode'),
                           choices=[
                               'do_not_use', 'hunt_only', 'every_combat',
                               'when_no_ammo', 'when_boss_combat',
                               'when_boss_combat_boss_appear'
                           ])

    # 心情控制
    emotion = setting_parser.add_argument_group('Mood control')
    emotion.add_argument('--enable_emotion_reduce',
                         default=default('--enable_emotion_reduce'),
                         choices=['yes', 'no'])
    emotion.add_argument('--ignore_low_emotion_warn',
                         default=default('--ignore_low_emotion_warn'),
                         choices=['yes', 'no'])

    e1 = emotion.add_argument_group('Mob Fleet')
    e1.add_argument(
        '--emotion_recover_1',
        default=default('--emotion_recover_1'),
        choices=['not_in_dormitory', 'dormitory_floor_1', 'dormitory_floor_2'])
    e1.add_argument('--emotion_control_1',
                    default=default('--emotion_control_1'),
                    choices=[
                        'keep_high_emotion', 'avoid_green_face',
                        'avoid_yellow_face', 'avoid_red_face'
                    ])
    e1.add_argument('--hole_fleet_married_1',
                    default=default('--hole_fleet_married_1'),
                    choices=['yes', 'no'])

    e2 = emotion.add_argument_group('BOSS Fleet')
    e2.add_argument(
        '--emotion_recover_2',
        default=default('--emotion_recover_2'),
        choices=['not_in_dormitory', 'dormitory_floor_1', 'dormitory_floor_2'])
    e2.add_argument('--emotion_control_2',
                    default=default('--emotion_control_2'),
                    choices=[
                        'keep_high_emotion', 'avoid_green_face',
                        'avoid_yellow_face', 'avoid_red_face'
                    ])
    e2.add_argument('--hole_fleet_married_2',
                    default=default('--hole_fleet_married_2'),
                    choices=['yes', 'no'])

    e3 = emotion.add_argument_group(
        'Alternate Mob Fleet',
        'Will be used when the first team triggers mood control')
    e3.add_argument(
        '--emotion_recover_3',
        default=default('--emotion_recover_3'),
        choices=['not_in_dormitory', 'dormitory_floor_1', 'dormitory_floor_2'])
    e3.add_argument('--emotion_control_3',
                    default=default('--emotion_control_3'),
                    choices=[
                        'keep_high_emotion', 'avoid_green_face',
                        'avoid_yellow_face', 'avoid_red_face'
                    ])
    e3.add_argument('--hole_fleet_married_3',
                    default=default('--hole_fleet_married_3'),
                    choices=['yes', 'no'])

    # 血量平衡
    hp = setting_parser.add_argument_group(
        'HP control', 'Fleet lock must be turned off to take effect')
    hp.add_argument('--enable_hp_balance',
                    default=default('--enable_hp_balance'),
                    choices=['yes', 'no'])
    hp.add_argument('--enable_low_hp_withdraw',
                    default=default('--enable_low_hp_withdraw'),
                    choices=['yes', 'no'])
    hp_balance = hp.add_argument_group('HP Balance', '')
    hp_balance.add_argument(
        '--scout_hp_difference_threshold',
        default=default('--scout_hp_difference_threshold'),
        help=
        'When the difference in HP volume is greater than the threshold, transpose'
    )
    hp_balance.add_argument(
        '--scout_hp_weights',
        default=default('--scout_hp_weights'),
        help=
        'Should be repaired when there is a difference in Vanguard, format 1000,1000,1000'
    )
    hp_add = hp.add_argument_group('Emergency repair', '')
    hp_add.add_argument(
        '--emergency_repair_single_threshold',
        default=default('--emergency_repair_single_threshold'),
        help='Used when single shipgirl is below the threshold')
    hp_add.add_argument(
        '--emergency_repair_hole_threshold',
        default=default('--emergency_repair_hole_threshold'),
        help='Used when all front rows or all back rows are below the threshold'
    )
    hp_withdraw = hp.add_argument_group('Low HP volume withdrawal', '')
    hp_withdraw.add_argument('--low_hp_withdraw_threshold',
                             default=default('--low_hp_withdraw_threshold'),
                             help='When HP is below the threshold, retreat')

    # 退役选项
    retire = setting_parser.add_argument_group('Retirement settings', '')
    retire.add_argument('--enable_retirement',
                        default=default('--enable_retirement'),
                        choices=['yes', 'no'])
    retire.add_argument('--retire_method',
                        default=default('--retire_method'),
                        choices=['enhance', 'one_click_retire', 'old_retire'])
    retire.add_argument('--retire_amount',
                        default=default('--retire_amount'),
                        choices=['retire_all', 'retire_10'])
    retire.add_argument('--enhance_favourite',
                        default=default('--enhance_favourite'),
                        choices=['yes', 'no'])

    rarity = retire.add_argument_group(
        'Retirement rarity',
        'The ship type selection is not supported yet. Ignore the following options when using one-key retirement'
    )
    rarity.add_argument('--retire_n',
                        default=default('--retire_n'),
                        choices=['yes', 'no'],
                        help='N')
    rarity.add_argument('--retire_r',
                        default=default('--retire_r'),
                        choices=['yes', 'no'],
                        help='R')
    rarity.add_argument('--retire_sr',
                        default=default('--retire_sr'),
                        choices=['yes', 'no'],
                        help='SR')
    rarity.add_argument('--retire_ssr',
                        default=default('--retire_ssr'),
                        choices=['yes', 'no'],
                        help='SSR')

    # 掉落记录
    drop = setting_parser.add_argument_group(
        'Drop record',
        'Save screenshots of dropped items, which will slow down the click speed when settlement is enabled'
    )
    drop.add_argument('--enable_drop_screenshot',
                      default=default('--enable_drop_screenshot'),
                      choices=['yes', 'no'])
    drop.add_argument('--drop_screenshot_folder',
                      default=default('--drop_screenshot_folder'))

    clear = setting_parser.add_argument_group(
        'Wasteland mode',
        'Unopened maps will stop after completion. Opened maps will ignore options, and its done if you do not open up'
    )
    clear.add_argument('--enable_map_clear_mode',
                       default=default('--enable_map_clear_mode'),
                       choices=['yes', 'no'])
    clear.add_argument('--clear_mode_stop_condition',
                       default=default('--clear_mode_stop_condition'),
                       choices=['map_100', 'map_3_star', 'map_green'])
    clear.add_argument(
        '--map_star_clear_all',
        default=default('--map_star_clear_all'),
        choices=['index_1', 'index_2', 'index_3', 'do_not_use'],
        help='The first few stars are to destroy all enemy ships')

    # ==========reward==========
    reward_parser = subs.add_parser('reward')
    reward_condition = reward_parser.add_argument_group(
        'Triggering conditions',
        'Need to run once to save the options, after running it will enter the on-hook vegetable collection mode'
    )
    reward_condition.add_argument('--enable_reward',
                                  default=default('--enable_reward'),
                                  choices=['yes', 'no'])
    reward_condition.add_argument(
        '--reward_interval',
        default=default('--reward_interval'),
        choices=['20', '30', '60'],
        help='How many minutes to trigger collection')

    reward_oil = reward_parser.add_argument_group('Oil supplies', '')
    reward_oil.add_argument('--enable_oil_reward',
                            default=default('--enable_oil_reward'),
                            choices=['yes', 'no'])
    reward_oil.add_argument('--enable_coin_reward',
                            default=default('--enable_coin_reward'),
                            choices=['yes', 'no'])

    reward_mission = reward_parser.add_argument_group('mission rewards', '')
    reward_mission.add_argument('--enable_mission_reward',
                                default=default('--enable_mission_reward'),
                                choices=['yes', 'no'])

    reward_commission = reward_parser.add_argument_group(
        'Commission settings', '')
    reward_commission.add_argument(
        '--enable_commission_reward',
        default=default('--enable_commission_reward'),
        choices=['yes', 'no'])
    reward_commission.add_argument(
        '--commission_time_limit',
        default=default('--commission_time_limit'),
        help=
        'Ignore orders whose completion time exceeds the limit, Format: 23:30. Fill in 0 if it is not needed'
    )

    priority1 = reward_commission.add_argument_group(
        'Commission priority by time duration', '')
    priority1.add_argument('--duration_shorter_than_2',
                           default=default('--duration_shorter_than_2'),
                           help='')
    priority1.add_argument('--duration_longer_than_6',
                           default=default('--duration_longer_than_6'),
                           help='')
    priority1.add_argument('--expire_shorter_than_2',
                           default=default('--expire_shorter_than_2'),
                           help='')
    priority1.add_argument('--expire_longer_than_6',
                           default=default('--expire_longer_than_6'),
                           help='')

    priority2 = reward_commission.add_argument_group(
        'Daily Commission priority', '')
    priority2.add_argument(
        '--daily_comm',
        default=default('--daily_comm'),
        help=
        'Daily resource development, high-level tactical research and development'
    )
    priority2.add_argument('--major_comm',
                           default=default('--major_comm'),
                           help='1200 oil / 1000 oil commission')

    priority3 = reward_commission.add_argument_group(
        'Additional commission priority', '')
    priority3.add_argument(
        '--extra_drill',
        default=default('--extra_drill'),
        help='Short-range Sailing Training, Coastal Defense Patrol')
    priority3.add_argument(
        '--extra_part',
        default=default('--extra_part'),
        help='Small Merchant Escort, Forest Protection Commission')
    priority3.add_argument(
        '--extra_cube',
        default=default('--extra_cube'),
        help='Fleet Exercise Ⅲ, Fleet Escort ExerciseFleet Exercise Ⅲ')
    priority3.add_argument(
        '--extra_oil',
        default=default('--extra_oil'),
        help='Small-scale Oil Extraction, Large-scale Oil Extraction')
    priority3.add_argument('--extra_book',
                           default=default('--extra_book'),
                           help='Small Merchant Escort, Large Merchant Escort')

    priority4 = reward_commission.add_argument_group(
        'Urgent commission priority', '')
    priority4.add_argument(
        '--urgent_drill',
        default=default('--urgent_drill'),
        help='Defend the transport troops, annihilate the enemy elite troops')
    priority4.add_argument(
        '--urgent_part',
        default=default('--urgent_part'),
        help='Support Vila Vela Island, support terror Banner')
    priority4.add_argument('--urgent_cube',
                           default=default('--urgent_cube'),
                           help='Rescue merchant ship, enemy attack')
    priority4.add_argument('--urgent_book',
                           default=default('--urgent_book'),
                           help='Support Tuhaoer Island, support Moe Island')
    priority4.add_argument('--urgent_box',
                           default=default('--urgent_box'),
                           help='BIW Gear Transport, NYB Gear Transport')
    priority4.add_argument('--urgent_gem',
                           default=default('--urgent_gem'),
                           help='BIW VIP Escort, NYB VIP Escort')
    priority4.add_argument(
        '--urgent_ship',
        default=default('--urgent_ship'),
        help=
        'Small Launch Ceremony, Fleet Launch Ceremony, Alliance Launch Ceremony'
    )

    reward_tactical = reward_parser.add_argument_group(
        'Classroom',
        'Only support continuation of skill books, not new skills')
    reward_tactical.add_argument('--enable_tactical_reward',
                                 default=default('--enable_tactical_reward'),
                                 choices=['yes', 'no'])
    reward_tactical.add_argument('--tactical_night_range',
                                 default=default('--tactical_night_range'),
                                 help='Format 23:30-06:30')
    reward_tactical.add_argument(
        '--tactical_book_tier',
        default=default('--tactical_book_tier'),
        choices=['3', '2', '1'],
        help=
        'Wich skill book will use first\nT3 is a gold book, T2 is a purple book, T1 is a blue book'
    )
    reward_tactical.add_argument(
        '--tactical_exp_first',
        default=default('--tactical_exp_first'),
        choices=['yes', 'no'],
        help=
        'Choose Yes, give priority to the 150% bonus \nSelect No, give priority to the skills book with the same rarity'
    )
    reward_tactical.add_argument('--tactical_book_tier_night',
                                 default=default('--tactical_book_tier_night'),
                                 choices=['3', '2', '1'])
    reward_tactical.add_argument('--tactical_exp_first_night',
                                 default=default('--tactical_exp_first_night'),
                                 choices=['yes', 'no'])

    # ==========emulator==========
    emulator_parser = subs.add_parser('emulator')
    emulator = emulator_parser.add_argument_group(
        'Emulator',
        'Need to run once to save the options, it will check whether the game is started \nIf the game has not started, it will be started'
    )
    emulator.add_argument(
        '--serial',
        default=default('--serial'),
        help='Bluestacks 127.0.0.1:5555 \nNox 127.0.0.1:62001')
    emulator.add_argument('--package_name',
                          default='com.YoStarEN.AzurLane',
                          help='')

    debug = emulator_parser.add_argument_group('Debug settings', '')
    debug.add_argument(
        '--enable_error_log_and_screenshot_save',
        default=default('--enable_error_log_and_screenshot_save'),
        choices=['yes', 'no'])
    debug.add_argument(
        '--enable_perspective_error_image_save',
        default=default('--enable_perspective_error_image_save'),
        choices=['yes', 'no'])

    adb = emulator_parser.add_argument_group('ADB settings', '')
    adb.add_argument('--use_adb_screenshot',
                     default=default('--use_adb_screenshot'),
                     choices=['yes', 'no'],
                     help='It is recommended to enable it to reduce CPU usage')
    adb.add_argument('--use_adb_control',
                     default=default('--use_adb_control'),
                     choices=['yes', 'no'],
                     help='Recommended off, can speed up the click speed')
    adb.add_argument(
        '--combat_screenshot_interval',
        default=default('--combat_screenshot_interval'),
        help='Slow down the screenshot speed during battle and reduce CPU')

    # ==========每日任务==========
    daily_parser = subs.add_parser('daily')

    # 选择每日
    daily = daily_parser.add_argument_group(
        'Choose daily', 'Daily tasks, exercises, difficulty charts')
    daily.add_argument('--enable_daily_mission',
                       default=default('--enable_daily_mission'),
                       help='If there are records on the day, skip',
                       choices=['yes', 'no'])
    daily.add_argument('--enable_hard_campaign',
                       default=default('--enable_hard_campaign'),
                       help='If there are records on the day, skip',
                       choices=['yes', 'no'])
    daily.add_argument('--enable_exercise',
                       default=default('--enable_exercise'),
                       help='If there is a record after refreshing, skip',
                       choices=['yes', 'no'])

    # 每日设置
    daily_task = daily_parser.add_argument_group(
        'Daily settings', 'Does not support submarine daily')
    daily_task.add_argument(
        '--tactical_training',
        default=default('--tactical_training'),
        choices=['daily_air', 'daily_gun', 'daily_torpedo'])
    daily_task.add_argument('--fierce_assault',
                            default=default('--fierce_assault'),
                            choices=['index_1', 'index_2', 'index_3'])
    daily_task.add_argument('--escort_mission',
                            default=default('--escort_mission'),
                            choices=['index_1', 'index_2', 'index_3'])
    daily_task.add_argument('--advance_mission',
                            default=default('--advance_mission'),
                            choices=['index_1', 'index_2', 'index_3'])
    daily_task.add_argument('--daily_fleet',
                            default=default('--daily_fleet'),
                            choices=['1', '2', '3', '4', '5', '6'])
    daily_task.add_argument(
        '--daily_equipment',
        default=default('--daily_equipment'),
        help=
        'Change equipment before playing, unload equipment after playing, do not need to fill in 0 \ncomma, such as 3, 1, 0, 1, 1, 0'
    )

    # 困难设置
    hard = daily_parser.add_argument_group(
        'Difficult setting',
        'Need to turn on weekly mode, only support 10-1, 10-2 and 10-4 temporarily'
    )
    hard.add_argument('--hard_campaign',
                      default=default('--hard_campaign'),
                      help='For example 10-4')
    hard.add_argument('--hard_fleet',
                      default=default('--hard_fleet'),
                      choices=['1', '2'])
    hard.add_argument(
        '--hard_equipment',
        default=default('--hard_equipment'),
        help=
        'Change equipment before playing, unload equipment after playing, do not need to fill in 0 \ncomma, such as 3, 1, 0, 1, 1, 0'
    )

    # 演习设置
    exercise = daily_parser.add_argument_group(
        'Exercise settings',
        'Only support the most experience for the time being')
    exercise.add_argument(
        '--exercise_choose_mode',
        default=default('--exercise_choose_mode'),
        choices=['max_exp', 'max_ranking', 'good_opponent'],
        help='Only support the most experience for the time being')
    exercise.add_argument('--exercise_preserve',
                          default=default('--exercise_preserve'),
                          help='Only 0 are temporarily reserved')
    exercise.add_argument('--exercise_try',
                          default=default('--exercise_try'),
                          help='The number of attempts by each opponent')
    exercise.add_argument('--exercise_hp_threshold',
                          default=default('--exercise_hp_threshold'),
                          help='HHP <Retreat at Threshold')
    exercise.add_argument(
        '--exercise_low_hp_confirm',
        default=default('--exercise_low_hp_confirm'),
        help=
        'After HP is below the threshold, it will retreat after a certain period of time \nRecommended 1.0 ~ 3.0'
    )
    exercise.add_argument(
        '--exercise_equipment',
        default=default('--exercise_equipment'),
        help=
        'Change equipment before playing, unload equipment after playing, do not need to fill in 0 \ncomma, such as 3, 1, 0, 1, 1, 0'
    )

    # ==========event_daily_ab==========
    event_ab_parser = subs.add_parser('event_daily_bonus')
    event_name = event_ab_parser.add_argument_group(
        'Choose an event', 'bonus for first clear each day')
    event_name.add_argument('--event_name_ab',
                            default=event_latest,
                            choices=event_folder,
                            help='There a dropdown menu with many options')
    # event_name.add_argument('--enable_hard_bonus', default=default('--enable_hard_bonus'), choices=['yes', 'no'], help='Will enable Daily bonus for Event hard maps') # Trying implement all event maps

    # ==========main==========
    main_parser = subs.add_parser('main')
    # 选择关卡
    stage = main_parser.add_argument_group(
        'Choose a level',
        'Main campaign, currently only supports the first six chapters and 7-2'
    )
    stage.add_argument('--main_stage',
                       default=default('--main_stage'),
                       help='E.g 7-2')

    # ==========event==========
    event_parser = subs.add_parser('event')

    description = """
    Support "Iris of Light and Dark Rerun" (event_20200521_en), optimized for D2
    """
    event = event_parser.add_argument_group(
        'Choose a level',
        '\n'.join([line.strip() for line in description.strip().split('\n')]))
    event.add_argument('--event_stage',
                       default=default('--event_stage'),
                       choices=[
                           'a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2',
                           'c3', 'd1', 'd2', 'd3'
                       ],
                       help='E.g d3')
    event.add_argument('--sp_stage',
                       default=default('--sp_stage'),
                       choices=['sp1', 'sp2', 'sp3'],
                       help='E.g sp3')
    event.add_argument('--event_name',
                       default=event_latest,
                       choices=event_folder,
                       help='There a dropdown menu with many options')

    # ==========半自动==========
    semi_parser = subs.add_parser('semi_auto')
    semi = semi_parser.add_argument_group(
        'Semi-automatic mode',
        'Manual selection of enemies, automatic settlement, used to attack unsuited pictures'
    )
    semi.add_argument('--enable_semi_map_preparation',
                      default=default('--enable_semi_map_preparation'),
                      help='',
                      choices=['yes', 'no'])
    semi.add_argument(
        '--enable_semi_story_skip',
        default=default('--enable_semi_story_skip'),
        help=
        'Note that this will automatically confirm all the prompt boxes, including the red face attack',
        choices=['yes', 'no'])

    # ==========c72_mystery_farming==========
    c_7_2_parser = subs.add_parser('c7-2_mystery_farming')
    c_7_2 = c_7_2_parser.add_argument_group('c72_mystery_farming', '')
    c_7_2.add_argument('--boss_fleet_step_on_a3',
                       default=default('--boss_fleet_step_on_a3'),
                       choices=['yes', 'no'],
                       help='A3 has enemies, G3, C3, E3')

    # ==========c122_leveling==========
    c_12_2_parser = subs.add_parser('c12-2_leveling')
    c_12_2 = c_12_2_parser.add_argument_group('12-2 enemy search settings', '')
    c_12_2.add_argument(
        '--s3_enemy_tolerance',
        default=default('--s3_enemy_tolerance'),
        choices=['0', '1', '2', '10'],
        help='The maximum number of battles to fight against large enemies')

    # ==========c124_leveling==========
    c_12_4_parser = subs.add_parser('c12-4_leveling')
    c_12_4 = c_12_4_parser.add_argument_group(
        '12-4 Search enemy settings',
        'Need to ensure that the team has a certain strength')
    c_12_4.add_argument('--non_s3_enemy_enter_tolerance',
                        default=default('--non_s3_enemy_enter_tolerance'),
                        choices=['0', '1', '2'],
                        help='Avoid enemy too strong')
    c_12_4.add_argument(
        '--non_s3_enemy_withdraw_tolerance',
        default=default('--non_s3_enemy_withdraw_tolerance'),
        choices=['0', '1', '2', '10'],
        help='How many battles will be fought after there is no large scale')
    c_12_4.add_argument('--ammo_pick_up_124',
                        default=default('--ammo_pick_up_124'),
                        choices=['2', '3', '4', '5'],
                        help='How much ammunition to pick after the battle')

    args = parser.parse_args()

    # Convert option from chinese to english.
    out = {}
    for key, value in vars(args).items():
        key = dic_true_eng_to_eng.get(key, key)
        value = dic_true_eng_to_eng.get(value, value)
        out[key] = value
    args = out

    # Update option to .ini file.
    command = args['command'].capitalize()
    config['Command']['command'] = command
    for key, value in args.items():
        config[command][key] = str(value)
    config.write(codecs.open(config_file, "w+", "utf8"))

    # Call AzurLaneAutoScript
    alas = AzurLaneAutoScript(ini_name=ini_name)
    alas.run(command=command)
def initOptParser():
	parser = GooeyParser(description="Copy files to specified location")

	# Option for the path of files to move (can be a full directory).

	parser.add_argument('--files', metavar='file', nargs='*', 
                 		 help='file(s) you wish to copy', widget="MultiFileChooser")

	parser.add_argument('--directories', metavar='dir', nargs='*', help="The directorie(s) you wish to copy.", widget="MultiDirChooser")
	# Option to specify which project said files go to.
	

	parser.add_argument('-p', '--path', metavar='path',dest='path',  type=str, 
						help='Path which will be considered as root of all projects. Default is currently : ' + utils.defaultFolderPath, 
						default=utils.defaultFolderPath, widget="DirChooser")

	parser.add_argument('projectName', metavar='projectName', type=str, 
						help='The project you wish to retrieve/add files to/from.')
	# Option to specify the version name of the commit.

	parser.add_argument('-v', '--version', metavar='versionName', type=str,
						help='The name of the directory which will be created during an update. By default, this will be : VERSION_X.')
	# Option allowing overwrite of current version.



	parser.add_argument('-m', '--message', metavar='logMessage', type=str, help='Use to specify a log message which will be put in a versFile at the root of the project directory.')
	# Specify --get to retrieve files instead of commiting them.

	parser.add_argument('-g', '--get', dest='method', action='store_const', help='Retrieve files from project (last version by default)', const=get.get, default=push.push)
	# Allows 'locking'. Not really a lock. Basically a warning message to all users who try to check out if a user checked out without commiting his files.
	
	parser.add_argument('-l', '--lock', action="store_true",
						help='Locks the current project. '+ 
							'Unlocked when next push from the locking user is made')
	# User name. Just to allow 'locking'/'unlocking'
	
	parser.add_argument('user', metavar='userName', type=str, help='Specify your name.')


	parser.add_argument('-a', '--archive', metavar='archivePath', type=str, help='Use to specify a directory which will be used as an archive. Current default is : ' + utils.archivePath, widget="DirChooser")
	# Will pop up a windows fileselector to choose which files will be copied.
	parser.add_argument('-s', '--store', metavar="destPath", help='Use to specify where you want the files retrieved from the project to be copied.', widget="DirChooser")
	# Function to call to get all arguments.
	
	args = parser.parse_args()
	#print(args.files)
	#print(args.directories)
	if (args.files == None and args.directories == None):
		return (None)
	if (args.files and args.directories):
		args.files = args.files + args.directories#args.files[0].split(";")  + args.directories[0].split(";")
	elif (args.directories):
		args.files = args.directories
	print("The following files/directories will be copied (along with all sub-directories) :")
	for myFile in args.files:
		print("- [" + myFile + "]")
	return (args)
示例#51
0
def main():
    desc = "Example application to show Gooey's various widgets"
    file_help_msg = "Name of the file you want to process"
    my_cool_parser = GooeyParser(description=desc)
    my_cool_parser.add_argument("filename",
                                help=file_help_msg,
                                widget="FileChooser")  # positional
    my_cool_parser.add_argument("directory",
                                help="Directory to store output")  # positional

    my_cool_parser.add_argument(
        '-c',
        '--countdown',
        default=2,
        type=int,
        help='sets the time to count down from you see its quite simple!')
    my_cool_parser.add_argument(
        '-j',
        '--cron-schedule',
        type=int,
        help='Set the datetime when the cron should begin',
        widget='DateChooser')
    my_cool_parser.add_argument("-s",
                                "--showtime",
                                action="store_true",
                                help="display the countdown timer")
    my_cool_parser.add_argument("-d",
                                "--delay",
                                action="store_true",
                                help="Delay execution for a bit")
    my_cool_parser.add_argument('-v', '--verbose', action='count')
    my_cool_parser.add_argument("-o",
                                "--obfuscate",
                                action="store_true",
                                help="obfuscate the countdown timer!")
    my_cool_parser.add_argument('-r',
                                '--recursive',
                                choices=['yes', 'no'],
                                help='Recurse into subfolders')
    my_cool_parser.add_argument("-w",
                                "--writelog",
                                default="No, NOT whatevs",
                                help="write log to some file or something")
    my_cool_parser.add_argument("-e",
                                "--expandAll",
                                action="store_true",
                                help="expand all processes")
    verbosity = my_cool_parser.add_mutually_exclusive_group()
    verbosity.add_argument('-t',
                           '--verbozze',
                           dest='verbose',
                           action="store_true",
                           help="Show more details")
    verbosity.add_argument('-q',
                           '--quiet',
                           dest='quiet',
                           action="store_true",
                           help="Only output on error")
    print my_cool_parser._actions
    print 'inside of main(), my_cool_parser =', my_cool_parser

    args = my_cool_parser.parse_args()
    print sys.argv
    print args.countdown
    print args.showtime

    start_time = _time()
    print 'Counting down from %s' % args.countdown
    while _time() - start_time < args.countdown:
        if args.showtime:
            print 'printing message at: %s' % _time()
        else:
            print 'printing message at: %s' % hashlib.md5(str(
                _time())).hexdigest()
        _sleep(.5)
    print 'Finished running the program. Byeeeeesss!'
示例#52
0
def parse_args_gui():
    parser = GooeyParser(
        description='neural style transfer between style and content images')

    parser.add_argument('style_path',
                        type=str,
                        widget='FileChooser',
                        help='path to the style image')

    parser.add_argument('content_path',
                        type=str,
                        widget='FileChooser',
                        help='path to the content image')

    parser.add_argument('output_dir',
                        type=str,
                        widget='DirChooser',
                        help='directory in where output should be saved')

    parser.add_argument('output_name', type=str, help='output filename')

    args = parser.parse_args()
    return args
def main():
    #wdata = pd.read_csv("treated_w.csv", sep = ',')
    #weightplot_hero(wdata)
    #tdata = pd.read_csv("JJmice.csv", sep = ',')
    #untreated_hero(tdata)
    #So first we will handle the arguments that are "required"
    #Here we give our GUI a title
    parser = GooeyParser(description="Dashboard for Mice Analysis")
    #Here we allow for the selection of the data files to analyze
    #Because there is no - infront of file_chooser it is required!
    parser.add_argument("file_chooser",
                        help='Choose the csv file to analyze.',
                        widget='FileChooser')
    parser.add_argument("-Graph_title",
                        help="Choose the label for the Figure.")
    parser.add_argument("-y_axis_title",
                        help="Choose the label for the y-axis.")
    parser.add_argument("-x_axis_title",
                        help="Choose the label for the x-axis.")
    parser.add_argument('-mouse_type',
                        metavar='Choose Data Type to Analyze',
                        help='Select the type of mouse being analyzed',
                        dest='m_type',
                        widget='Dropdown',
                        choices=['JJ Mice', 'Treated Mice'],
                        gooey_options={
                            'validator': {
                                'test': 'user_input != "Select Option"',
                                'message': 'Choose a save file from the list'
                            }
                        })
    #Now we parse all these arguments
    args = parser.parse_args()
    raw_data = args.file_chooser
    yaxis = args.y_axis_title
    fig_title = args.Graph_title
    xaxis = args.x_axis_title
    analysis_type = args.m_type
    #if no CSV file is found and we want to visualize, fail gracefully and request the CSV file be provided
    if (len(raw_data) == 0):
        print("Please ensure that you select files to analyze")
        return (None)
    #if the user would like to provide y-axis and figure title, use it, otherwise use the default
    else:
        wdata = pd.read_csv(raw_data, sep=',')
        if (yaxis is not None):
            if (fig_title is not None):
                if (xaxis is not None):
                    if (analysis_type == 'JJ Mice'):
                        untreated_hero(wdata, fig_title, yaxis, xaxis)
                    else:
                        weightplot_hero(wdata, fig_title, yaxis, xaxis)
        elif (fig_title is not None):
            if (xaxis is not None):
                if (analysis_type == 'JJ Mice'):
                    untreated_hero(wdata, fig_title=fig_title, xaxis=xaxis)
                else:
                    weightplot_hero(wdata, fig_title=fig_title, xaxis=xaxis)
            else:
                if (analysis_type == 'JJ Mice'):
                    untreated_hero(wdata, fig_title=fig_title)
                else:
                    weightplot_hero(wdata, fig_title=fig_title)
        elif (xaxis is not None):
            if (analysis_type == 'JJ Mice'):
                untreated_hero(wdata, xaxis=xaxis)
            else:
                weightplot_hero(wdata, xaxis=xaxis)
        else:
            if (analysis_type == 'JJ Mice'):
                untreated_hero(wdata)
            else:
                weightplot_hero(wdata)
示例#54
0
def main():
    p = GooeyParser(
        description='Post-Process RASDRviewer/RASDRproc spectrum data output files')
    p.add_argument(      "--version", action='version', version='%(prog)s '+DEF_VERSION)
    # NB: need to order these with the most used options first
    # http://stackoverflow.com/questions/20165843/argparse-how-to-handle-variable-number-of-arguments-nargs
    p.add_argument(      "file", widget="FileChooser")
    p.add_argument('-b', '--background', type=str, metavar='PATH', default='', widget="FileChooser",
        help='Specify how to perform background subtraction;'+
             'if the word automatic is used, then the background will be taken'+
             'from the average of all lines in the file.  Otherwise, it is taken'+
             'as a file to process.  The file must have the same frequency plan as the foreground file.')
    p.add_argument('-a', '--average', type=int, metavar='N', default=DEF_AVERAGE,
        help='Specify the number of spectra to average for each plot')
    p.add_argument('-s', '--smooth', type=int, metavar='N', default=0,
        help='Smooth final plot using a sliding window of N points')
    p.add_argument('--fcenter', dest='fc', type=float, default=0.0,
        help='Define the offset for the center frequency in Hz')  #default=%f'%0.0)
    p.add_argument('--statistics', type=str, metavar='PATH', default=None, widget="FileChooser",
        help='Dump statistical information to a file in comma-separated-values format')
    p.add_argument('-i', '--info', action='store_true', default=False,
        help='Produce information about a file only; do not generate any plots')
    p.add_argument('-g', '--gui', action='store_true', default=False,
        help='Create interactive PLOTS')
    g = p.add_mutually_exclusive_group()
    g.add_argument("-v", "--verbose", default=False, help="Turn on verbose output", action="store_true")
    g.add_argument("-q", "--quiet", default=False, help='Suppress progress messages', action="store_true")
    # call matplotlib.use() only once
    p.set_defaults(matplotlib_use = False)
    p.add_argument('-c', '--cancel-dc', dest='canceldc', action='store_true', default=False,
        help='Cancel out component at frequency bin for 0Hz')
    p.add_argument('-d', '--delimiter', type=str, metavar='CHAR', default=DEF_DELIM,
        help='Specify the delimiter character to use"')
    p.add_argument('-e', '--localtime', action='store_true', default=False,
        help='Indicate that .csv file has timestamps in RASDRviewer\'s "LocalTime" format')
    p.add_argument('-k', '--calibration', type=float, metavar='CONST', default=DEF_CALIB,
        help='Specify the calibration constant for the system; 0.0=uncal')    #default=%f'%DEF_CALIB)
    p.add_argument('-l', '--line', action='store_true', default=False,
        help='Perform line-by-line processing instead of loading entire file(s); NOTE: much slower but tolerates low memory better.')
##    p.add_argument('-m', '--milliwatt', dest='dbm', action='store_true', default=False,
##        help='Plot in decibels referenced to 1mW (dBm/Hz)')
##    p.add_argument('-t', '--datetime', action='store_true', default=False,
##        help='Indicate that timestamps in the .csv file are in Excel\'s datetime format')
    p.add_argument('--debug', action='store_true', default=False,
        help='Drop into ipython shell at predefined point(s) to debug the script')
    p.add_argument('--hold', action='store_true', default=False,
        help='Perform a maximum value HOLD during averaging and plot it as a second line')
    p.add_argument('--bplot', action='store_true', default=False,
        help='If using background file, choose whether to plot the background reference in a difffert color')
    p.add_argument('--ptype', type=str, metavar='TYPE', default='log',
        help='Control plot vertical scale (linear or log)')
    p.add_argument('--atype', type=str, metavar='TYPE', default='log',
        help='Control averaging method (linear or log)')
        # http://www.dtic.mil/dtic/tr/fulltext/u2/657404.pdf
    ## for handling RASDRviewer versions
    v = DEF_VERSION.split('.')
    ver = v[0]+'.'+v[1]+'.'+v[2]
    p.add_argument('--format', type=str, metavar='X.Y.Z', default=ver,
        help='Specify the RASDRviewer .csv output format to interpret')

    opts = p.parse_args(sys.argv)
    execute(opts)
示例#55
0
def main():
    desc = 'A simplified GUI for wiping your Twitter history'
    parser = GooeyParser(description=desc)

    creds_parser = parser.add_argument_group(
        'First, enter your Twitter API credentials:',
        gooey_options={
            'show_border': False,
            'columns': 2
        })
    creds_parser.add_argument('consumer_key',
                              metavar='Consumer Key',
                              widget='PasswordField')
    creds_parser.add_argument('consumer_secret',
                              metavar='Consumer Secret:',
                              widget='PasswordField')
    creds_parser.add_argument('access_token',
                              metavar='Access Token:',
                              widget='PasswordField')
    creds_parser.add_argument('access_token_secret',
                              metavar='Access Token Secret:',
                              widget='PasswordField')

    date_parser = parser.add_argument_group('Select your cutoff date')
    date_parser.add_argument(
        'stop_date',
        metavar='Tweets published before this date will be deleted:',
        widget='DateChooser')

    keepers = parser.add_argument_group('Keeping any tweets?')
    keepers.add_argument(
        'keepers',
        default='None',
        metavar='Enter tweet IDs you want to keep, separated by commas. '
        '(If not, leave as \'None\'.)')

    args = parser.parse_args()

    consumer_key = args.consumer_key
    consumer_secret = args.consumer_secret
    access_token = args.access_token
    access_token_secret = args.access_token_secret

    if args.keepers == 'None':
        if os.path.exists(os.path.join('data', 'keepers.json')):
            with open(os.path.join('data', 'keepers.json'), 'r') as j:
                keeping_tweets = json.load(j)
        else:
            pass
    else:
        keeping_tweets = trapper_keeper(args.keepers)

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)

    tweets = get_tweets(api)

    try:
        nonkeepers = [
            tweet for tweet in tweets if tweet.id not in keeping_tweets
        ]
        destroyer(nonkeepers, api, args.stop_date)
    except NameError:
        destroyer(tweets, api, args.stop_date)
def param_parser():
    stored_args = {}
    # get the script name without the extension & use it to build up
    # the json filename
    script_name = os.path.splitext(os.path.basename(__file__))[0]
    congifg_folder = AtlassGen.makedir("C:\\pythontools")
    args_file = os.path.join(congifg_folder,
                             "{}-args.json".format(script_name))
    '''
    globalmapperexe = glob.glob('C:\\Program Files\\'+'GlobalMapper2*')
    globalmapperexe = '{0}\\global_mapper.exe'.format(globalmapperexe[0])
    print(globalmapperexe)
    # Read in the prior arguments as a dictionary
    if os.path.isfile(args_file):
        with open(args_file) as data_file:
            stored_args = json.load(data_file)
    '''
    parser = GooeyParser(description="Make Contour")
    parser.add_argument("inputfolder",
                        metavar="LAS file Folder",
                        widget="DirChooser",
                        help="Select las file folder",
                        default=stored_args.get('inputfolder'))
    parser.add_argument(
        "filepattern",
        metavar="Input File Pattern",
        help=
        "Provide a file pattern seperated by ';' for multiple patterns (*.laz or 123*_456*.laz;345*_789* )",
        default=stored_args.get('filepattern'))
    parser.add_argument("layoutfile",
                        metavar="TileLayout file",
                        widget="FileChooser",
                        help="TileLayout file(.json)",
                        default=stored_args.get('layoutfile'))
    parser.add_argument("outputpath",
                        metavar="Output Directory",
                        widget="DirChooser",
                        help="Output directory",
                        default=stored_args.get('outputpath'))
    cls_type = parser.add_mutually_exclusive_group(
        required=True, gooey_options={'initial_selection': 0})
    cls_type.add_argument("--type1",
                          metavar="Type 1  [classes- DEM, 3,4,9]",
                          action='store_true')
    cls_type.add_argument("--type2",
                          metavar="Type 2 [classes- DEM, 3,4,5,6,1,9,10,13]",
                          action='store_true')
    cls_type.add_argument("--type3",
                          metavar="Type 3 [classes- DEM, 3,4,5,6,1,9,10,13]",
                          action='store_true')
    parser.add_argument("--diff",
                        metavar="Diff - Make ascfs to check coverage",
                        action='store_true',
                        default=True)
    parser.add_argument(
        "projection",
        metavar="Projection",
        choices=['AMG (Australian Map Grid)', 'MGA (Map Grid of Australia)'],
        default=stored_args.get('projection'))
    parser.add_argument(
        "datum",
        metavar="Datum",
        choices=['D_AUSTRALIAN_1984', 'D_AUSTRALIAN_1966', 'GDA94'],
        default=stored_args.get('datum'))
    parser.add_argument("zone",
                        metavar="UTM Zone",
                        choices=['50', '51', '52', '53', '54', '55', '56'],
                        default=stored_args.get('zone'))
    parser.add_argument("step",
                        metavar="Step for lasgrid",
                        type=float,
                        default=stored_args.get('step'))
    parser.add_argument("gmexe",
                        metavar="Global Mapper EXE",
                        widget="FileChooser",
                        help="Location of Global Mapper exe",
                        default='globalmapperexe')
    parser.add_argument("-workspace",
                        metavar="Create Global Mapper workspace",
                        action='store_true')
    parser.add_argument(
        "-onlymapC",
        metavar="Create only the map catalogs(ascs must be available",
        action='store_true')
    parser.add_argument("-c",
                        "--cores",
                        metavar="Cores",
                        help="No of cores to run",
                        type=int,
                        default=stored_args.get('cores'))

    args = parser.parse_args()

    # Store the values of the arguments so we have them next time we run
    with open(args_file, 'w') as data_file:
        # Using vars(args) returns the data as a dictionary
        json.dump(vars(args), data_file)

    return args
def main():
    """Running desktop app"""

    desc = u'Введите параметр и нажмите "Запуск"'

    p = GooeyParser(description=desc)

    p.add_argument('-a',
                   '--a',
                   default=2,
                   type=int,
                   help='Кол-во перевозимых детей')
    p.add_argument('-b', '--b', default=25, type=int, help='Возраст водителя')
    p.add_argument('-c', '--c', default=3, type=int, help='Кол-во детей всего')
    p.add_argument('-d', '--d', default=2, type=int, help='Возраст детей')
    p.add_argument('-e', '--e', default=4, type=int, help='Водительский стаж')
    p.add_argument('-f', '--f', default=2, type=int, help='Категории')
    p.add_argument('-s',
                   '--s',
                   default=3,
                   type=int,
                   help='Кол-во страховых случаев')
    p.add_argument('-i',
                   '--i',
                   default=2,
                   type=int,
                   help='Интегрированный показатель')
    p.add_argument('-k', '--k', default=1, type=int, help='Возраст автомобиля')
    p.add_argument('-m',
                   '--m',
                   default=2,
                   type=int,
                   help='Категория автомобиля')

    global args
    args = p.parse_args()

    with open('xgb_model.pickle', 'rb') as f:
        clf_2 = pickle.load(f)

    result = clf_2.predict_proba(
        pd.DataFrame([
            args.a, args.b, args.c, args.d, args.e, args.f, args.s, args.i,
            args.k, args.m
        ]).T)[0][0]

    print 'вероятность наступления страхового случая составляет : {} процентов'.format(
        result)
示例#58
0
def arg_define():
    parser = GooeyParser(description='Pix Plot analysis')
    parser.add_argument(
        'image_Dir',
        widget='DirChooser',
        help=
        'Folder containing all images prepared for analysis. Images should be in JPEG format ending in .jpg'
    )
    parser.add_argument('model_dir',
                        widget='DirChooser',
                        help='Select folder location of the model.')
    parser.add_argument(
        'model_use',
        widget='FileChooser',
        help='Select the pretrained model that you want to use.')
    parser.add_argument(
        'clusters',
        action='store',
        type=int,
        help='Choose the number of hotspots you want pix_plot to find')
    parser.add_argument('validate', action='store', help='TRUE or FALSE')
    parser.add_argument('output',
                        widget='DirChooser',
                        help='The folder where output files will be stored')
    parser.add_argument('method',
                        action='store',
                        help='Select method for mapping, type umap or TSNE')
    args = parser.parse_args()
    return args
示例#59
0
def param_parser():
    stored_args = {}
    # get the script name without the extension & use it to build up
    # the json filename
    script_name = os.path.splitext(os.path.basename(__file__))[0]
    congifg_folder = AtlassGen.makedir("C:\\pythontools")
    args_file = os.path.join(congifg_folder,
                             "{}-args.json".format(script_name))
    # Read in the prior arguments as a dictionary
    if os.path.isfile(args_file):
        with open(args_file) as data_file:
            stored_args = json.load(data_file)

    namestr = " E = b (Y - f) + a (X - g) + d + g \n N = a (Y - f) - b (X - g) + c + f "
    namestr = namestr + '\na=' + str(a) + ' b= ' + str(b) + ' c= ' + str(c)
    namestr = namestr + '\nd=' + str(d) + ' f= ' + str(f) + ' g= ' + str(g)

    parser = GooeyParser(description=namestr)
    parser.add_argument("inputfolder",
                        metavar="LAS file Folder",
                        widget="DirChooser",
                        help="Select las file folder",
                        default=stored_args.get('inputfolder'))
    parser.add_argument("filetype",
                        metavar="Input File Pattern",
                        default='laz')
    parser.add_argument("layoutfile",
                        metavar="TileLayout file",
                        widget="FileChooser",
                        help="TileLayout file(.json)",
                        default=stored_args.get('layoutfile'))
    parser.add_argument("outputfolder",
                        metavar="Output Directory",
                        widget="DirChooser",
                        help="Output directory",
                        default=stored_args.get('outputfolder'))
    parser.add_argument("-cores", metavar="Cores", type=int, default=12)

    args = parser.parse_args()

    # Store the values of the arguments so we have them next time we run
    with open(args_file, 'w') as data_file:
        # Using vars(args) returns the data as a dictionary
        json.dump(vars(args), data_file)

    return args
示例#60
0
def main():
    desc = "A Python GUI App to convert a .mp3 and an image into a .mp4"
    mp3_select_help_msg = "Select a .mp3 audio file to process"
    image_select_help_msg = "Select an image file (.png or .jpg) to use in the video"

    my_parser = GooeyParser(description=desc)
    my_parser.add_argument("mp3_to_convert",
                           help=mp3_select_help_msg,
                           widget="FileChooser")
    my_parser.add_argument("image_to_convert",
                           help=image_select_help_msg,
                           widget="FileChooser")
    my_parser.add_argument("output_dir",
                           help="Directory to save output",
                           widget="DirChooser")

    args = my_parser.parse_args()

    # construct the .mp3 input audio file path
    mp3_to_convert_Path = Path(args.mp3_to_convert)

    # construct image file path
    image_to_convert_Path = Path(args.image_to_convert)

    # construct output .mp4 file path
    mp4_outfile_name = str(mp3_to_convert_Path.stem) + ".mp4"
    mp4_outfile_Path = Path(args.output_dir, mp4_outfile_name)
    mp4_outfile_Path.unlink(
        missing_ok=True)  # delete the .mp4 file if it's there

    # Determine ffmpeg executable file path
    """
    where ffmpeg
    """
    if platform.system() == 'Windows':
        ffmpeg_path_bytes = subprocess.check_output(
            "where ffmpeg", shell=True)  # returns bytes
    elif platform.system() == 'Linux':
        ffmpeg_path_bytes = subprocess.check_output("which ffmpeg", shell=True)

    ffmpeg_executable_path = ffmpeg_path_bytes.decode().strip()
    print("ffmpeg_executable_path: ", ffmpeg_executable_path)

    # create the ffmpeg command
    """
    ffmpeg -loop 1 -i image.png -i audio.mp3 -c:a copy -c:v libx264 -shortest video.mp4
    """

    ffmpeg_command = f"-loop 1 -i {image_to_convert_Path} -i {mp3_to_convert_Path} -c:a copy -c:v libx264 -shortest {mp4_outfile_Path}"
    cmd_command = f"{ffmpeg_executable_path} {ffmpeg_command}"

    print(f"input .mp3 file \n {mp3_to_convert_Path}")
    print()
    print(f"input image file \n {image_to_convert_Path}")
    print()
    print(f"output .mp4 file \n {mp4_outfile_Path}")
    print()
    print("cmd prompt command: ")
    print()
    print(cmd_command)

    # call ffmpeg
    returned_value = subprocess.call(
        cmd_command, shell=True)  # returns the exit code in unix
    print("returned value:", returned_value)