Esempio n. 1
0
def option():
    usage = "usage: %prog [options] arg"
    parser = OptionParser(usage)

    parser.add_option("-f",
                      "--file",
                      dest="filename",
                      help="file with download links")
    parser.add_option("-t",
                      "--thread",
                      dest="thread_number",
                      help="How much files download in one time",
                      default=2)
    parser.add_option("-k", "--key", dest="key", help="Key for premka")
    parser.add_option("-d",
                      "--no-delete",
                      action="store_false",
                      dest="no_delete",
                      help="Dont delete exists links on premka",
                      default=True)
    (options, args) = parser.parse_args()
    if not options.filename:
        parser.error('File name option is required')
    if not options.key:
        parser.error('Premka key is required')
    return options
Esempio n. 2
0
def main(argv=None):
    """Main entrypoint."""

    if argv is None:
        argv = sys.argv[1:]

    opts, parser = parse_args(argv)
    if not os.path.exists(opts.arch_json):
        parser.error(CONSTANTS_ERR_MSG)

    parsed_arch = arch.Arch.load_from_json(opts.arch_json)
    policy_compiler = compiler.PolicyCompiler(parsed_arch)
    if opts.use_kill_process:
        kill_action = bpf.KillProcess()
    else:
        kill_action = bpf.KillThread()
    override_default_action = None
    if opts.default_action:
        parser_state = parser.ParserState('<memory>')
        override_default_action = parser.PolicyParser(
            parsed_arch, kill_action=bpf.KillProcess()).parse_action(
                next(parser_state.tokenize([opts.default_action])))
    with opts.output as outf:
        outf.write(
            policy_compiler.compile_file(
                opts.policy.name,
                optimization_strategy=opts.optimization_strategy,
                kill_action=kill_action,
                include_depth_limit=opts.include_depth_limit,
                override_default_action=override_default_action).opcodes)
    return 0
Esempio n. 3
0
def main():
    """Main function for running the analyzer.
    Options will be parsed from the command line."""

    availableCommands = ["analyze", "list-forms", "stats"]

    args = parse_args(availableCommands)

    if not args.command in availableCommands:
        parser.error("Unknown command: %s" % (args.command))
    print("The following zip files will be handled:")
    print("\n".join(map(lambda s: "* %s" % (s), args.files)))

    count = 0
    zipHandler = ConsultationZipHandler()
    for zipFile in args.files:
        zipHandler.addZip(zipFile)

    print("")
    if args.command == "list-forms":
        print("List of consultation forms:")
        for file in zipHandler.listFiles():
            try:
                print("* %s" % (file))
            except UnicodeEncodeError:
                print("ERROR: Encoding error")
    elif args.command == "stats":
        print("Categories:")
        categories = zipHandler.getCategories()
        for category in categories:
            print("  %-55s: %5d" %
                  (category, zipHandler.getCountInCategory(category)))
        print("")
        print("File extensions:")
        for (ext, count) in zipHandler.getExtensionCount():
            print("  %-5s: %5d" % (ext, count))
        print("")
        print("Languages:")
        for (lang, count) in zipHandler.getLanguageCount():
            print("  %-2s: %5d" % (lang, count))
        print("")
        print("NUMBER OF FILES: %d" % (zipHandler.getCount()))
        print("")
        count += zipHandler.getCount()
    elif args.command == "analyze":
        zipHandler.analyze(numProcesses=args.processes,
                           randomize=args.randomize,
                           showProgress=args.progress,
                           printNames=args.printNames,
                           numberOfFiles=args.numberOfFiles,
                           queueSize=args.queueSize,
                           filePattern=args.filePattern,
                           skip=args.offset,
                           convert2odt=args.convert2odt,
                           wipeDatabase=args.wipeDatabase)
Esempio n. 4
0
def _parse_args():
	'''Parse the command-line arguments.'''
	parser = OptionParser(usage='%prog [Options] <device>', version='%prog 0.5')
	parser.add_option('-p', '--purge',
		dest='purge',
		help='purge the tracklog memory on the device',
		action='store_true',
		default=False)
	parser.add_option('-d', '--download',
		dest='download',
		help='download tracklogs from device',
		action='store_true',
		default=False)
	parser.add_option('-t', '--target-dir',
		dest='target_dir',
		help='target directory for downloaded tracklogs [default: %default]',
		default='%s/mainnav-tracklogs/' % os.environ.get('HOME', tempfile.gettempdir()))
	parser.add_option('-u', '--utc',
		dest='utc_offset',
		help='generate GPX time entry in UTC by declaring the offset (your timezone, e.g. -5 or +9.5)',
		type='float',
		default=False)
	parser.add_option('-r', '--raw',
		dest='raw',
		help='store the raw binary data in the target directory (must be combined with the download option)',
		action='store_true',
		default=False)
	parser.add_option('-m', '--memory',
		dest='memory',
		help='show the amount of memory in use',
		action='store_true',
		default=False)
	parser.add_option('-v', '--verbose',
		dest='verbose',
		help='be verbose',
		action='store_true',
		default=False)

	(options, args) = parser.parse_args()

	try:
		options.device = args[0]
	except IndexError:
		options.device = ''
	if not options.device:
		parser.error('please specify device path, for example \'/dev/ttyUSB0\'')
	if options.download and options.purge:
		parser.error('options -d and -p are mutually exclusive')
	if options.download and options.memory:
		parser.error('options -d and -m are mutually exclusive')
	if options.memory and options.purge:
		parser.error('options -m and -p are mutually exclusive')

	return options
Esempio n. 5
0
def run():
    global dictionary, code
    # console.start()
    code = textPad.get("1.0", tk.END + '-1c')
    # print code
    filename = 'test.vote'
    newfile = open(filename, 'w')
    newfile.write(code)
    newfile.close()
    dictionary = get_tokens(filename)

    if (dictionary):
        try:
            start()
        except ParserError as e:
            error(e, code)
            return
    interpret()
    print 'done'
Esempio n. 6
0
def parse_args():
    """parse_args parses sys.argv for wiki2centrality."""
    # Help Menu
    parser = optparse.OptionParser(usage='%prog [options] title')
    parser.add_option('-r', '--remove',
                      action='store_false', dest='remove', default=True,
                      help='remove mass deletions')
    parser.add_option('-c', '--centrality',
                      type='str', dest='ctype', default='closeness',
                      help='type of centrality: closeness, out_degree, betweenness',
                      metavar='CTYPE')

    (opts, args) = parser.parse_args()

    # Parser Errors
    if len(args) != 1:
        parser.error('incorrect number of arguments')

    wiki2centrality(args[0], remove=opts.remove, ctype=opts.ctype)
Esempio n. 7
0
def run():
    global dictionary, code
    # console.start()
    code = textPad.get("1.0",tk.END+'-1c')
    # print code
    filename = 'test.vote'
    newfile = open(filename,'w')
    newfile.write(code )
    newfile.close()
    dictionary = get_tokens(filename)

    if (dictionary):
        try:
            start()
        except ParserError as e:
            error(e,code)
            return
    interpret()
    print 'done'
Esempio n. 8
0
def main():
    args = sys.argv[1:]
    if len(args) == 0:
        error("invalid flags/options, use -h for help")
    flags = {'-' + x: None for x in ['o', 's', 'c']}
    args = sys.argv[1:]
    if '-h' in args:
        help()
    compiler = defaultCompiler
    outfile = "x.out"
    if '-s' in args:
        flags['-s'] = True
        args.remove('-s')
        outfile = "x.c"
    for i in range(len(args) - 1):
        if args[i] == '-o':
            outfile = args[i + 1]
            del args[i + 1]
            del args[i]
            break
    for i in range(len(args) - 1):
        if args[i] == '-c':
            compiler = args[i + 1]
            del args[i + 1]
            del args[i]
            break
    if len(args) != 1:
        error("Invalid flags/options, use -h for help")
    sourceName = args[0]
    with open(sourceName, 'r') as f:
        source = f.read()
    output = parse(source)
    if not flags['-s']:
        os.system(
            f"echo {output} | base64 -d | {compiler} -w -x c - -o {outfile}")
    else:
        os.system(f"echo {output} | base64 -d > {outfile}")
Esempio n. 9
0
def get_args():
    """Get command-line arguments"""

    parser = argparse.ArgumentParser(
        description='Heap Abuse',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('-n',
                        '--number',
                        help='Number of Insults',
                        metavar='insults',
                        type=int,
                        default=3)

    parser.add_argument('-a',
                        '--adjectives',
                        help='Number of adjectives',
                        metavar='adjectives',
                        type=int,
                        default=2)

    parser.add_argument('-s',
                        '--seed',
                        metavar='seed',
                        help='Random Seed',
                        type=int,
                        default=None)

    args = parser.parse_args()

    if args.adjectives < 1:
        parser.error('--adjectives "{}" must be > 0'.format(args.adjectives))

    if args.number < 1:
        parser.error('--number "{}" must be > 0'.format(args.number))

    return parser.parse_args()
Esempio n. 10
0
    from optparse import OptionParser
    parser = OptionParser(
            usage="""
python %prog action [-o outputfile] pl0sourcefile
Action is one of
    parseprint      - parse and print the parse tree,
    astprint        - parse, generate the AST then print the AST,
    interp          - parse, generate the AST then interpret the AST""")
    parser.add_option('-o', '--outputfile',
                      action='store',
                      dest='outputfile',
                      help='Output file.')
    (options, args) = parser.parse_args()

    if len(args) != 2:
        parser.error('wrong number of arguments.')

    action = args[0]
    infile = args[1]
    if action in ('parseprint', 'astprint', 'interp') and len(args) == 2:
        if action == 'x86asm' or action == 'c--':
            # check -o option
            if hasattr(options, 'outputfile') and options.outputfile:
                actions[action](infile, options.outputfile)
            else:
                parser.error('Missing -o option.')
        else:
            actions[action](infile)
            print '\n'
    else:
        parser.error('Invalid action.')
Esempio n. 11
0
def generateMIPSCode(code):
    global outputFile
    global RTC
    sys.stderr = open('dump', 'w')
    ST, TAC = z.parse(code)
    # sys.stderr.close()
    # TAC.printCode()
    # ST.printSymbolTableHistory()
    RTC = runTimeCode.RunTimeCode(ST, TAC)
    RTC.fixLabels()
    counter = 0
    for function in TAC.code:
        RTC.addFunction(function)

        if (function == 'main'):
            RTC.addLineToCode(['sub', '$sp', '$sp', '200'])
            RTC.addLineToCode(['la', '$fp', '200($sp)', ''])
            RTC.addLineToCode(['la', '$s5', '__myspace__', ''])
            RTC.addLineToCode(['lw', '$s7', '0($s5)', ''])
            RTC.addLineToCode([
                'la', '$v0',
                '-' + str(ST.getAttributeFromFunctionList(function, 'width')) +
                '($sp)', ''
            ])
            RTC.addLineToCode(['sw', '$v0', '0($s5)', ''])
            RTC.addLineToCode([
                'li', '$v0',
                ST.getAttributeFromFunctionList(function, 'width'), ''
            ])
            RTC.addLineToCode(['sub', '$sp', '$sp', '$v0'])

        else:
            RTC.addLineToCode(['sub', '$sp', '$sp', '72'])
            RTC.addLineToCode(['sw', '$ra', '0($sp)', ''])
            RTC.addLineToCode(['sw', '$fp', '4($sp)', ''])
            RTC.addLineToCode(['la', '$fp', '72($sp)', ''])
            RTC.addLineToCode([
                'li', '$v0',
                ST.getAttributeFromFunctionList(function, 'scopeLevel'), ''
            ])
            RTC.addLineToCode(['la', '$s5', '__myspace__', ''])
            RTC.addLineToCode(['add', '$v0', '$v0', '$v0'])
            RTC.addLineToCode(['add', '$v0', '$v0', '$v0'])
            RTC.addLineToCode(['add', '$s6', '$v0', '$s5'])
            RTC.addLineToCode(['lw', '$s7', '0($s6)', ''])
            RTC.addLineToCode(['sw', '$s7', '8($sp)', ''])
            RTC.addLineToCode([
                'la', '$v0',
                '-' + str(ST.getAttributeFromFunctionList(function, 'width')) +
                '($sp)', ''
            ])
            RTC.addLineToCode(['sw', '$v0', '0($s6)', ''])
            registerAction('sw')
            RTC.addLineToCode([
                'li', '$v0',
                ST.getAttributeFromFunctionList(function, 'width'), ''
            ])
            RTC.addLineToCode(['sub', '$sp', '$sp', '$v0'])

            # Copy the parameters
            numParam = ST.getAttributeFromFunctionList(function, 'numParam')
            if numParam > 4:
                parser.error("Too many parameters (max: 4)", None)
            for x in range(numParam):
                RTC.addLineToCode(
                    ['sw', '$a' + str(x),
                     str(4 * x) + '($sp)', ''])

        for line in TAC.code[function]:
            if line[3] == 'JUMPLABEL':
                counter = 0
                RTC.addLineToCode(['jal', RTC.getRegister(line[2]), '', ''])
                RTC.reloadParentRegisters(
                    ST.getAttributeFromFunctionList(function, 'scopeLevel'),
                    function)

            elif line[3] == 'JUMP_RETURN':
                RTC.addLineToCode(['b', function + 'end', '', ''])

            elif line[3] == 'PARAM':
                RTC.addLineToCode([
                    'move', '$a' + str(counter),
                    RTC.getRegister(line[0]), ''
                ])
                counter = counter + 1
                if counter == 5:
                    parser.error("Too many parameters (max: 4)", None)

            elif line[3] == '=':
                RTC.addLineToCode([
                    'move',
                    RTC.getRegister(line[0]),
                    RTC.getRegister(line[1]), ''
                ])

            elif line[3] == '=i':
                RTC.addLineToCode(
                    ['li', RTC.getRegister(line[0]), line[1], ''])

            elif line[3] == '=REF':
                RTC.addLineToCode(
                    ['la', RTC.getRegister(line[0]), line[1], ''])

            elif line[3] == '+':
                RTC.addLineToCode([
                    'add',
                    RTC.getRegister(line[0]),
                    RTC.getRegister(line[1]),
                    RTC.getRegister(line[2])
                ])

            elif line[3] == '-':
                RTC.addLineToCode([
                    'sub',
                    RTC.getRegister(line[0]),
                    RTC.getRegister(line[1]),
                    RTC.getRegister(line[2])
                ])

            elif line[3] == '*':
                RTC.addLineToCode([
                    'mult',
                    RTC.getRegister(line[1]),
                    RTC.getRegister(line[2]), ''
                ])
                RTC.addLineToCode(['mflo', RTC.getRegister(line[0]), '', ''])

            elif line[3] == '/':
                RTC.addLineToCode([
                    'div',
                    RTC.getRegister(line[1]),
                    RTC.getRegister(line[2]), ''
                ])
                RTC.addLineToCode(['mflo', RTC.getRegister(line[0]), '', ''])

            elif line[3] == '%':
                RTC.addLineToCode([
                    'div',
                    RTC.getRegister(line[1]),
                    RTC.getRegister(line[2]), ''
                ])
                RTC.addLineToCode(['mfhi', RTC.getRegister(line[0]), '', ''])

            elif line[3] == '<':
                RTC.addLineToCode([
                    'slt',
                    RTC.getRegister(line[0]),
                    RTC.getRegister(line[1]),
                    RTC.getRegister(line[2])
                ])

            elif line[3] == '>':
                RTC.addLineToCode([
                    'sgt',
                    RTC.getRegister(line[0]),
                    RTC.getRegister(line[1]),
                    RTC.getRegister(line[2])
                ])

            elif line[3] == '<=':
                RTC.addLineToCode([
                    'sle',
                    RTC.getRegister(line[0]),
                    RTC.getRegister(line[1]),
                    RTC.getRegister(line[2])
                ])

            elif line[3] == '>=':
                RTC.addLineToCode([
                    'sge',
                    RTC.getRegister(line[0]),
                    RTC.getRegister(line[1]),
                    RTC.getRegister(line[2])
                ])

            elif line[3] == '==':
                RTC.addLineToCode([
                    'seq',
                    RTC.getRegister(line[0]),
                    RTC.getRegister(line[1]),
                    RTC.getRegister(line[2])
                ])

            elif line[3] == '!=':
                RTC.addLineToCode([
                    'sne',
                    RTC.getRegister(line[0]),
                    RTC.getRegister(line[1]),
                    RTC.getRegister(line[2])
                ])

            elif line[3] == 'or':
                RTC.addLineToCode([
                    'or',
                    RTC.getRegister(line[0]),
                    RTC.getRegister(line[1]),
                    RTC.getRegister(line[2])
                ])

            elif line[3] == 'and':
                RTC.addLineToCode([
                    'and',
                    RTC.getRegister(line[0]),
                    RTC.getRegister(line[1]),
                    RTC.getRegister(line[2])
                ])

            elif line[3] == '>>':
                RTC.addLineToCode([
                    'srl',
                    RTC.getRegister(line[0]),
                    RTC.getRegister(line[1]),
                    RTC.getRegister(line[2])
                ])

            elif line[3] == '<<':
                RTC.addLineToCode([
                    'sll',
                    RTC.getRegister(line[0]),
                    RTC.getRegister(line[1]),
                    RTC.getRegister(line[2])
                ])

            elif line[3] == 'COND_GOTO':
                RTC.addLineToCode(
                    ['beq', RTC.getRegister(line[0]), line[1], line[2]])

            elif line[3] == 'GOTO':
                RTC.addLineToCode(['b', line[2], '', ''])

            elif line[3] == 'FUNCTION_RETURN':
                RTC.addLineToCode(
                    ['move', RTC.getRegister(line[0]), '$v0', ''])

            elif line[3] == 'RETURN':
                RTC.addLineToCode(
                    ['move', '$v0',
                     RTC.getRegister(line[0]), ''])
                RTC.addLineToCode(['b', function + 'end', '', ''])

            elif line[3] == 'HALT':
                RTC.addLineToCode(['jal', 'exit', '', ''])

            elif line[3] == 'PRINT' and line[0] == '':
                RTC.addLineToCode(['jal', 'print_newline', '', ''])

            elif line[3] == 'PRINT':
                RTC.addLineToCode(
                    ['move', '$a0',
                     RTC.getRegister(line[0]), ''])

                if line[2] == 'NUMBER':
                    RTC.addLineToCode(['jal', 'print_integer', '', ''])
                elif line[2] == 'STRING':
                    RTC.addLineToCode(['jal', 'print_string', '', ''])
                else:
                    RTC.addLineToCode(['jal', 'print_boolean', '', ''])
            else:
                RTC.addLineToCode(line)

        if function != 'main':
            RTC.addLineToCode(['LABEL', function + 'end', '', ''])
            RTC.addLineToCode([
                'addi', '$sp', '$sp',
                ST.getAttributeFromFunctionList(function, 'width')
            ])
            RTC.addLineToCode(['lw', '$ra', '0($sp)', ''])
            RTC.addLineToCode(['lw', '$fp', '4($sp)', ''])
            RTC.addLineToCode(['lw', '$a0', '8($sp)', ''])
            RTC.addLineToCode([
                'li', '$a1',
                ST.getAttributeFromFunctionList(function, 'scopeLevel'), ''
            ])
            RTC.addLineToCode(['la', '$s5', '__myspace__', ''])
            RTC.addLineToCode(['add', '$a1', '$a1', '$a1'])
            RTC.addLineToCode(['add', '$a1', '$a1', '$a1'])
            RTC.addLineToCode(['add', '$s6', '$a1', '$s5'])
            RTC.addLineToCode(['sw', '$a0', '0($s6)', ''])
            registerAction('lw')
            RTC.addLineToCode(['addi', '$sp', '$sp', '72'])
            RTC.addLineToCode(['jr', '$ra', '', ''])

    RTC.printCode(outputFile)
Esempio n. 12
0
parser.add_option("--biomart-db", dest="biomart_db", default=None, metavar="NAME", help="Biomart database name")

parser.add_option("--start", dest="start_file", default=None, metavar="NAME", help="SQL file to start with. Optional")

parser.add_option("-h", "--host", dest="db_host", default=None, metavar="HOST", help="host")
parser.add_option("-P", "--port", dest="db_port", default=None, metavar="PORT", help="port")
parser.add_option("-u", "--user", dest="db_user", default=None, metavar="NAME", help="user name")
parser.add_option("-p", "--passwd", dest="db_passwd", default=None, metavar="PASSWD", help="password")

(options, args) = parser.parse_args()

if options.help:
    parser.print_help()

if len(args) != 1:
    parser.error("Incorrect number of arguments")

if options.browser_db is None:
    parser.error("Missing browser database name option")

if options.biomart_db is None:
    parser.error("Missing biomart database name option")

files = sorted(glob.glob(os.path.join(args[0], "*.sql")))

start = 0

if options.start_file is not None:
    start_file = os.path.abspath(options.start_file)
    while start < len(files) and os.path.abspath(files[start]) != start_file:
        start += 1
Esempio n. 13
0
def generateMIPSCode(code):
	global outputFile
	global RTC
	sys.stderr = open('dump','w')
	ST, TAC = z.parse(code)
	# sys.stderr.close()
	# TAC.printCode()
	# ST.printSymbolTableHistory()
	RTC = runTimeCode.RunTimeCode(ST, TAC)
	RTC.fixLabels()
	counter = 0
	for function in TAC.code:
		RTC.addFunction(function)

		if (function == 'main'):
			RTC.addLineToCode(['sub', '$sp', '$sp', '200'])
			RTC.addLineToCode(['la', '$fp', '200($sp)', ''])
			RTC.addLineToCode(['la', '$s5', '__myspace__', ''])
			RTC.addLineToCode(['lw', '$s7', '0($s5)', ''])
			RTC.addLineToCode(['la', '$v0', '-' + str(ST.getAttributeFromFunctionList(function, 'width')) + '($sp)', ''])
			RTC.addLineToCode(['sw','$v0', '0($s5)', ''])
			RTC.addLineToCode(['li', '$v0', ST.getAttributeFromFunctionList(function, 'width'), ''])
			RTC.addLineToCode(['sub', '$sp', '$sp', '$v0'])

		else:
			RTC.addLineToCode(['sub', '$sp','$sp','72'])
			RTC.addLineToCode(['sw','$ra','0($sp)',''])
			RTC.addLineToCode(['sw','$fp','4($sp)',''])
			RTC.addLineToCode(['la','$fp','72($sp)',''])
			RTC.addLineToCode(['li','$v0',ST.getAttributeFromFunctionList(function, 'scopeLevel'),''])
			RTC.addLineToCode(['la', '$s5', '__myspace__', ''])
			RTC.addLineToCode(['add', '$v0', '$v0', '$v0'])
			RTC.addLineToCode(['add', '$v0', '$v0', '$v0'])
			RTC.addLineToCode(['add', '$s6', '$v0', '$s5'])
			RTC.addLineToCode(['lw','$s7','0($s6)',''])
			RTC.addLineToCode(['sw','$s7','8($sp)',''])
			RTC.addLineToCode(['la', '$v0', '-' + str(ST.getAttributeFromFunctionList(function, 'width'))+'($sp)' , ''])
			RTC.addLineToCode(['sw','$v0','0($s6)',''])
			registerAction('sw')
			RTC.addLineToCode(['li','$v0',ST.getAttributeFromFunctionList(function, 'width'),''])
			RTC.addLineToCode(['sub','$sp','$sp','$v0'])

			# Copy the parameters
			numParam = ST.getAttributeFromFunctionList(function, 'numParam')
			if numParam >4:
				parser.error("Too many parameters (max: 4)", None)
			for x in range(numParam):
				RTC.addLineToCode(['sw','$a' + str(x), str(4*x) + '($sp)', ''])

		for line in TAC.code[function]:
			if line[3] == 'JUMPLABEL':
				counter = 0 ;
				RTC.addLineToCode(['jal', RTC.getRegister(line[2]), '', ''])
				RTC.reloadParentRegisters(ST.getAttributeFromFunctionList(function, 'scopeLevel'), function)

			elif line[3] == 'JUMP_RETURN':
				RTC.addLineToCode(['b', function + 'end', '', ''])

			elif line[3] == 'PARAM':
				RTC.addLineToCode(['move', '$a'+str(counter), RTC.getRegister(line[0]),''])
				counter = counter +1 ;
				if counter == 5:
					parser.error("Too many parameters (max: 4)", None)

			elif line[3] == '=':
				RTC.addLineToCode(['move', RTC.getRegister(line[0]), RTC.getRegister(line[1]), ''])
				
			elif line[3] == '=i':
				RTC.addLineToCode(['li', RTC.getRegister(line[0]), line[1], ''])
				
			elif line[3] == '=REF':
				RTC.addLineToCode(['la', RTC.getRegister(line[0]), line[1], ''])
				
			elif line[3] == '+':
				RTC.addLineToCode(['add', RTC.getRegister(line[0]), RTC.getRegister(line[1]), RTC.getRegister(line[2])])
				
			elif line[3] == '-':
				RTC.addLineToCode(['sub', RTC.getRegister(line[0]), RTC.getRegister(line[1]), RTC.getRegister(line[2])])
				
			elif line[3] == '*':
				RTC.addLineToCode(['mult', RTC.getRegister(line[1]), RTC.getRegister(line[2]),''])
				RTC.addLineToCode(['mflo', RTC.getRegister(line[0]),'',''])
				
			elif line[3] == '/':
				RTC.addLineToCode(['div', RTC.getRegister(line[1]), RTC.getRegister(line[2]), ''])
				RTC.addLineToCode(['mflo', RTC.getRegister(line[0]), '', ''])
				
			elif line[3] == '%':
				RTC.addLineToCode(['div', RTC.getRegister(line[1]), RTC.getRegister(line[2]), ''])
				RTC.addLineToCode(['mfhi', RTC.getRegister(line[0]), '', ''])
				
			elif line[3] == '<':
				RTC.addLineToCode(['slt', RTC.getRegister(line[0]), RTC.getRegister(line[1]), RTC.getRegister(line[2])])
				
			elif line[3] == '>':
				RTC.addLineToCode(['sgt', RTC.getRegister(line[0]), RTC.getRegister(line[1]), RTC.getRegister(line[2])])
				
			elif line[3] == '<=':
				RTC.addLineToCode(['sle', RTC.getRegister(line[0]), RTC.getRegister(line[1]), RTC.getRegister(line[2])])
				
			elif line[3] == '>=':
				RTC.addLineToCode(['sge', RTC.getRegister(line[0]), RTC.getRegister(line[1]), RTC.getRegister(line[2])])
				
			elif line[3] == '==':
				RTC.addLineToCode(['seq', RTC.getRegister(line[0]), RTC.getRegister(line[1]), RTC.getRegister(line[2])])
				
			elif line[3] == '!=':
				RTC.addLineToCode(['sne', RTC.getRegister(line[0]), RTC.getRegister(line[1]), RTC.getRegister(line[2])])
							
			elif line[3] == 'or':
				RTC.addLineToCode(['or', RTC.getRegister(line[0]), RTC.getRegister(line[1]), RTC.getRegister(line[2])])
			
			elif line[3] == 'and':
				RTC.addLineToCode(['and', RTC.getRegister(line[0]), RTC.getRegister(line[1]), RTC.getRegister(line[2])])
			
			elif line[3] == '>>':
				RTC.addLineToCode(['srl', RTC.getRegister(line[0]), RTC.getRegister(line[1]), RTC.getRegister(line[2])])

			elif line[3] == '<<':
				RTC.addLineToCode(['sll', RTC.getRegister(line[0]), RTC.getRegister(line[1]), RTC.getRegister(line[2])])

			elif line[3] == 'COND_GOTO':
				RTC.addLineToCode(['beq', RTC.getRegister(line[0]), line[1], line[2]])

			elif line[3] == 'GOTO':
				RTC.addLineToCode(['b', line[2], '', ''])

			elif line[3] == 'FUNCTION_RETURN':
				RTC.addLineToCode(['move', RTC.getRegister(line[0]), '$v0', ''])

			elif line[3] == 'RETURN':
				RTC.addLineToCode(['move', '$v0', RTC.getRegister(line[0]), ''])
				RTC.addLineToCode(['b', function + 'end', '', ''])
 
			elif line[3] == 'HALT':
				RTC.addLineToCode(['jal', 'exit', '', ''])

			elif line[3] == 'PRINT' and line[0] == '':
				RTC.addLineToCode(['jal', 'print_newline', '', ''])

			elif line[3] == 'PRINT':
				RTC.addLineToCode(['move', '$a0', RTC.getRegister(line[0]), ''])

				if line[2] == 'NUMBER':
					RTC.addLineToCode(['jal', 'print_integer', '', ''])
				elif line[2] == 'STRING':
					RTC.addLineToCode(['jal', 'print_string', '', ''])
				else:
					RTC.addLineToCode(['jal', 'print_boolean', '', ''])
			else:
				RTC.addLineToCode(line)

		if function != 'main':
			RTC.addLineToCode(['LABEL', function + 'end', '', ''])
			RTC.addLineToCode(['addi','$sp','$sp',ST.getAttributeFromFunctionList(function,'width')])
			RTC.addLineToCode(['lw','$ra','0($sp)',''])
			RTC.addLineToCode(['lw','$fp','4($sp)',''])
			RTC.addLineToCode(['lw','$a0','8($sp)',''])
			RTC.addLineToCode(['li','$a1',ST.getAttributeFromFunctionList(function, 'scopeLevel'),''])
			RTC.addLineToCode(['la', '$s5', '__myspace__', ''])
			RTC.addLineToCode(['add', '$a1', '$a1', '$a1'])
			RTC.addLineToCode(['add', '$a1', '$a1', '$a1'])
			RTC.addLineToCode(['add', '$s6', '$a1', '$s5'])
			RTC.addLineToCode(['sw','$a0','0($s6)',''])
			registerAction('lw')
			RTC.addLineToCode(['addi','$sp','$sp','72'])
			RTC.addLineToCode(['jr','$ra','',''])

	RTC.printCode(outputFile)
Esempio n. 14
0
)

compliestring = Template("pyuic4 -o ui_$py.py $ui")

if __name__ == "__main__":
    """
        Helper to create the form folder structure with the correct layer and files
    """

    parser = OptionParser()
    parser.add_option("-f", "--folder", dest="foldername", help="Overwrite folder name for form folder", metavar="NAME")

    (options, args) = parser.parse_args()

    if not len(args) == 3:
        parser.error("incorrect number of arguments")

    filename = args[0]
    layer = args[1]
    name = args[2]
    if not filename[-3:] == ".ui":
        parser.error("incorrect number of arguments")

    newfilename = filename.replace(" ", "")
    print filename
    foldername = "form%s" % (options.foldername or newfilename[:-3])
    print foldername
    if not os.path.exists(foldername):
        os.makedirs(foldername)

    os.rename(filename, os.path.join(foldername, newfilename))
Esempio n. 15
0
    import platform
    hostname = platform.uname()[1]

    url = 'http://127.0.0.1/server-status?auto'
    data = fetchURL(url)
    try:
        (tempfiled, tempfilepath) = mkstemp()
        tempfile = open(tempfilepath, 'wb')
    except:
        print "Error creating tmp file"

    try:
        try:
            data = parse(data=data)
        except csv.Error:
            parser.error("Error parsing returned data")

        try:
            for key, val in data.items():
                if isinstance(val, str):
                    if val.startswith("."):
                        val = "0" + val
                tempfile.write("%s apache_%s %s\n" % (hostname, key, val))
            tempfile.close()
        except "bogus":
            parser.error("Error creating the file to send")

        try:
            zabbix_sender = "/usr/bin/zabbix_sender"
            zabbix_conf = "/etc/zabbix/zabbix_agentd.conf"
            zabbix_send_file = tempfilepath
Esempio n. 16
0
def main():
    """Main function for running the analyzer.
    Options will be parsed from the command line."""

    availableCommands = ["analyze", "analyze_text", "list-forms", "stats"]

    args = parse_args(availableCommands)

    if not args.command in availableCommands:
        parser.error("Unknown command: %s" % (args.command))
    print("The following zip files will be handled:")
    print("\n".join(map(lambda s: "* %s" % (s), args.files)))

    count = 0
    zipHandler = ConsultationZipHandler()
    for zipFile in args.files:
        zipHandler.addZip(zipFile)

    print("")
    if args.command == "list-forms":
        print("List of consultation forms:")
        for file in zipHandler.listFiles():
            try:
                print("* %s" % (file))
            except UnicodeEncodeError:
                print("ERROR: Encoding error")
    elif args.command == "stats":
        print("Categories:")
        categories = zipHandler.getCategories()
        for category in categories:
            print("  %-55s: %5d" % (category, zipHandler.getCountInCategory(category)))
        print("")
        print("File extensions:")
        for (ext, count) in zipHandler.getExtensionCount():
            print("  %-5s: %5d" % (ext, count))
        print("")
        print("Languages:")
        for (lang, count) in zipHandler.getLanguageCount():
            print("  %-2s: %5d" % (lang, count))
        print("")
        print("NUMBER OF FILES: %d" % (zipHandler.getCount()))
        print("")
        count += zipHandler.getCount()
    elif args.command == "analyze":
        zipHandler.analyze(lambda q, z, f: typographicAnalyze(q, z, f, args.convert2odt),
                           typographicAnalyzeWorker,
                           numProcesses=args.processes,
                           randomize=args.randomize,
                           showProgress=args.progress,
                           printNames=args.printNames,
                           numberOfFiles=args.numberOfFiles,
                           queueSize=args.queueSize,
                           filePattern=args.filePattern,
                           skip=args.offset,
                           convert2odt=args.convert2odt,
                           wipeDatabase=args.wipeDatabase)
    elif args.command == "analyze_text":
        zipHandler.analyze(textBasedAnalyze,
                           textBasedAnalyzeWorker,
                           numProcesses=args.processes,
                           randomize=args.randomize,
                           showProgress=args.progress,
                           printNames=args.printNames,
                           numberOfFiles=args.numberOfFiles,
                           queueSize=args.queueSize,
                           filePattern=args.filePattern,
                           skip=args.offset,
                           convert2odt=args.convert2odt,
                           wipeDatabase=args.wipeDatabase)
Esempio n. 17
0
if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description=
        'Script to upload or delete Jeopardy games from Firebase DB by season')

    parser.add_argument('-s',
                        '--season',
                        type=int,
                        required=True,
                        help='jeopardy season to process')

    parser.add_argument('-d',
                        '--delete',
                        action='store_true',
                        help='set to true if you want to delete season')

    parser.add_argument('-u',
                        '--upload',
                        action='store_true',
                        help='set to true if you want to upload season')

    args = parser.parse_args()

    if not args.delete and not args.upload:
        parser.error(
            'At least one of upload or delete season action is required to specificity!'
        )

    run(args)