Пример #1
0
def init():
    global screen_width, screen_height
    config = parser.load(game_config)
    # Turn engine.cfg definitions into global variables.
    globals().update(config.todict())
    screen_width = int(screen_width)
    screen_height = int(screen_height)
    try:
        f = open(ika_config)
    except IOError:
        pass
    else:
        # Turn user.cfg definitions into global variables.
        lines = f.readlines()
        for line in lines:
            line = line.split()
            globals()[line[0]] = int(line[1])
        f.close()
    if 'xres' not in globals() or 'yres' not in globals():
        try:
            last_character = open(ika_config, 'rt').read()[-1]
        except IOError:
            last_character = '\n'
        f = open(ika_config, 'aU')
        if last_character != '\n':
            print >> f, '\n',
        if 'xres' not in globals():
            print >> f, 'xres', screen_width
        if 'yres' not in globals():
            print >> f, 'yres', screen_height
        f.close()
        import os
        os.spawnl(os.P_NOWAIT, 'ika.exe')
        ika.Exit()
Пример #2
0
    def load(self, filename='%s/default.save' % config.save_path):
        self.loading = True
        d = parser.load(filename)
        self.curmap = d['mannux-save'].get('map')
        self.player.hp = int(d['mannux-save'].get('hp'))
        self.player.maxhp = int(d['mannux-save'].get('maxhp'))
        self.player.mp = int(d['mannux-save'].get('mp'))
        self.player.maxmp = int(d['mannux-save'].get('maxmp'))
        self.flags = d['mannux-save']['flags'].todict()

        a = d['mannux-save'].get('amap1')


        print 'testing: '
        print d['mannux-save'].get('map')
        print d['mannux-save'].get('amap1')

        #print a


        #if 'amap1' in d['mannux-save']:
        #    print 'yes!'
        #    a = d['mannux-save']['amap1']
        #    b = ''
        #    for c in a:
        #        b+=str(c)
        #    print "Load test:"
        #
        #    test = eval(b)
        #    self.automap.amap = test
        #else:
        #    print 'wtf!'



        #b = d['mannux-save']['amap']

        #self.automap.amap = []
        #i=0
        #for y in range(50): #need to change so it's not just 50x50...
        #    for x in range(50):
                #self.automap.amap.append(a[i])

        #for i in a:
        #    ika.Log('i: '+str(i))
        #        i+=1


            #for i in d['mannux-save']['amap']:
            #    self.automap.amap.append(i)


        self.hud.resize()



        #print self.curmap
        self.map_switch(0, 0, self.curmap, fadeout=False)
        self.loading = False
Пример #3
0
 def LoadData(self):
     for key in ("locations", "enemies", "lore"):
         self.data[key] = {}
         self.order[key] = []
         f = parser.load("data/" + key + ".logs")
         for entry, data in f["metroid2-log"].todict().iteritems():
             entry = entry.replace("_", " ")
             self.order[key].append(entry)
             self.data[key][entry] = (0, data)
Пример #4
0
def load(filename) :
	global definitions, unsLexer, unsParser
	
	if not (unsLexer and unsParser) :
		unsLexer = lexer.load("unsugarer.lex")
		unsParser = parser.load("unsugarer.par")

	with open(filename, "r") as file :
		text = file.read()

	trees = unsParser.parse(unsLexer.lex(text))
	parsers = [process(tree) for tree in trees]

	for name, params, processor in [x for x in parsers if x] :
		definitions[name] = list(map(lambda x : x[1], params)), processor


	uns = Unsugarer(definitions)
	definitions = {}
	return uns
Пример #5
0
 def Load(self):
     """Load up all the save files in the save folder, minus the default.save."""
     self.files = []
     for name in ("save/file1.save", "save/file2.save", "save/file3.save", "save/file4.save"):
         try:
             f = parser.load(name)
         except IOError:
             self.files.append(None)
         else:
             energy = f["metroid2-save"]["equipment"]["energy"].todict()
             clock = f["metroid2-save"]["clock"].todict()
             self.files.append({"mode": f["metroid2-save"].get("mode"), "energy": int(energy["current"]), "max_energy": int(energy["max"]), "hours": int(clock["hours"]), "minutes": int(clock["minutes"]), "area": f["metroid2-save"].get("area_name"), "file": f})
             #Determine which suit graphic to use for cursor.
             obtained = f["metroid2-save"]["equipment"].todict()["obtained"]
             if "Aero Suit" in obtained:
                 self.files[-1]["suit"] = "aero"
             elif "Gravity Suit" in obtained:
                 self.files[-1]["suit"] = "gravity"
             elif "Varia Suit" in obtained:
                 self.files[-1]["suit"] = "varia"
             else:
                 self.files[-1]["suit"] = "power"
Пример #6
0
    def add_file(cls, path):
        content, words, links = load(path)

        if (not content and links) or ctx.collect_links:
            # Store links
            new_cnt = cls.store_links(links)
            if new_cnt > 1:
                log('%s links collected' % new_cnt, 'green')
            else:
                log('%s link collected' % new_cnt, 'green')
            return True

        if not content:
            return False

        doc = Document.get(path)
        if doc.distance is None:
            doc.distance = 0

        doc.dirty = True
        doc.content = content
        log(
            'Document %s added (distance: %s, score: %s)' %
            (path, doc.distance, doc.score), 'green')

        cls.store_links(links, doc)

        # Build neighbours
        neighbours = 0
        for word in words:
            kw = Keyword.get(word)
            neighbours |= 1 << kw.id

        # Update all keywords
        for word in words:
            kw = Keyword.get(word)
            kw.update(doc, neighbours)

        return True
Пример #7
0
#	show :: [Instruction] -> String
#	show (Lam : is) = '\\' : show is
#	show (APP l:is) = '(' : show is ++ ' ' : show l ++ ")"
#	show (Ind n:is) = show n

import lexer
import parser
import unsugarer
import assembler
import generator

if __name__ == "__main__" :

	langLexer = lexer.load("lang.lex")
	langParser = parser.load("lang.par")
	langUnser = unsugarer.load("lang.uns")
	assm = assembler.load("lang.lasm")

	with open("lambda.lang") as file :
		code = file.read()

	lexed = langLexer.lex(code)
	parsed = langParser.parse(lexed)
	unsuged = langUnser.unsugar(parsed)
	gened = generator.generate(unsuged)

	print(gened)
	assmed = assm.assemble(gened)

	print(assmed, "\n")
Пример #8
0
from parser import load
from nn import NN

import numpy as np
epoch_count = 100

if __name__ == '__main__':
    print('Creating network model...')
    nn = NN()

    nn.train(load('./vindi/'), epoch=1)
Пример #9
0
            print('python3 main.py vc-exact_019.gr 60000 1 1')
            exit(1)

        filename = sys.argv[1]
        runtime = int(sys.argv[2])
        max_temperature = int(sys.argv[3])
        seed = int(sys.argv[4])

        print('')
        print('Running %s' % filename)
        print('runtime: %i' % runtime)
        print('max_temperature: %i' % max_temperature)
        print('seed: %i' % seed)
        print('')

        nr_nodes, edges = load(filename)
        best_solution, evaluation_list = search(nr_nodes, edges, runtime, max_temperature, seed)
        plot_evaluations(filename, nr_nodes, len(edges), evaluation_list, len(best_solution), runtime,
                         max_temperature, seed)
        exit(0)

    """
    Exectue all files from data directory with all available settings
    """
    data_files = filter(lambda x: '.gr' in x, os.listdir('data'))

    for filename in data_files:
        nr_runs = 10
        runtime = 60000
        max_temperature = 1
Пример #10
0
import parser
import solver

figure = parser.load('figure.pol')

for idx, s in enumerate(solver.auto_congruent_polyomino_split(figure, 5)):
    parser.save_solution_to_svg(s, str(idx) + 'th_sol.svg')
    parser.pretty_print_solution(s)
    print()
Пример #11
0
    USE_PARSING = options.parse

    CLASSIFIER = options.classifier
    CUTOFF_PROB = options.cutoff_prob
    BOOTSTRAP_CUTOFF_PROB = options.bootstrap_cutoff
    BOOTSTRAP_REPS = options.bootstrap
    if BOOTSTRAP_REPS > 0:
        USE_PROBS = True
    if CLASSIFIER == nltk.DecisionTreeClassifier and USE_PROBS:
        raise Exception("Decision tree classifier does not support probability\
		measures")
    if CLASSIFIER == None:
        raise Exception("No classifier specified, use -n -t or -m")

    parses = open("parses.pickle", 'r')
    dep_parser.all_of_them = dep_parser.load(parses)
    parses.close()

    print >> sys.stderr, "Gathering Items"
    items = senseval.fileids()
    print >> sys.stderr, "Gathering Tests"
    tests = pairing.parse_file("EnglishLS.test/EnglishLS.test")

    print >> sys.stderr, "Classifying"
    senses = batch_classify(items, tests)

    parses = open("parses.pickle", 'w')
    dep_parser.pickle(parses)
    parses.close()

    f = open('answers.txt')
Пример #12
0
def index():
	servers = parser.load()
	return render_template('index.html', servers=servers, trim=trim, geoip=geoip, colour=colour, gametype=gametype, mapname=mapname, len=len)
Пример #13
0
def test_sanity():
    msg = '{"type":"BA","data":"14:53:34|LPB|9.1|690|9|50350|8.9|23950|9.2|3000|9.3|10000|9.4|8840|100790|9.4|290|0.02726|157580|198110|"}'
    obj = parser.load(msg)
    assert obj['time'] == "14:53:34"
    assert obj['totalBidQtty'] == 198110
Пример #14
0
    (type, parts) = type
    if type in ("type", "variable"):
        return parts
    return "(" + tostr(parts[0]) + ("->" if type == "funtype" else
                                    " ") + tostr(parts[1]) + ")"


import lexer
import parser
import unsugarer
import copy

if __name__ == "__main__":
    unsugarer.load("lang.uns")
    lexer.load("lang.lex")
    parser.load("lang.par")

    typedefs[("type", "Bool")] = ("funtype", [("variable", "a"),
                                              ("funtype", [("variable", "a"),
                                                           ("variable", "a")])
                                              ])
    typedefs[("type", "String")] = ("constype", [("type", "List"),
                                                 ("type", "Char")])
    typedefs[("type", "Pair")] = ("funtype", [
        ("funtype", [("variable", "a"),
                     ("funtype", [("variable", "b"), ("variable", "c")])]),
        ("variable", "c")
    ])

    print(
        tostr(
Пример #15
0
import parser

parser.load()

print parser.data
Пример #16
0
import tensorflow as tf
import parser
from tensorflow import keras
from tensorflow.keras import layers


def create_model():
    opt = keras.optimizers.SGD(learning_rate=0.01, momentum=0.9, nesterov=True)
    model = keras.models.Sequential([
        layers.Dense(10, activation='relu', input_shape=(384, )),
        layers.Dense(10, activation='relu', input_shape=(10, )),
        layers.Dense(
            2,
            activation='softmax',
            input_shape=(10, ),
        )
    ])
    model.compile(optimizer=opt, loss='binary_crossentropy')
    # x = tf.ones((1, 384))
    # y = model(x)
    print(model.summary())
    return model


if __name__ == '__main__':
    model = create_model()
    features, labels = parser.load('data.txt')
    model.fit(features, labels, epochs=3)
Пример #17
0
	USE_PARSING = options.parse

	CLASSIFIER=options.classifier
	CUTOFF_PROB=options.cutoff_prob
	BOOTSTRAP_CUTOFF_PROB=options.bootstrap_cutoff
	BOOTSTRAP_REPS=options.bootstrap
	if BOOTSTRAP_REPS > 0:
		USE_PROBS = True
	if CLASSIFIER == nltk.DecisionTreeClassifier and USE_PROBS:
		raise Exception("Decision tree classifier does not support probability\
		measures")
	if CLASSIFIER == None:
		raise Exception("No classifier specified, use -n -t or -m")

	parses = open("parses.pickle", 'r')
	dep_parser.all_of_them = dep_parser.load(parses)
	parses.close()

	print >> sys.stderr, "Gathering Items"
	items = senseval.fileids()
	print >> sys.stderr, "Gathering Tests"
	tests = pairing.parse_file("EnglishLS.test/EnglishLS.test")

	print >> sys.stderr, "Classifying"
	senses = batch_classify(items, tests)

	parses = open("parses.pickle", 'w')
	dep_parser.pickle(parses)
	parses.close()

Пример #18
0
        elif arg.startswith("-d"):
            statflags(arg)
    Verbose = "-V" in argv
    Generate = not "-NG" in argv


if __name__ == "__main__":
    argv = sys.argv

    # Compiled language
    language = argv[argv.index("-l") + 1] if "-l" in argv else "lang"

    # Loading the appropriate config files
    unsugarer.load(language + ".uns")
    lexer.load(language + ".lex")
    parser.load(language + ".par")

    # Various switches
    flags(argv)

    # Input
    if "-f" in argv:
        filename = argv[argv.index("-f") + 1]
        with open(filename, "r") as file:
            source = file.read()
    elif "--imm" in argv:
        source = argv[argv.index("-imm") + 1]
    elif "-I" in argv:
        interactive()
    else:
        source = input()
Пример #19
0
def make( fp ):
    assert fp.endswith(".c2")
    for stmt in parser.load(fp):
        put_stmt(stmt)
    prg = get_program()        
    codegen.to_py(fp[:-3]+".py",prg)
Пример #20
0
    def refresh(self):
        self.status = self.STATUS_UPDATED

        with open(self.path, 'r') as fp:
            self.data = parser.load(fp)
Пример #21
0
 async def recv(self):
     data = await self.ws.recv()
     print("recv", data)
     return parser.load(data)
Пример #22
0
 async def recv(self):
     data = await self.ws.recv()
     return parser.load(data)