Beispiel #1
0
 def __init__(self):
     source = ap(
         description='¡Genera los valores exactos para algunas particiones!'
     )
     nope = source.add_mutually_exclusive_group()
     source.add_argument('M', type=int, help="Tamaño disponible")
     source.add_argument('-X',
                         type=float,
                         help="1° Porcentaje a calcular",
                         nargs='?',
                         const=16,
                         default=16)
     source.add_argument('-Y',
                         type=float,
                         help="2° Porcentaje a calcular",
                         nargs='?',
                         const=84,
                         default=84)
     source.add_argument('-A',
                         type=float,
                         help="3° Porcentaje a calcular",
                         nargs='?',
                         const=32,
                         default=32)
     source.add_argument('-B',
                         type=float,
                         help="4° Porcentaje a calcular",
                         nargs='?',
                         const=68,
                         default=68)
     source.add_argument('-R',
                         type=int,
                         help="Memoria RAM",
                         nargs='?',
                         const=0,
                         default=0)
     source.add_argument('-E',
                         type=int,
                         help="Tamaño de la partición EFI",
                         nargs='?',
                         const=261,
                         default=261)
     source.add_argument('-L',
                         type=int,
                         help="Espacio vacío al final del disco",
                         nargs='?',
                         const=1,
                         default=1)
     nope.add_argument(
         '-MB',
         help="Tipo de Unidad para medir el tamaño disponible",
         action="store_true")
     nope.add_argument(
         '-GB',
         help="Tipo de Unidad para medir el tamaño disponible",
         action="store_true")
     Values = self.Values()
     s("clear")
     print Values.linux(source.parse_args(), self.Funcs)
     print Values.windows(source.parse_args(), self.Funcs)
Beispiel #2
0
def parse_args():
    p = ap(description='test OFX account query')
    p.add_argument('-i', '--institution',
                   action='store', type=str, required=True,
                   help='institution name, case insensitive')
    p.add_argument('-u', '--user',
                   action='store', type=str, required=True,
                   help='user name')
    p.add_argument('-p', '--passwd',
                   action='store', type=str, required=True,
                   help='user password')
    return p.parse_args()
Beispiel #3
0
def initArgParser():
    parser = ap()
    parser.add_argument(
        "-p",
        "--plot",
        help="Parameter for chart type generate, can be boxplot",
        dest="plot")
    parser.add_argument("-x",
                        "--xaxis",
                        help="Parameter for chart xAxis generate,\
                                                can be Age, City or Seniority",
                        dest="xAxis")
    args = parser.parse_args()
    if not len(sys.argv) > 1:
        log.error("Plz try: plot.py -p [chartType] -x [xAxis]")
        sys.exit(0)
    return args
def get_args():
    parser = ap()
    parser.add_argument("-l",
                        "--length",
                        dest="length",
                        type=int,
                        required=True,
                        help="length of the nop slide")
    parser.add_argument(
        "-p",
        "--payload",
        dest="payload",
        type=str,
        required=True,
        help="your custom payload in bytes, will be inserted after nop slide")
    parser.add_argument("-o",
                        "--outfile",
                        dest="outfile",
                        type=str,
                        required=False,
                        help="save to file")
    return parser.parse_args()
Beispiel #5
0
def main():

    parser = ap(
        help="To install dependencies, setting up database and load data into it. "
    )
    parser.add(
        "-i",
        "--install",
        action="store_true",
        help="Installing Dependencies and Setting Up Database",
    )
    parser.add(
        "-l",
        "--load",
        action="store_true",
        help="Load Data from csv file to database (File Should be present in Data/CSV_Database Directory). Note: Only Sample Format to be used for structure and file name. For Sample Format of csv file Check Data/Sample_CSV Folder",
    )
    arg = parser.parse()
    if arg.install:
        install_db_dep()
    if arg.load:
        load_data()
Beispiel #6
0
def main():
    parser = ap(description='Sort all of your files in any directory')
    parser.add_argument(
        '--directory',
        action='store',
        dest='directory',
        type=str,
        help='The name of the directory in which to sort the files')

    args = parser.parse_args()

    sorter = FileSorter()

    if args.directory:
        sorter.set_working_directory(args.directory)

        # configure sorter
        sorter.configure()

        all_files = sorter.get_all_files_from_dir()
        categorized_files = sorter.categorize_files(all_files)

        sorter.sort_files()
Beispiel #7
0
def main():
    parser = ap(description='File-sorter config utility')
    parser.add_argument('--show',
                        action='store_true',
                        help='Showing all path patterns')
    parser.add_argument('--edit-name', action='store', nargs=2,\
        help='Edit category name,\n usage: file-sorter-config --edit-name old_name new_name')
    parser.add_argument('--edit-ext', action='store', nargs=1,\
        help='Edit category extensions,\n usage: file-sorter-config --edit-ext category_name')
    parser.add_argument('--add', action='store', nargs=1,\
        help='Add new category,\n usage: file-sorter-config --add category_name')

    args = parser.parse_args()

    config = Config()
    config.read_config()
    config.get_categories()
    config.get_path_patterns()

    if args.show:
        config.print_path_patterns()

    if args.edit_name:
        pattern_name, new_name = args.edit_name

        config.edit_path_pattern_name(pattern_name, new_name)

    if args.edit_ext:
        pattern_name = args.edit_ext[0]

        edit_extensions(config, pattern_name)

    if args.add:
        pattern_name = args.add[0]

        config.add_path_pattern(pattern_name)
        edit_extensions(config, pattern_name)
Beispiel #8
0
def main():
    from argparse import ArgumentParser as ap
    ap = ap()
    ap.add_argument('filename')
    args = ap.parse_args()
    dump_graphics(args.filename, versions.ruby)
Beispiel #9
0
from argparse import ArgumentParser as ap
import time
from Utility import print_records
import sys

parser = ap(description="Python FIle to view Records")
parser.add_argument("-i",
                    "--id",
                    action="store",
                    help="Input of User Id for further function use")
# Here constant is stored in case no argument is passed
parser.add_argument(
    "-v",
    "--view",
    const=True,
    nargs="?",
    help="to view records of Booking, Caretaker,Elderly,etc.",
)
args = parser.parse_args()
print("WORKING")
if args.id == None:
    if args.view == None:
        invalid_arg()
    else:
        print_records("Caretaker")
        print_records("Elderly")
        print_records("BookingRecord")
        print_records("PendingBooking")
        print_records("VerificationProof")
        print_records("ReviewInfo")
Beispiel #10
0
from bs4 import BeautifulSoup as bs
from requests import get
from configparser import ConfigParser as cp
import xlrd
from contextlib import closing
import json
import re
from argparse import ArgumentParser as ap
import xml.etree.ElementTree as et

parser = ap(prog="n_scraper", description="nekakav opis, onako nek se nadje")
parser.add_argument('-z', help='ime zupanije!')
parser.add_argument('-c', help='ime grada!')
parser.parse_args()
args = parser.parse_args()

tree = et.parse('test.xml')
root = tree.getroot()


def city():
    for county in root:
        if county.attrib["name"] == args.z:
            return county.attrib["code"]
        for child in county:
            if child.attrib["name"] == args.c:
                return child.attrib["code"]


print(city())
def parser():
    parser = ap()
    parser.add_argument('-r', '--receiver', default="*****@*****.**", \
        help="Receiver's email address")
    arg = parser.parse_args()
    return arg
Beispiel #12
0
from os import path, access, R_OK

import entropyDeviationType

def printBlock(idx, block):

	print "\t\tBN: {0:^5X}\tC: {1:^7.4f}\tS: {2:^7.4f}\tES: {3:^7.4f}\tER: {4:^7.4f}".format(idx, 
																						block.chi_square, 
																						block.shannon,
																						block.estimate,
																						block.error)

	return


parser = ap(description='Accepted Arguments')
parser.add_argument(	'file', 		 
						help='The input file to scan')
parser.add_argument(	'--blocksize',	'-b',
						help='The size of the blocks to split the input file into; specified in bytes',
						default=8192)
parser.add_argument(	'--blockscore', '-s', 
						help='Whether to print the score of all the blocks or not', 
						action='store_true')
parser.add_argument(	'--wholescore',	'-w', 
						help='Whether to print the whole file score or not', 
						action='store_true')
parser.add_argument(	'--blockdev',	'-d', 
						help='Whether to calculate and print deviations for a given block', 
						action='store_true')
parser.add_argument(	'--blocknumber', '-n',
Beispiel #13
0
# local imports
from pyign.functions.core import getPTData, getTCData, getLCData, getLSData, getGOState, getAbortState, getNanny, getValveState, getIgnitorState, setValveState, setIgnitorState, setGOState, setAbortState, setNanny, _init_system, pt_index, tc_index, lc_index, check_limits, check_limit_switch, check_go, check_abort, check_pt_data, check_tc_data, check_lc_data
'''
# local imports
from core import getPTData, getTCData, getLCData, getLSData, getGOState, getAbortState, getNanny, getValveState, getIgnitorState, setValveState, setIgnitorState, setGOState, setAbortState, setNanny, _init_system, pt_index, tc_index, lc_index, check_limits, check_limit_switch, check_go, check_abort, check_pt_data, check_tc_data, check_lc_data
'''

script_dir = os.path.dirname(__file__)
file_1 = os.path.join(script_dir, '../raw/press_data.txt')
file_2 = os.path.join(script_dir, '../raw/therm_data.txt')
file_3 = os.path.join(script_dir, '../raw/load_data.txt')
pt_data = getTCData(file_1)
tc_data = getTCData(file_2)
lc_data = getTCData(file_3)

parser = ap(description='Test Stand System State')

parser.add_argument('-s','--start',action = 'store_true',required = False, help = 'Initialize and output initial system state')

parser.add_argument('-n','--nanny',action = 'store_true',required = False, help = 'Turn "Nanny" to "ON"')

parser.add_argument('-g','--go',action = 'store_true',required = False, help = 'Turn "GO/NOGO" to "GO" and change ignitor state')

parser.add_argument('-t','--test',action = 'store_true',required = False, help = 'Tests system with input sensor data')

args = parser.parse_args()

if args.start == True:
    vst, ist, abt, gst, ptl, tcl, lcl = _init_system()
    print(' ')
    print(' ')
Beispiel #14
0
        return self.version['map_groups_address']
    param_classes = [MapGroupPointer]
    def parse(self):
        self.count = len(self.version['map_groups'])
        List.parse(self)
        for i, chunk in enumerate(self.chunks):
            chunk.group = i
            label_name = 'gMapGroup{}'.format(i)
            label = Label(chunk.real_address)
            label.asm = label_name
            chunk.chunks += [label]
            chunk.label = label


if __name__ == '__main__':
    from argparse import ArgumentParser as ap
    ap = ap()
    ap.add_argument('version', nargs='?', default='ruby')
    ap.add_argument('--debug', action='store_true')
    args = ap.parse_args()
    version = versions.__dict__[args.version]
    setup_version(version)
    if args.debug:
        print print_nested_chunks(dump_maps(version))
    else:
        chunks = flatten_nested_chunks(dump_maps(version))
        for path in version['maps_paths']:
            insert_chunks(chunks, path, version)
        create_files_of_chunks(chunks)
        find_files.main(version)
Beispiel #15
0
        return root

    def make_xml(self):
        """Iterate over jobs and make and xml document out of them"""
        self.tree = self.get_job_tree(self.job)

    def __str__(self):
        self.make_xml()
        dom = md.parseString(et.tostring(self.tree))
        bytes_str = dom.toprettyxml(encoding='utf-8')
        return bytes_str.decode('utf-8')


if __name__ == '__main__':

    argparser = ap()
    argparser.add_argument('config_file')
    argparser.add_argument('-f', '--file', help='Name of xml file to write to')
    argparser.add_argument('-s',
                           '--submit',
                           help='Submit xml file after writing',
                           action='store_true')
    args = argparser.parse_args()

    job = Job(config_file=args.config_file)
    req = Request(job)

    if args.file:
        with open(args.file, 'w') as f:
            f.write(req.__str__())
    else:
Beispiel #16
0
base_palette = []
cycle_palette = []
palette_direction = ''
palette_len = 0

VALID_DIRECTIONS = ['left', 'right']
VALID_DIR_RE_STRING = '^('
for i in VALID_DIRECTIONS:
    VALID_DIR_RE_STRING += i
    if i != VALID_DIRECTIONS[len(VALID_DIRECTIONS) - 1]:
        VALID_DIR_RE_STRING += '|'
VALID_DIR_RE_STRING += ')$'

parser = ap(
    description=
    'Generate separate, palette cycling images given base colors, cycle colors, and direction.'
)
parser.add_argument(
    'image',
    metavar='base_image',
    help=
    'A base image to start out from. This should be a png with alpha channel.')
parser.add_argument(
    'listfile',
    metavar='list_file',
    help=
    'A text file containing information about the palette mapping. The file itself should be in the format of "base <hex> <hex> ... \\n dir <left|right> \\n cycle <hex> <hex> ...", where \\n denotes a new line.'
)
parser.add_argument(
    'output',
    metavar='output_prefix',
Beispiel #17
0
from Utility.Utility import verify_user, invalid_user, chgdir
from argparse import ArgumentParser as ap
from os import system as cli

chgdir()
miscellaneous = "Miscellaneous Python file to Update Carely user records and confirm Booking status and Verify Carely Users "
parser = ap(description=miscellaneous)
parser.add_argument("-u",
                    "--update",
                    action="store_true",
                    help="To Book Appointment")
parser.add_argument("-v",
                    "--verification",
                    action="store_true",
                    help="To register new Carely User.")
args = parser.parse()

uid = input("Enter a Valid Carely Id")
if uid[:2] not in ["el,ct"]:
    invalid_user()
db = "Caretaker" if uid[:2] else "Elderly"
if verify_user(uid, db, "id"):
    if arg.update:
        cli("python Miscellaneous/Update.py -i '" + uid + "'")
    if arg.verification:
        cli("python Miscellaneous/Verification.py -i '" + uid + "'")
Beispiel #18
0
def main():
    parser = ap(
        description=
        "Creates an essentially random password by leveraging hash algorithms")
    parser.add_argument("-l",
                        "--length",
                        action="store",
                        type=int,
                        dest="length",
                        default=30,
                        help="specify password length (default=30)")
    parser.add_argument(
        "-r",
        "--rounds",
        action="store",
        type=int,
        dest="numRounds",
        default=500000,
        help="specify number of hashing rounds (default=500000)")
    args = parser.parse_args()
    pwLength = args.length
    rounds = args.numRounds
    seed1 = ""
    seed2 = ""
    seed3 = ""

    procList = []
    p1 = Process(target=genSeed, args=(pwLength, seed1))
    p2 = Process(target=genSeed, args=(pwLength, seed2))
    p3 = Process(target=genSeed, args=(pwLength, seed3))
    procList.append(p1)
    procList.append(p2)
    procList.append(p3)
    for i in range(3):
        procList[i].start()
    for i in range(3):
        procList[i].join()

    blaked = blake2b()
    sha3d = sha3_512()
    sha2d = sha512()

    blaked.update(bytearray(seed1, 'utf-8'))
    sha3d.update(bytearray(seed2, 'utf-8'))
    sha2d.update(bytearray(seed3, 'utf-8'))

    procList2 = []
    p21 = Process(target=hashUpdater, args=(blaked, rounds))
    p22 = Process(target=hashUpdater, args=(sha3d, rounds))
    p23 = Process(target=hashUpdater, args=(sha2d, rounds))
    procList2.append(p21)
    procList2.append(p22)
    procList2.append(p23)
    for i in range(3):
        procList2[i].start()
    for i in range(3):
        procList2[i].join()

    forwardNibbles = selectNibbles(pwLength, blaked, sha3d, sha2d)
    rblaked = blaked.hexdigest()[::-1]
    rsha3d = sha3d.hexdigest()[::-1]
    rsha2d = sha2d.hexdigest()[::-1]
    revNibbles = selectNibblesFromStr(pwLength, rblaked, rsha3d, rsha2d)

    # yields a list of hex-bytes
    prefinal = [
        i + j for i, j in zip(forwardNibbles[::2], forwardNibbles[1::2])
    ]
    prefinal2 = [i + j for i, j in zip(revNibbles[::2], revNibbles[1::2])]

    # randomly map hex-bytes to chars and cat to final result
    prefinal = mapper(pwLength, prefinal, createConvDict(ALL_CHAR),
                      createConvDict(ALL_CHAR), createConvDict(ALL_CHAR))
    final = ''.join(prefinal)
    prefinal2 = mapper(pwLength, prefinal2, createConvDict(ALL_CHAR),
                       createConvDict(ALL_CHAR), createConvDict(ALL_CHAR))
    final += ''.join(prefinal2)

    # ensure user requirement is met
    #   ...seriously, one char that is less outrageously random is okay
    if len(final) != pwLength:
        idx = randb(len(ALL_CHAR))
        addToFinal = createConvDict(ALL_CHAR)[hex(idx)]
        final += ''.join(addToFinal)
        print("\nsecret = " + final)
    else:
        print("\nsecret = " + final)
Beispiel #19
0
        if ext2 != 'eps' and ext2 != 'ps':
          MISC_PATH.append(
            {re.sub(u'{}$'.format(ext),u'xbb',figpath2):
             re.sub(u'{}$'.format(ext),u'xbb',figname2)})

      fout.write(line)

def bbl_print(filename, fout):
  filename = filename.replace(ur'.tex',ur'.bbl')
  with codecs.open(filename, 'r', 'utf-8') as bbl:
    for line in bbl:
      fout.write(line)


if __name__ == '__main__':
  parser = ap(
    description='Make a multi-file tex documents into a single tex file.')
  parser.add_argument(
    'master_tex', metavar='master', type=unicode,
    help='master .tex file to be converted.')
  parser.add_argument(
    'archive', metavar='archive', type=unicode,
    help='output archive file (tar.gz).')

  args = parser.parse_args()

  archive_base = re.sub(ur'\.tar\.gz$',u'',args.archive)
  archive_file = archive_base + '.tar.gz'

  master = args.master_tex

  with TarFile.gzopen(archive_file, 'w') as arv:
Beispiel #20
0
    i.e. it corresponds to \sigma in k(x,y)=\exp(-0.5*||x-y||^2 / \sigma^2) where
    \sigma is the median distance. \gamma = 0.5/(\sigma^2)
    """
    inds = np.random.permutation(len(Z))[:np.max([num_subsample, len(Z)])]
    dists = squareform(pdist(Z[inds], 'sqeuclidean'))
    median_dist = np.median(dists[dists > 0])
    mean_dist = np.mean(dists[dists > 0])
    
    sigma = np.sqrt(0.5 * median_dist)
    
    gamma = 0.5 / (sigma ** 2)
    
    return {'sigma':sigma, 'median':median_dist, 'mean':mean_dist}, gamma, Z.shape

if __name__ == "__main__":
    parser = ap(description='This script performs different tests over any input dataset of numerical representations. The main aim is to determine an estimate of a valid range of bandwidths for such a dataset, under the assumption the user wants to use any RBF-like kernel. Also it can be tested some bandwidth entered by the user. In both cases it is possible to see the resultant kernel matrices: the values and a furface plotting (when graphics are available).')    
    parser.add_argument("-f", help="Input file name (vectors)", metavar="input_file", required=True)
    parser.add_argument("-v", help="Custom value specification. If argument for -v is not the number you want to test, you can type {'sigma':sigma, 'median':median_dist, 'mean':mean_dist}. default = 'median'", metavar="custom_value", default = 'median')
    parser.add_argument("-s", help="Number of samples to be considered. Must not be greater than the available number of them.", metavar="considered_rows", default=0)
    parser.add_argument("-c", help="Toggles if you want to see a combined kernel. The default is a 5-degree Polynomial kernel.", default=False, action="store_true")
    parser.add_argument("-g", help="Toggles if you have graphics for surface plotting. You will see firstly the input data, after that the obtained Gaussian kernel. If you selected seeing combined kernel, you will see also the Polynomial kernel and after that the combined kernel (Poly-Gaussian).", default=False, action="store_true")
    
    args = parser.parse_args()
    if args.s:
        
        with open(args.f, 'r') as f:
            lines = (line for l, line in enumerate(f) if l < int(args.s)) 
            feats = genfromtxt(lines).astype('float64')
    else:
        feats = loadtxt(args.f)
Beispiel #21
0
# relative modules
# from ...math.miscmath import raster_matrix

# global attributes
__all__ = ('test', )
__doc__ = """."""
__filename__ = __file__.split('/')[-1].strip('.py')
__path__ = __file__.strip('.py').strip(__filename__)


def main():
    """Main."""
    pass


def test():
    """Testing function for module."""
    pass


if __name__ == "__main__":
    """Directly Called."""
    parser = ap('Generator for ARCSAT mosaics.')

    print('Testing module')
    test()
    print('Test Passed')

# end of code
Beispiel #22
0
def arg_parser():
    parser = ap()

    parser.add_argument('-db',
                        dest='db',
                        help='The name of database'
                        ' from which tables will'
                        ' have to mapped ')

    parser.add_argument('-t',
                        dest='tables',
                        nargs='+',
                        help='List of table names '
                        'each separated by one or '
                        'more space')

    parser.add_argument('-host',
                        dest="host",
                        help="Name of the MySql host\n"
                        " For Eg., localhost , "
                        "mysql.mydomain.com ,....etc")

    parser.add_argument('-u',
                        dest="uname",
                        help="Your Mysql username")

    parser.add_argument('-o',
                        dest="outfile",
                        help="Output file name ,"
                        "along with its extension and "
                        "absolute path\n For Eg. , /home"
                        "/shravan97/Desktop/out.py")

    args = parser.parse_args()

    if args.uname is None:
        print "Please enter"\
            " your MySql username"
        sys.exit(0)
    elif args.db is None:
        print "Please enter"\
            " the required database name"
        sys.exit(0)
    elif args.host is None:
        print "Please enter in the "\
            " MySql host"
        sys.exit(0)
    else:
        values = {}
        values['uname'] = args.uname
        values['db'] = args.db
        values['host'] = args.host

        if args.tables is None:
            values['tables'] = '*'
        else:
            values['tables'] = args.tables

        if args.outfile is None:
            values['out'] = 'db.py'
        else:
            values['out'] = args.outfile

        return values
Beispiel #23
0
# actual imports
from datetime import date, timedelta as td
from dateutil.parser import parse as date_parse
from argparse import ArgumentParser as ap
import holidays

def is_empty( data ):
    try:
        data
        return False
    except:
        return True

# cli args
parser = ap( description="Prints the number of weekdays between two dates. Uses the dateutil library to parse the input. Should be able to accept most standard date formats." )
parser.add_argument( "start", action="store", help="the date to start counting from." )
parser.add_argument( "end", action="store", help="The date to count to." )
parser.add_argument( "-i", "--inverse", action="store_true", dest="i", help="Perform the inverse action and print the number of weekends" )
parser.add_argument( "-x", "--holidays", action="store_true", dest="x", help="Skip US holidays during calculation. Has no effect if specified with -i." )
parser.add_argument( "-a", "--all", action="store_true", dest="a", help="Count all days instead. Specifying -a causes -x and -i to have no effect." )
args = parser.parse_args()


# arg init and input error checks
try:
    s = date_parse( args.start )
    e = date_parse( args.end )
except ValueError:
    print( "[ERR] One of the provided dates was invalid." )
    sys.exit( -1 )
Beispiel #24
0
from argparse import ArgumentParser as ap

parser = ap(description='This script divides a tab separated file containing a sentence and its score.')
parser.add_argument("-f", help="Input file name (complete democratic)", metavar="input_file", required=True)
parser.add_argument("-F", help="Output file name (scores complete)", metavar="output_file", required=True)

args = parser.parse_args()

with open(args.f, 'r') as fi, open(args.F, 'w') as fo:   
    for line in fi:
        fo.write("%s" % (line.split("\t")[1]))
Beispiel #25
0
from argparse import ArgumentParser as ap
from os.path import basename, splitext, dirname
import sys
from math import modf

def Round(x):
    d, i = modf(x)
    if d > 0.5:
        return i + 1
    else:
        return i

parser = ap(description='This script converts the predictions in a dictionary of estimated outputs in to ranked sentences.')
parser.add_argument("-s", help="Input file name of sentences.", metavar="sent_file", required=True)
parser.add_argument("-p", help="Regression predictions file." , metavar="predictions", required=True)
parser.add_argument("-n", help="Percentage of output sentences.", metavar="per_sents", default=25)
parser.add_argument("-m", help="Minimum sentence length.", metavar="min_length", default=0)
parser.add_argument("-d", action='store_true', help="Score order of the output summary. The default is ascendant. typing '-d' toggles descendant.", default=False)
parser.add_argument('-e', action='store_true', help='Toggles printing the estimated scores in the output file if required.')
parser.add_argument('-c', action='store_true', help='Toggles printing source information comments in the output file.')
parser.add_argument('-l', action='store_true', help='Toggles if logical order is required.')
args = parser.parse_args()

sent_file = args.s
source = basename(args.s)
pred_file = args.p
assert 1 < int(args.n) <= 100 # Valid compression percentaje?
#<<<<<<< HEAD
#LME = 28 # Longueur Moyenne des l'Enonces
#=======
LME = int(args.m) # Longueur Moyenne des l'Enonces (0 := all lengths allowed)
Beispiel #26
0
from argparse import ArgumentParser as ap
from pylab import *
from scipy.io import wavfile
import os

parser = ap(
        description='convert single-period .wav files to C array'
        )
parser.add_argument(
        '-d', '--dir',
        help='the directory containing the .wav files to convert',
        default='.'
        )
parser.add_argument(
        '-f', '--fmt',
        help='format of the data',
        choices=['MYFLT', 'int16_t', 'double'],
        default='MYFLT'
        )
parser.add_argument(
        '-o', '--outfile',
        help='name of the header file to generate',
        default='wt.h'
        )
parser.add_argument(
        '--origin',
        default=''
        )
args = parser.parse_args()

path = './wav/AKWF_sinharm'
Beispiel #27
0
from argparse import ArgumentParser as ap
from BaseClass import Register_Caretaker as ct_reg
from BaseClass import Register_Elderly as el_reg

parser = ap(description="New Registration of user (Caretaker/Elderly)")
parser.add_argument("-c",
                    "--caretaker",
                    default=1,
                    action="store_true",
                    help="Selection of Caretaker")
parser.add_argument("-e",
                    "--elderly",
                    default=2,
                    action="store_true",
                    help="Selection of Elderly")

args = parser.parse_args()

if type(args.caretaker) == type(True):
    print(
        "\n***************New Carely Caretaker Registration***************\n")
    ct_reg()
    print("\n*********************Registration is Done*********************\n")
if type(args.elderly) == type(True):
    print("\n***************New Carely Elderly Registration***************\n")
    el_reg()
    print("\n*********************Registration is Done*********************\n")
else:
    print("No Arguments passed here")

    print("***************Registration is Done***************")
Beispiel #28
0
    param_classes = [MapGroupPointer]

    def parse(self):
        self.count = len(self.version['map_groups'])
        List.parse(self)
        for i, chunk in enumerate(self.chunks):
            chunk.group = i
            label_name = 'gMapGroup{}'.format(i)
            label = Label(chunk.real_address)
            label.asm = label_name
            chunk.chunks += [label]
            chunk.label = label


if __name__ == '__main__':
    from argparse import ArgumentParser as ap
    ap = ap()
    ap.add_argument('version', nargs='?', default='ruby')
    ap.add_argument('--debug', action='store_true')
    args = ap.parse_args()
    version = versions.__dict__[args.version]
    setup_version(version)
    if args.debug:
        print print_nested_chunks(dump_maps(version))
    else:
        chunks = flatten_nested_chunks(dump_maps(version))
        for path in version['maps_paths']:
            insert_chunks(chunks, path, version)
        create_files_of_chunks(chunks)
        find_files.main(version)
Beispiel #29
0
def main():
	from argparse import ArgumentParser as ap
	ap = ap()
	ap.add_argument('filename')
	args = ap.parse_args()
	dump_graphics(args.filename, versions.ruby)
Beispiel #30
0
def arg_parser():
    parser = ap()

    parser.add_argument('-db',
                        dest='db',
                        help='The name of database'
                        ' from which tables will'
                        ' have to mapped ')

    parser.add_argument('-t',
                        dest='tables',
                        nargs='+',
                        help='List of table names '
                        'each separated by one or '
                        'more space')

    parser.add_argument('-host',
                        dest="host",
                        help="Name of the MySql host\n"
                        " For Eg., localhost , "
                        "mysql.mydomain.com ,....etc")

    parser.add_argument('-u', dest="uname", help="Your Mysql username")

    parser.add_argument('-o',
                        dest="outfile",
                        help="Output file name ,"
                        "along with its extension and "
                        "absolute path\n For Eg. , /home"
                        "/shravan97/Desktop/out.py")

    args = parser.parse_args()

    if args.uname is None:
        print("Please enter"\
            " your MySql username")
        sys.exit(0)
    elif args.db is None:
        print("Please enter"\
            " the required database name")
        sys.exit(0)
    elif args.host is None:
        print("Please enter in the "\
            " MySql host")
        sys.exit(0)
    else:
        values = {}
        values['uname'] = args.uname
        values['db'] = args.db
        values['host'] = args.host

        if args.tables is None:
            values['tables'] = '*'
        else:
            values['tables'] = args.tables

        if args.outfile is None:
            values['out'] = 'db.py'
        else:
            values['out'] = args.outfile

        return values
Beispiel #31
0

def handleEvent(event):
    global tout
    tout.handle(event)
    collect()


if __name__ == '__main__':
    isroot = os.getuid() is 0
    pidfile = '/tmp/pytouchd.pid'
    byteorder = 'big'  # sys.byteorder

    p = ap(
        prog='touchd',
        description='a adaptive touch driver (e.g. for ODROID VU7 Plus)',
        conflict_handler='resolve',
    )
    p.add_argument('action',
                   choices=['start', 'stop', 'status', 'zombie'],
                   help='start the daemon or stop the running instance',
                   action='store')
    p.add_argument('--device',
                   '-d',
                   help='path to the device, e.g. /dev/hidraw0',
                   action='store',
                   type=str,
                   nargs=1,
                   default='/dev/hidraw0')
    p.add_argument('--debug',
                   '-D',
Beispiel #32
0
#!/usr/bin/python

import sys
from argparse import ArgumentParser as ap
import requests
import json

parser = ap(description='Get an URL and optionally write it to a file')
parser.add_argument('url', help='URL to request')
parser.add_argument('--json', action='store_true', help='Output as JSON. Default is text')
parser.add_argument('--file', '-f', help='Store answer in this file. Default is stdout')

args = parser.parse_args()

r = requests.get(args.url)

if r.status_code != 200:
    print(f"Error: failed to get url: {r.statuscode}")
    sys.exit(1)

if args.json:
    try:
        # pretty printing :-)
        res = json.dumps(r.json(),sort_keys=True,
                         indent=2, separators=(',', ': '))
    except json.decoder.JSONDecodeError:
        print("Invalid JSON")
        sys.exit(1)
else:
    res = r.text
Beispiel #33
0
import os
import hashlib
from argparse import ArgumentParser as ap

checksumlist = {}
hasherclass = hashlib.sha1
BLOCKSIZE = 16384

emptysums = [
    "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    "d41d8cd98f00b204e9800998ecf8427e",
    "da39a3ee5e6b4b0d3255bfef95601890afd80709"
]

parser = ap(description = "List all files in a given location that have the same checksum.",
            epilog = """Copyright 2016 Eero Leno. This software is licensed \
                           under the MIT license.""")

parser.add_argument("directory",
                   nargs = "?", # not required
                   type = str,
                   help = "The location in where to look"
                   )

parser.add_argument("--recursive", "-r",
                   required = False,
                   action = "store_true",
                   help = "Traverse subdirectories"
                   )

parser.add_argument("--all", "-a",
Beispiel #34
0
from ROOT import *
from set_style import *
from argparse import ArgumentParser as ap


def add_bin(i, hists):
    total = 0
    for h in hists:
        total += h.GetBinContent(i)
    return total


gROOT.SetBatch(1)
gStyle.SetOptStat(0)

parser = ap()
parser.add_argument("-m", type=str, help='MC file')
parser.add_argument("-d", type=str, help='Data file')
parser.add_argument("--o1", type=str, help='Output file', default="ev_sel.pdf")
parser.add_argument("--o2",
                    type=str,
                    help='Output file',
                    default="ev_sel_vt.pdf")
parser.add_argument("--o3",
                    type=str,
                    help='Output file',
                    default="ev_sel_vt_close.pdf")
parser.add_argument("--o4",
                    type=str,
                    help='Output file',
                    default="ev_sel_bg.pdf")
                           test_score * 100.))

            if patience <= iter:
                done_looping = True
                break
    print ("Patience: %d" % patience)
    print ("Iterations: %d" % iter)
    end_time = timeit.default_timer()
    #print(('Optimization complete. Best validation score of %f %% '
    #       'obtained at iteration %i, with test performance %f %%') %
    #      (best_validation_loss * 100., best_iter + 1, test_score * 100.))
    #print(('The code for file ' +
    #       os.path.split(__file__)[1] +
    #       ' ran for %.2fm' % ((end_time - start_time) / 60.)), file=sys.stderr)
    return best_iter + 1, best_validation_loss * 100.0, test_score * 100.0

if __name__ == '__main__':

    from argparse import ArgumentParser as ap
    parser = ap(description='This script trains/applies a SVR over any input dataset of numerical representations. The main aim is to determine a set of learning parameters')
    parser.add_argument("--hidden", help="Size of the hidden layer", metavar="hidden", default=100)
    parser.add_argument("--dims", help="Size of the input layer", metavar="dims", required=True)
    parser.add_argument("--lrate", help="The learning rate", metavar="lrate", default=0.01)
    args = parser.parse_args()
# learning_rate=0.01, L1_reg=0.00, L2_reg=0.0001, n_epochs=1000, dataset='mnist.pkl.gz', batch_size=20, n_hidden=500)
    best_iter, best_validation_loss, test_score = test_mlp(learning_rate=float(args.lrate), batch_size=20, n_epochs=100000, n_hidden=int(args.hidden), dataset=args.dims, verbose=True)
              #L1_reg=0.10, L2_reg=0.001 )
    with open("mlp.out", "a") as f:
        f.write("Best validation score of %f %% obtained at iteration %i, with test performance %f %%\tParameters: dims = %d\tHidden = %d\n" % (best_validation_loss, best_iter, test_score, int(args.dims), int(args.hidden)))
    print("Best validation score of %f %% obtained at iteration %i, with test performance %f %%\tParameters: dims = %d\tHidden = %d\n" % (best_validation_loss, best_iter, test_score, int(args.dims), int(args.hidden)))
Beispiel #36
0
    self.handler = handler(logger=self.logger, **options)

  def start(self):
    try:
      while True:
        try:
          self.handler()
        except Exception as e:
          self.logger.error(str(e))
        time.sleep(self.interval)
    except KeyboardInterrupt as e:
      self.logger.info('Executor Interrupted: {}'.format(str(e)))


if __name__ == '__main__':
  parser = ap(description='classical website monitoring tool')
  parser.add_argument('url', help='url of the website to be monitored')

  parser.add_argument('--title', type=str, action='store',
                      help='title of the website')
  parser.add_argument('--interval', type=float, action='store', default=3600.,
                      help='monitoring interval in seconds')
  parser.add_argument('--hook', action='store', default=None,
                      help='the path to a hook command')
  parser.add_argument('--debug', action='store_const', const='DEBUG',
                      help='enabling debug outputs')

  args = parser.parse_args()

  options = {
    'url': args.url,
Beispiel #37
0
                    else:
                        tag = str(l)+"_snippet"                # sentence index tag                          
                    if cs:
                        yield LabeledSentence(cs, [tag])
                    else:
                        #sys.stderr.write("Empty string at line %s.\n" % l)
                        yield None
                    
        else:
            for fname in os.listdir(self.dirname):
                for line in open(os.path.join(self.dirname, fname)):
                    #yield clean_Ustring_fromU(line)
                    yield self.get_string[self.dirty](line)

if __name__ == "__main__":
    parser = ap(description='Trains and saves a word2vec model into a file for mmap\'ing. Tokenization is performed un utf-8 an for Python 2.7. Non-latin characters are replaced by spaces. The model is saved into a given directory. All options are needed.')    
    parser.add_argument('-i', type=str, dest = 'indir_file_name', help='Specifies the directory containing files to be processed. No sub-directories are allowed. In the case doc2vec is used, a file name must be specified. This file must contain a a sentence/document by line.')
    parser.add_argument('-o', type=str, dest = 'outfile', help='Specifies the file where to be stored the model.')
    parser.add_argument('-t', type=int, dest = 'threads', help='Specifies the number of threads the training will be divided.')
    parser.add_argument('-H', type=int, dest = 'hidden', help='Specifies the number of hidden units the model going to have.')
    parser.add_argument('-m', type=int, dest = 'minc', help='Specifies the minimum frequency a word should have in the corpus to be considered.')
    parser.add_argument('-d', default=False, action="store_true", dest = 'd2v', help='Toggles the doc2vec model, insted of the w2v one.')
    parser.add_argument('-s', default=False, action="store_true", dest = 'single', help='Toggles the pair or single tags.')
    parser.add_argument('-c', default=False, action="store_true", dest = 'update', help='Toggles if you want loading a pretrained model and continue training it with new input files.')
    parser.add_argument('-D', default=False, action="store_true", dest = 'dirty', help='Toggles if you do not want to process clean strings (i.e. raw file, including any symbol).')
    parser.add_argument('-w', type=int, dest = 'window', default=8, help='Specifies the number of words in the cooccurrence window.')
    args = parser.parse_args()

    if args.d2v:
        if not args.update:
            sys.stderr.write("\n>> [%s] Articles generator unpacking... %s\n" % (strftime("%Y-%m-%d %H:%M:%S", localtime()), args.outfile))
Beispiel #38
0
  line = line.replace(ur'ξ', u'''${\\xi}$''')
  line = line.replace(ur'ο', u'''${o}$''')
  line = line.replace(ur'π', u'''${\\pi}$''')
  line = line.replace(ur'ρ', u'''${\\rho}$''')
  line = line.replace(ur'σ', u'''${\\sigma}$''')
  line = line.replace(ur'τ', u'''${\\tau}$''')
  line = line.replace(ur'υ', u'''${\\upsilon}$''')
  line = line.replace(ur'φ', u'''${\\phi}$''')
  line = line.replace(ur'χ', u'''${\\chi}$''')
  line = line.replace(ur'ψ', u'''${\\psi}$''')
  line = line.replace(ur'ω', u'''${\\omega}$''')
  return line


if __name__ == '__main__':
  parser = ap(description='Convert Zotero .bib file.')
  parser.add_argument(
    'input_bib', metavar='src', type=str,
    help='source .bib file to be converted.')
  parser.add_argument(
    'output_bib', metavar='output', type=str,
    help='output .bib file for bibtex.')


  args = parser.parse_args()

  inside_elem = 0
  with codecs.open(args.input_bib, 'r', 'utf-8') as fin:
    with codecs.open(args.output_bib, 'w', 'utf-8') as fout:
      writeln = ur''
      for line in fin:
Beispiel #39
0
from argparse import ArgumentParser as ap
from os import system as cli
from Utility.Utility import chgdir

chgdir()
desc = "Main Python file to use execute commands :- New Registation of Carely User\
                ,Booking Appointments, and View Records. "

parser = ap(description=desc)
parser.add_argument("-i",
                    "--id",
                    action="store_true",
                    help="Input of User Id for further function use")
# Here constant is stored in case no argument is passed
parser.add_argument("-r",
                    "--registration",
                    action="store_true",
                    help="To register new Carely User.")
parser.add_argument("-b",
                    "--booking",
                    action="store_true",
                    help="To Book Appointment")
parser.add_argument(
    "-v",
    "--view",
    const=True,
    nargs="?",
    help="to view records of Booking, Caretaker,Elderly,etc.",
)
arg = parser.parse_args()
print(arg)
Beispiel #40
0
from sklearn.decomposition import TruncatedSVD
from sklearn import preprocessing
from argparse import ArgumentParser as ap
from numpy import loadtxt, savetxt
from numpy import array
parser = ap()
parser.add_argument("-x", help="Input file name (vectors)", metavar="input_file", required=True)
parser.add_argument("-n", help="N desired output components", metavar="n_components", required=True)
parser.add_argument("-s", help="Toggle save computed matrices.", default=False, action='store_true')
args = parser.parse_args()

fout = args.x+".svd"
foutN = args.x+".norm"
X = loadtxt(args.x)
#print "Mean before rescaling: %s" % (X.mean(axis=0))
#print "Var before rescaling : %s" % (X.std(axis=0))
X = preprocessing.scale(X)

print "Origin shape:", X.shape

if args.s:
    savetxt(foutN, X)
#print "Mean after: %s" % (X.mean(axis=0))
#print "Var afeter: %s" % (X.std(axis=0))
svd = TruncatedSVD(n_components=int(args.n), random_state=42)
X_p = svd.fit_transform(X)
print "Final shape:",X_p.shape

print "Var_ratio: %f percent" % (svd.explained_variance_ratio_.sum()*100)
print "Variance : %s" % (svd.explained_variance_)
Beispiel #41
0
                    if cs:
                        yield LabeledSentence(cs, [tag])
                    else:
                        #sys.stderr.write("Empty string at line %s.\n" % l)
                        yield None

        else:
            for fname in os.listdir(self.dirname):
                for line in open(os.path.join(self.dirname, fname)):
                    #yield clean_Ustring_fromU(line)
                    yield self.get_string[self.dirty](line)


if __name__ == "__main__":
    parser = ap(
        description=
        'Trains and saves a word2vec model into a file for mmap\'ing. Tokenization is performed un utf-8 an for Python 2.7. Non-latin characters are replaced by spaces. The model is saved into a given directory. All options are needed.'
    )
    parser.add_argument(
        '-i',
        type=str,
        dest='indir_file_name',
        help=
        'Specifies the directory containing files to be processed. No sub-directories are allowed. In the case doc2vec is used, a file name must be specified. This file must contain a a sentence/document by line.'
    )
    parser.add_argument(
        '-o',
        type=str,
        dest='outfile',
        help='Specifies the file where to be stored the model.')
    parser.add_argument(
        '-t',
Beispiel #42
0
#!/Users/ding/miniconda3/bin/python

from argparse import ArgumentParser as ap

from mcmc_funs import fit_BAO

if __name__ == '__main__': 
    parser = ap(description='Use mcmc routine to get the BAO peak stretching parameter alpha'\
                           +', damping parameter A, amplitude parameter B.')
    parser.add_argument("--kmin", help = 'kmin fit boundary.', required=True)
    parser.add_argument("--kmax", help = 'kmax fit boundary.', required=True)
    parser.add_argument("--params_str", help = 'Set fitting parameters. 1: free; 0: fixed.', required=True)
    parser.add_argument("--Pk_type", help = "The type of P(k) to be fitted. Pwig: wiggled P(k)"\
                                            +"with BAO; (Pwnw: Pwig-Pnow? Maybe it's not necessary.", required=True)
    args = parser.parse_args()
    fit_BAO(args)