Example #1
0
File: main.py Project: mion/def
def main_repl(engine):
	"""
	Simple REPL-like search.
	"""

	repl = REPL(lambda s: display_results(engine.search(s)))
	repl.start()
Example #2
0
def run(code, out=None):

    if out is None:
        out = sys.stdout

    interp = Interpreter()
    repl = REPL(interp)
    errors = 0
    for cmd, expect in extract(code):

        if not clean(cmd):
            print >> out
            continue

        print >> out, yellow % '> %s' % cmd

        if clean(cmd) == '*resume*':
            repl.cmdloop()
            continue

        exception = False
        sys.stdout = x = StringIO()
        try:
            repl.onecmd(cmd)
        except:
            exception = True
            print >> out, red % traceback.format_exc()
        finally:
            sys.stdout = sys.__stdout__

        got = clean(x.getvalue())
        expect = clean(expect)

        if expect == '*ignore*' and not exception:
            continue

        if expect != got or exception:
            print >> out, green % expect
            print >> out, red % got
            print >> out, bold % yellow % '=== diff ======'
            print >> out, diff(expect, got).strip()
            print >> out, bold % yellow % '==============='
            errors += 1

        else:
            print >> out
            print >> out, got

        print >> out

    if not errors:
        print >> out, green % 'PASS!'
        return 0
    else:
        print >> out, yellow % '>>>', red % '%s errors' % errors
        return 1
Example #3
0
def main():

    # Grab file_path argument from initial run
    file_path = sys.argv[1]

    #Instatiate repl that interacts with the user
    repl = REPL()
    repl.greet()

    # Instantiate ip populator that generates all the ips
    ip_populator = IpPopulator(file_path=file_path)

    # Save file to json if it doesnt already exist
    json_file_path = file_path.replace("txt", "json")
    if path.exists(json_file_path) is False:
        exporter = Exporter()
        exporter.export_as_json(
            file_path=json_file_path,
            modeled_ips_dict=ip_populator.dict_of_ip_objects)

    # Set queryable_options for repl
    repl.queryable_options = ip_populator.list_of_ip_geo_attributes
    repl.ip_populator = ip_populator

    # Get into query mode
    response = repl.intro()
    repl.handle_response(response)

    #iterate over the subsection of ip addresses for testing purposes

    # write json file of ips

    import pdb
    pdb.set_trace()
Example #4
0
def run(argv):
    if len(argv) < 2:
        sys.stderr.write(
            color('usage: %s node_id\n' % argv[0], 'red', bold=True))
        return 1

    node_id = argv[1]

    config = read_config()
    if node_id not in config['nodes']:
        sys.stderr.write('%s\ncheck config file\n' %
                         color('invalid node id', 'red', bold=True))
        return 2

    node_config = config['nodes'][node_id]
    node = AppNode(config, node_id)

    request_queue = Queue()
    network_process = Process(target=node.start, args=(request_queue, ))
    network_process.start()

    # don't let this thread touch node ever again
    # it's running in a separate process
    del node

    repl = REPL(prompt='dht>> ', command_queue=request_queue)
    repl.add_commands_from_module(repl_task)
    repl.add_commands_from_module(social_repl_task)
    repl.loop()

    request_queue.put(repl_task.LeaveTask())
    network_process.join()
    sys.stdout.write('bye\n')
    return 0
Example #5
0
def main():
	from repl import (
		REPL, EUDCommand, argEncNumber, argEncUnit, RegisterCommand
	)
	if EUDInfLoop()():
		# Turbo
		DoActions(SetDeaths(203151, SetTo, 1, 0))
		REPL(superuser=P1).execute() # The position of this function does not matter


		# SEE EFFECT
		UNIT = EUDVariable(initval = EncodeUnit("Terran Marine"))
		COUNT = EUDVariable(initval = 1)
		DoActions([
			CreateUnit(COUNT, UNIT, "Anywhere", P1),
			KillUnit(UNIT, P1)
		])

		# Make function that modifies variables - UNIT and CNT
		@EUDCommand([argEncUnit, argEncNumber])
		def SeeEffect(u, n):
			UNIT << u
			COUNT << n

		# Register command for REPL
		RegisterCommand("effect", SeeEffect)

		# run map trigger and end trigger end trigger loop
		RunTrigTrigger()
		EUDDoEvents()
	EUDEndInfLoop()
Example #6
0
def test():
    PORT = '/dev/tty.usbmodem1412'
    BAUD = 115200

    def get_serial():
        s = serial.Serial(PORT)
        s.baudrate = BAUD
        s.parity = serial.PARITY_NONE
        s.databits = serial.EIGHTBITS
        s.stopbits = serial.STOPBITS_ONE
        s.timeout = 0  # non blocking mode

        s.close()
        s.port = PORT
        s.open()
        return s

    s = get_serial()

    repl = REPL(s)
    repl.to_raw()

    repl.send_command("print('hello')")
    print(repl.wait_response())

    repl.send_command("a=1")
    repl.wait_response()

    repl.send_command("print(a)")
    print(repl.wait_response())

    # FINISHED

    s.close()
Example #7
0
def run(argv):
  if len(argv) < 2:
    sys.stderr.write(color('usage: %s node_id\n' % argv[0], 'red', bold=True))
    return 1
  
  node_id = argv[1]

  config = read_config()
  if node_id not in config['nodes']:
    sys.stderr.write('%s\ncheck config file\n' % color('invalid node id', 'red', bold=True))
    return 2

  node_config = config['nodes'][node_id]
  node = AppNode(config, node_id)

  request_queue = Queue()
  network_process = Process(target=node.start, args=(request_queue,))
  network_process.start()

  # don't let this thread touch node ever again
  # it's running in a separate process
  del node
 
  repl = REPL(prompt='dht>> ', command_queue=request_queue)
  repl.add_commands_from_module(repl_task)
  repl.add_commands_from_module(social_repl_task)
  repl.loop()

  request_queue.put(repl_task.LeaveTask())
  network_process.join()
  sys.stdout.write('bye\n')
  return 0
Example #8
0
def rdf_repl(serializer='nt',
             out=None,
             optpaths=[],
             extensions=[],
             debug_lvl=1):

    print("Building parser with yacc...")
    print("Parser build success...")
    print("Lexer build success... Enjoy your RDF...")
    print("#" * 40)

    repl = REPL(serializer=serializer,
                out=out,
                optpaths=optpaths,
                optextensions=extensions,
                debug_lvl=debug_lvl)

    repl.start()
Example #9
0
def main():
	from repl import REPL

	if EUDInfLoop()():
		# Turbo
		DoActions(SetDeaths(203151, SetTo, 1, 0))
		REPL().execute()

		RunTrigTrigger()
		EUDDoEvents()
	EUDEndInfLoop()
Example #10
0
def beforeTriggerExec():
	# loading settings
	pid = 0 # default as P1
	if 'superuser' in settings:
		su = playerMap.get(settings['superuser'], settings['superuser'])
		pid = EncodePlayer(su)

	if pid not in range(7):
		raise RuntimeError('Superuser in REPL should be one of P1~P8')

	from repl import REPL
	REPL(superuser = pid).execute()
Example #11
0
def run(code, out=None):

    if out is None:
        out = sys.stdout

    interp = Interpreter()
    repl = REPL(interp)
    errors = 0
    for cmd, expect in extract(code):

        if not clean(cmd):
            print >> out
            continue

        print >> out, yellow % '> %s' % cmd

        if clean(cmd) == '*resume*':
            repl.cmdloop()
            continue

        exception = False
        sys.stdout = x = StringIO()
        try:
            repl.onecmd(cmd)
        except:
            exception = True
            print >> out, red % traceback.format_exc()
        finally:
            sys.stdout = sys.__stdout__

        got = clean(x.getvalue())
        expect = clean(expect)

        if expect == '*ignore*' and not exception:
            continue

        if expect != got or exception:
            print >> out, green % expect
            print >> out, red % got
            print >> out, bold % yellow % '=== diff ======'
            print >> out, diff(expect, got).strip()
            print >> out, bold % yellow % '==============='
            errors += 1

        else:
            print >> out
            print >> out, got

        print >> out

    if not errors:
        print >> out, green % 'PASS!'
        return 0
    else:
        print >> out, yellow % '>>>', red % '%s errors' % errors
        return 1
Example #12
0
    def __init__(self):
        """
		Constructor: Inicializa propiedades de instancia y ciclo REPL.
		"""
        self.comandos = {
            "agendar": self.agendar,
            "vacunar": self.vacunar,
            "eliminar": self.eliminar,
            "listar": self.listar,
            "buscar": self.buscar,
            #"ayuda": self.ayuda,
            "salir": self.salir
        }
        archivo = "registro"
        #introduccion = strip(__doc__)
        self.registro = shelve.open(archivo, writeback=False)
        REPL(self.comandos).ciclo()
Example #13
0
def main():
    parser = argparse.ArgumentParser(description='Todoo Description...')
    parser.add_argument('--use', help='Choose a list to use')

    # Parse the arguments for initial load
    args = parser.parse_args()

    # Print the banner
    REPL.banner()

    # Establish the main REPL object
    repl = REPL(args.use)

    # Register our completer function
    readline.set_completer(SimpleCompleter(repl.get_options()).complete)

    # Use the tab key for completion
    readline.parse_and_bind('tab: complete')

    # Start the event loop
    repl.start()
Example #14
0
"""The entry point to the interpreter."""
import sys

if len(sys.argv) > 1:
    import core

    core.proc_load(core.GlobalScope(), sys.argv[1])
else:
    from repl import REPL
    REPL().start()
Example #15
0
    logger.debug('Conectando como cliente a la dirección "%s:%d"', *conn)
    try:
        socket.connect(conn)  # Conectar como cliente.
    except OSError:
        logger.critical('Esta dirección no tiene servidor.')
        pause()
        sys.exit(1)

# Crear el protocolo.
logger.info('Creando el manejador para el protocolo NTP')
if server: t = Transfer(c)
else: t = Transfer(socket)

# Crear e iniciar el REPL.
logger.info('Creando REPL')
repl = REPL(t, CMDS)
if nm:
    logger.debug('Estableciendo apodo del REPL a "%s"', nm)
    repl.nickname = nm

# Iniciar el REPL, y manejar los posibles errores.
logger.info('Iniciando bucle principal del REPL')
try:
    repl.main_loop()
except ConnectionBrokenError:
    logger.info('Conexión finalizada')
    print('Conexión finalizada.')
    pause()
except ConnectionAbortedError:
    logger.error('Se ha anulado la conexión')
    pause()
Example #16
0
File: main.py Project: nwf/dyna
def main():
    parser = argparse.ArgumentParser(description="The dyna interpreter!")

    parser.add_argument("--version", action="store_true", help="Print version information.")
    parser.add_argument("source", nargs="*", type=path, help="Path to Dyna source file.")
    parser.add_argument("-i", dest="interactive", action="store_true", help="Fire-up REPL after runing solver..")
    parser.add_argument("-o", "--output", dest="output", type=argparse.FileType("wb"), help="Write solution to file.")
    parser.add_argument("--post-process", nargs="*", help="run post-processor.")
    parser.add_argument("--load", nargs="*", help="run loaders.")
    parser.add_argument("--debug", action="store_true", help="Debug planner, normalizer and parser.")

    args = parser.parse_args()

    if args.version:
        try:
            print (dynahome / "dist/VERSION").text()  # XREF:VERSION
        except IOError:
            print "failed to obtain version info."
        exit(0)

    interp = Interpreter()

    crash_handler()

    if args.source:

        if len(args.source) > 1:
            # concatenate files
            with file(interp.compiler.tmp / "tmp.dyna", "wb") as g:
                for f in args.source:
                    if not f.exists():
                        print "File `%s` does not exist." % f
                        return
                    with file(f) as f:
                        g.write("\n")
                        g.write("%" * 80)
                        g.write("\n")
                        g.write("%% ")
                        g.write(f.name)
                        g.write("\n")
                        g.write(f.read())
            args.source = g.name
        else:
            [args.source] = args.source

        if not args.source.exists():
            print "File `%s` does not exist." % args.source
            return

        if args.debug:
            import debug

            debug.main(args.source, browser=True)
            exit(1)

        try:
            plan = interp.dynac(args.source)
        except DynaCompilerError as e:
            print e
            exit(1)

        interp.load_plan(plan)
        interp.run_agenda()

    if args.load:
        for cmd in args.load:
            load.run(interp, cmd)

    if args.post_process:
        for cmd in args.post_process:
            post.run(interp, cmd)

    if args.load or args.post_process or args.source:
        interp.dump_charts(args.output)  # should be a post-processor

    if args.interactive or not args.source:
        repl = REPL(interp)

        def repl_crash():
            # all files the interpreter generated
            with file(dotdynadir / "crash-repl.log", "wb") as f:
                for line in repl.lines:
                    print >> f, line

        crash_handler.hooks.append(repl_crash)

        repl.cmdloop()
Example #17
0
 def __init__(self):
     self.screen = ScreenPainter()
     self.game = Game(screen=self.screen, initial_state=[])
     self.repl = REPL(screen=self.screen)
     self.parser = GameParser(self)
Example #18
0
class Main(object):
    """
    This class contains the main application logic. Entry point for the REPL
    is run_repl. The rest of the methods serve for dispatching the game's
    config/control language elements to the various application components.
    """
    def __init__(self):
        self.screen = ScreenPainter()
        self.game = Game(screen=self.screen, initial_state=[])
        self.repl = REPL(screen=self.screen)
        self.parser = GameParser(self)

    def run_repl(self):
        self.screen.clear()
        while True:
            try:
                text = self.repl.prompt()
                self.parser.parse(text)
            except GameOver:
                break
            except EOFError:
                break
        print("Goodbye!")

    def run(self, *args):
        if args:
            self.game = Game.from_file(args[0],
                                       screen=self.screen,
                                       topology=self.topology)
        # self.screen.clear()
        # os.system("setterm -cursor off")
        try:
            while True:
                self.screen.draw_state(self.game)
                time.sleep(.1)
                self.game.next()
        except KeyboardInterrupt:
            pass
            # self.screen.clear()
            # os.system("setterm -cursor on")

    def quit(self):
        print("Goodbye!")
        raise GameOver()

    exit = quit

    @property
    def topology(self):
        return self.game.topology

    @topology.setter
    def topology(self, value):
        self.game.topology = value.strip("'")

    @property
    def width(self):
        return self.screen.width

    @width.setter
    def width(self, value):
        self.screen.width = value
        self.game.width = value

    @property
    def height(self):
        return self.screen.height

    @height.setter
    def height(self, value):
        self.screen.height = value
        self.game.height = value

    @property
    def state(self):
        return self.game.living_cells

    @state.setter
    def state(self, state):
        self.game.living_cells = state

    def random_state(self):
        initial_state = set(
            random.sample(
                list(itertools.product(range(self.width), range(self.height))),
                int(self.height * self.width * proportion)))
        return initial_state

    def block(self, dim):
        initial_state = {(p, q) for p in range(dim) for q in range(dim)}
        return initial_state

    def clear(self):
        self.screen.clear()
Example #19
0
import sys

from repl import REPL

ascii_art = """
 /$$$$$$$                       /$$$$$$          /$$                                     
| $$__  $$                     /$$__  $$        | $$                                     
| $$  \ $$/$$   /$$           | $$  \__/ /$$$$$$| $$$$$$$  /$$$$$$ /$$$$$$/$$$$  /$$$$$$ 
| $$$$$$$| $$  | $$  /$$$$$$  |  $$$$$$ /$$_____| $$__  $$/$$__  $| $$_  $$_  $$/$$__  $$
| $$____/| $$  | $$ |______/   \____  $| $$     | $$  \ $| $$$$$$$| $$ \ $$ \ $| $$$$$$$$
| $$     | $$  | $$            /$$  \ $| $$     | $$  | $| $$_____| $$ | $$ | $| $$_____/
| $$     |  $$$$$$$           |  $$$$$$|  $$$$$$| $$  | $|  $$$$$$| $$ | $$ | $|  $$$$$$$
|__/      \____  $$            \______/ \_______|__/  |__/\_______|__/ |__/ |__/\_______/
          /$$  | $$                                                                        
         |  $$$$$$/                                                                        
          \______/                                                                         """
print(ascii_art)
quote = """
"The continuation that obeys only obvious stack semantics, O grasshopper, is not the true continuation."

                                                                                         - Guy L Steele
                                                                  		              """
print(quote)
REPL().roll()
Example #20
0
File: spelling.py Project: mion/def
    model = collections.defaultdict(lambda: 1)
    for f in features:
        model[f] += 1
    return model

NWORDS = train(words(file('TEMP-E20131002.tsv')))

alphabet = 'abcdefghijklmnopqrstuvwxyz'

def edits1(word):
   splits     = [(word[:i], word[i:]) for i in range(len(word) + 1)]
   deletes    = [a + b[1:] for a, b in splits if b]
   transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
   replaces   = [a + c + b[1:] for a, b in splits for c in alphabet if b]
   inserts    = [a + c + b     for a, b in splits for c in alphabet]
   return set(deletes + transposes + replaces + inserts)

def known_edits2(word):
    return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)

def known(words): return set(w for w in words if w in NWORDS)

def correct(word):
    candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word]
    return sorted(candidates, key=NWORDS.get)[:5]

if __name__ == '__main__':
    from repl import REPL
    repl = REPL(lambda s: sys.stdout.write(str(correct(s))+'\n'))
    repl.start()
Example #21
0
                        path=pyjs.path,
                        compiler=translator.compiler,
                        translator_arguments=translator_arguments)
    linker()

    fp = open(linker.out_file_mod, 'r')
    txt = fp.read()
    fp.close()

    #PyV8.debugger.enabled = True

    # create a context with an explicit global
    g = Global(app_args, pyjs.path)
    ctxt = PyV8.JSContext(g)
    g.__context__ = ctxt
    # enter the context
    ctxt.enter()
    try:
        x = ctxt.eval(txt)
    except Exception, e:
        print JSRuntimeError(ctxt, e).full()

    if IS_REPL:
        from repl import REPL
        REPL(translator.compiler, linker, translator_arguments, g, ctxt)()


if __name__ == '__main__':
    main()

Example #22
0
def main():
    parser = argparse.ArgumentParser(description="The dyna interpreter!")

    parser.add_argument('--version',
                        action='store_true',
                        help='Print version information.')
    parser.add_argument('source',
                        nargs='*',
                        type=path,
                        help='Path to Dyna source file.')
    parser.add_argument('-i',
                        dest='interactive',
                        action='store_true',
                        help='Fire-up REPL after runing solver..')
    parser.add_argument('-o',
                        '--output',
                        dest='output',
                        type=argparse.FileType('wb'),
                        help='Write solution to file.')
    parser.add_argument('--post-process',
                        nargs='*',
                        help='run post-processor.')
    parser.add_argument('--load', nargs='*', help='run loaders.')
    parser.add_argument('--debug',
                        action='store_true',
                        help='Debug planner, normalizer and parser.')

    args = parser.parse_args()

    if args.version:
        try:
            print(dynahome / 'dist/VERSION').text()  # XREF:VERSION
        except IOError:
            print 'failed to obtain version info.'
        exit(0)

    interp = Interpreter()

    crash_handler()

    if args.source:

        if len(args.source) > 1:
            # concatenate files
            with file(interp.compiler.tmp / 'tmp.dyna', 'wb') as g:
                for f in args.source:
                    if not f.exists():
                        print 'File `%s` does not exist.' % f
                        return
                    with file(f) as f:
                        g.write('\n')
                        g.write('%' * 80)
                        g.write('\n')
                        g.write('%% ')
                        g.write(f.name)
                        g.write('\n')
                        g.write(f.read())
            args.source = g.name
        else:
            [args.source] = args.source

        if not args.source.exists():
            print 'File `%s` does not exist.' % args.source
            return

        if args.debug:
            import debug
            debug.main(args.source, browser=True)
            exit(1)

        try:
            plan = interp.dynac(args.source)
        except DynaCompilerError as e:
            print e
            exit(1)

        interp.load_plan(plan)
        interp.run_agenda()

    if args.load:
        for cmd in args.load:
            load.run(interp, cmd)

    if args.post_process:
        for cmd in args.post_process:
            post.run(interp, cmd)

    if args.load or args.post_process or args.source:
        interp.dump_charts(args.output)  # should be a post-processor

    if args.interactive or not args.source:
        repl = REPL(interp)

        def repl_crash():
            # all files the interpreter generated
            with file(dotdynadir / 'crash-repl.log', 'wb') as f:
                for line in repl.lines:
                    print >> f, line

        crash_handler.hooks.append(repl_crash)

        repl.cmdloop()