예제 #1
0
파일: tests.py 프로젝트: saksim/slpp
    def test_numbers(self):
        # Integer and float:
        self.assertEqual(slpp.decode('3'), 3)
        self.assertEqual(slpp.decode('4.1'), 4.1)
        self.assertEqual(slpp.encode(3), '3')
        self.assertEqual(slpp.encode(4.1), '4.1')

        # Negative float:
        self.assertEqual(slpp.decode('-0.45'), -0.45)
        self.assertEqual(slpp.encode(-0.45), '-0.45')

        # Scientific:
        self.assertEqual(slpp.decode('3e-7'), 3e-7)
        self.assertEqual(slpp.decode('-3.23e+17'), -3.23e+17)
        self.assertEqual(slpp.encode(3e-7), '3e-07')
        self.assertEqual(slpp.encode(-3.23e+17), '-3.23e+17')

        # Hex:
        self.assertEqual(slpp.decode('0x3a'), 0x3a)

        differ(
            slpp.decode('''{
            ID = 0x74fa4cae,
            Version = 0x07c2,
            Manufacturer = 0x21544948
        }'''), {
                'ID': 0x74fa4cae,
                'Version': 0x07c2,
                'Manufacturer': 0x21544948
            })
예제 #2
0
 def test_unicode(self):
     if six.PY2:
         self.assertEqual(
             slpp.encode(u'Привет'),
             '"\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82"')
     if six.PY3:
         self.assertEqual(slpp.encode(u'Привет'), '"Привет"')
     self.assertEqual(slpp.encode({'s': u'Привет'}), '{\n\ts = "Привет"\n}')
예제 #3
0
    def test_string(self):
        # Escape test:
        self.assertEqual(slpp.decode(r"'test\'s string'"), "test's string")

        # Add escaping on encode:
        self.assertEqual(slpp.encode({'a': 'func("call()");'}),
                         '{\n\ta = "func(\\"call()\\");"\n}')
예제 #4
0
def convert(xlsxfile, tablename):
    o = parseObject(xlsxfile)
    if isinstance(o, list) and type(o[0]) is dict:
        if 'Key' in o[0] and 'Value' in o[0]:
            o = dict([(item['Key'], item['Value']) for item in o])
    tempLuaFilename = xlsxfile.replace('.xlsx', '.lua')
    with open(tempLuaFilename, 'w') as tempLuaFile:
        tempLuaFile.write(tablename + ' = ' + lua.encode(o))
예제 #5
0
파일: tests.py 프로젝트: saksim/slpp
    def test_string(self):
        # Escape test:
        self.assertEqual(slpp.decode(r"'test\'s string'"), "test's string")

        # Add escaping on encode:
        self.assertEqual(slpp.encode({'a': 'func("call()");'}),
                         '{\n\t["a"] = "func(\\"call()\\");"\n}')

        # Strings inside double brackets
        longstr = ' ("word") . [ ["word"] . ["word"] . ("word" | "word" | "word" | "word") . ["word"] ] '
        self.assertEqual(slpp.decode('[[' + longstr + ']]'), longstr)
        self.assertEqual(
            slpp.decode('{ [0] = [[' + longstr + ']], [1] = "a"}'),
            [longstr, "a"])
예제 #6
0
 def _save_lua_data(self, data: dict):
     save_data = {}
     for data_file in data:
         raw_data = data_file.split("/")[-1] + " =\n" + lua.encode(
             data[data_file])
         save_data.update({data_file: raw_data})
     with zipfile.ZipFile(self.path,
                          mode='w',
                          compression=zipfile.ZIP_DEFLATED) as archive_w:
         for filename, buffer in self.buffer_dict.items():
             if filename not in save_data.keys():
                 archive_w.writestr(filename, buffer)
         for local_path in save_data:
             archive_w.writestr(local_path, save_data[local_path])
     self.buffer_dict = self._get_buffer()
예제 #7
0
파일: tests.py 프로젝트: saksim/slpp
    def test_table(self):
        # Bracketed string key:
        self.assertEqual(slpp.decode('{[10] = 1}'), {10: 1})

        # Void table:
        self.assertEqual(slpp.decode('{nil}'), {})

        # Values-only table:
        self.assertEqual(slpp.decode('{"10"}'), ["10"])

        # Last zero
        self.assertEqual(slpp.decode('{0, 1, 0}'), [0, 1, 0])

        # Mixed encode
        self.assertEqual(slpp.encode({
            '0': 0,
            'name': 'john'
        }), '{\n\t["0"] = 0,\n\t["name"] = "john"\n}')
예제 #8
0
파일: GetCSC.py 프로젝트: kfusac/TellMeWhen

	# class spells
	all_spell_pages = list(itertools.product(class_spells_urls, class_slugs))
	results = pool.map(scrape_class_spells, [(b + c, class_slugs[c]) for (b, c) in all_spell_pages])

	for classIDAndSpells in results:
		classID = classIDAndSpells[0]
		keyed_results[classID] = keyed_results.get(classID, []) + classIDAndSpells[1]





	# pet spells
	results = pool.map(scrape_class_spells, [(pet_spells_url + c, class_slugs[c]) for c in pet_classes])

	keyed_results["PET"] = {}
	for classIDAndSpells in results:
		classID = classIDAndSpells[0]
		keyed_results["PET"].update({id: classID for id in classIDAndSpells[1]})





	output = "local Cache = " + lua.encode(keyed_results)
	output = re.sub(r"\n\t\t(.*?) = ", r'\1=', output)
	open('CSC.lua', 'w').write(output)

	print("complete. written to CSC.lua.")
예제 #9
0
파일: tests.py 프로젝트: saksim/slpp
    def test_bool(self):
        self.assertEqual(slpp.encode(True), 'true')
        self.assertEqual(slpp.encode(False), 'false')

        self.assertEqual(slpp.decode('true'), True)
        self.assertEqual(slpp.decode('false'), False)
예제 #10
0
파일: tests.py 프로젝트: saksim/slpp
 def test_nil(self):
     self.assertEqual(slpp.encode(None), 'nil')
     self.assertEqual(slpp.decode('nil'), None)
예제 #11
0
def create_lua_file(path, name, table):
    # replace string to number
    fileobj = open(path + name + ".lua", "w")
    buff = lua.encode(table)
    fileobj.write(buff)
    fileobj.close()    
예제 #12
0
def exportBlueprint(layout, string=True):
    """
  Convert Layout to lua blueprint.
  If string==True, outputs a blueprint string (gzip+base64)
  Otherwise, blueprint is an entity list that can be used via
  "/c game.player.cursor_stack.set_blueprint_entities(blueprint)"
  """
    if not layout.flags["meta_valid"]:
        raise RuntimeError("Cannot produce blueprint without valid meta info")

    bp_entities = []
    for ent in layout.entities:
        ent_bp = {}
        ent_bp["connections"] = {}
        for i, term in enumerate(ent.terminals):
            bp_term = str(i + 1)
            bp_wires_by_color = defaultdict(list)
            for wire in term.wires:
                other_term = list(wire.terminals - {term})[0]
                other_ent = other_term.ent
                circuit_id = other_ent.terminal_types[other_term.type] + 1

                bp_wires_by_color[wire.color.name].append({
                    "circuit_id":
                    circuit_id,
                    "entity_id":
                    other_ent.number
                })

            ent_bp["connections"][bp_term] = bp_wires_by_color
            ent_bp["entity_number"] = ent.number
            ent_bp["name"] = ent.name
            ent_bp["position"] = ent.position
            if hasattr(ent, "direction"):
                ent_bp["direction"] = ent.direction.value
            if hasattr(ent, "behavior"):
                ent_bp["control_behavior"] = ent.behavior
        bp_entities.append(ent_bp)
    bp_entities.sort(key=lambda ent_bp: ent_bp["entity_number"])

    if not string:
        lua_entities = lua.encode(bp_entities)
        return lua_entities
    else:
        blueprint = {"entities": bp_entities}

        # Name is optional
        if "name" in layout.meta:
            blueprint["name"] = layout.meta["name"]

        # Icons are required
        if "icons" in layout.meta:
            blueprint["icons"] = [{
                "signal": icon,
                "index": i
            } for i, icon in enumerate(layout.meta["icons"], 1)]
        else:
            first_ent_name = bp_entities[0]["name"]
            blueprint["icons"] = [{
                "index": 1,
                "signal": {
                    "type": "item",
                    "name": first_ent_name
                }
            }]

        lua_blueprint = lua.encode(blueprint)
        lua_blueprint = "do local _=" + lua_blueprint + ";return _;end"

        # Encode blueprint string
        bp_string = base64.b64encode(
            gzip.compress(lua_blueprint.encode('utf-8'))).decode('utf-8')
        return bp_string
예제 #13
0
 def parse_json_to_lua(self, data):
     lua_str = lua.encode(data)
     return re.sub("\[\"(\d+)\"]", r'[\1]', lua_str)
예제 #14
0
def create_lua_file(path, name, table):
    # replace string to number
    fileobj = open(path + name + ".lua", "w")
    buff = lua.encode(table)
    fileobj.write(buff)
    fileobj.close()
예제 #15
0
파일: tests.py 프로젝트: saksim/slpp
 def t(data):
     d = slpp.decode(data)
     self.assertEqual(d, slpp.decode(slpp.encode(d)))
예제 #16
0
        keyed_results[classID] = keyed_results.get(classID,
                                                   []) + classIDAndSpells[1]

    # pet spells
    results = pool.map(scrape_class_spells,
                       [(pet_spells_url + c, class_slugs[c])
                        for c in pet_classes])

    keyed_results["PET"] = {}
    for classIDAndSpells in results:
        classID = classIDAndSpells[0]
        keyed_results["PET"].update(
            {id: classID
             for id in classIDAndSpells[1]})

    output = "local Cache = {\n"
    for key in sorted(keyed_results,
                      key=lambda k: '%03d' % k
                      if isinstance(k, (int)) else str(k)):
        # in-place sort the list of spellIDs.
        if type(keyed_results[key]) is list:
            keyed_results[key].sort()

        line = lua.encode(keyed_results[key])
        line = re.sub(r"[\n\t ]", r'', line)
        output += "\t[" + lua.encode(key) + "] = " + line + ",\n"

    output += "}"
    open(os.path.join(os.path.dirname(__file__), 'CSC.lua'), 'w').write(output)

    print("complete. written to CSC.lua.")
예제 #17
0
파일: sheet.py 프로젝트: amorwilliams/etox
 def export_lua(self, name, sheet_output_field=[]):
     sheet = self.sheet_dic[name]
     data = sheet.to_python(sheet_output_field)
     s = ('%s' % '\n').join([ 't[%s] = %s' % (k, lua.encode(v)) for k, v in data.items() ])
     return 't={}\n %s \n ' % s
예제 #18
0
파일: tests.py 프로젝트: saksim/slpp
 def test_basic(self):
     # No data loss:
     data = '{ array = { 65, 23, 5 }, dict = { string = "value", array = { 3, 6, 4}, mixed = { 43, 54.3, false, string = "value", 9 } } }'
     d = slpp.decode(data)
     differ(d, slpp.decode(slpp.encode(d)))
예제 #19
0
                    checks[ID] = checksum(fullpath)
                except Exception, e:
                    pass

        if not isPrecompile:
            #print checks
            save(BUILDPATH + "o", checks)

        #project info
        PROJECT_INFO = {
            "width": self._screenWidth,
            "height": self._screenHeight,
            "fullscreen": self._fullscreen
        }
        with codecs.open(BUILDPATH + "ProjectInfo.lua", "w", "utf-8") as fp:
            fp.write("return " + slpp.encode(PROJECT_INFO) + "\n")

        # fp = QFile(BUILDPATH+"ProjectInfo.lua")
        # fp.open(QIODevice.WriteOnly | QIODevice.Text)

        # out = QTextStream(fp)
        # out.setCodec("UTF-8")
        # out.setGenerateByteOrderMark(False)
        # out<<"return "<<slpp.encode(PROJECT_INFO)<<"\n"
        # out = None
        # fp.close()

        #FILEMANGER
        with codecs.open(BUILDPATH + "FILEMANS.lua", "w", "utf-8") as fp:
            fp.write("FILES = {}\n")
            for k, v in fileMans.iteritems():
예제 #20
0
    # Run racials first since they're most prone to failure.
    result = pool.apply(scrape_racial_spells)
    keyed_results["RACIAL"] = result

    # class spells
    all_spell_pages = list(itertools.product(class_spells_urls, class_slugs))
    results = pool.map(scrape_class_spells,
                       [(b + c, class_slugs[c]) for (b, c) in all_spell_pages])

    for classIDAndSpells in results:
        classID = classIDAndSpells[0]
        keyed_results[classID] = keyed_results.get(classID,
                                                   []) + classIDAndSpells[1]

    # pet spells
    results = pool.map(scrape_class_spells,
                       [(pet_spells_url + c, class_slugs[c])
                        for c in pet_classes])

    keyed_results["PET"] = {}
    for classIDAndSpells in results:
        classID = classIDAndSpells[0]
        keyed_results["PET"].update(
            {id: classID
             for id in classIDAndSpells[1]})

    output = "local Cache = " + lua.encode(keyed_results)
    output = re.sub(r"\n\t\t(.*?) = ", r'\1=', output)
    open('CSC.lua', 'w').write(output)

    print("complete. written to CSC.lua.")
예제 #21
0
        model = joblib.load(open(sys.argv[1], 'r+'))
        model_idx_count = 0
        past_node_ct = 0
        past_tree_ct = 0
        mdl_map = {}
        if isinstance(model, dict):
            ## this case, it's a model of models.
            final_model_list = []
            for k, v in model.iteritems():
                model_op = generate_csv_indiv_model(v, model_idx_count,
                                                    past_node_ct, past_tree_ct)
                past_node_ct = model_op['nodes']
                past_tree_ct = past_tree_ct + model_op['n_trees']
                model_idx_count = model_idx_count + 1
                mdl_map[model_idx_count] = k
                final_model_list.append(model_op['df'])
            final_df = pd.concat(final_model_list)
        else:
            final_df = generate_csv_indiv_model(model, model_idx_count,
                                                past_node_ct,
                                                past_tree_ct)['df']
            mdl_map[str(model_idx_count)] = DEFAULT_MODEL_NM
        final_df.to_csv(sys.argv[2], index=False)
        print lua.encode(mdl_map)
        lua_dict = 'return {}'.format(lua.encode(mdl_map).strip('\n'))
        print lua_dict
        with open(sys.argv[3], 'w+') as outf:
            outf.write(lua_dict)
    except Exception as e:
        logr.error('Error: {}'.format(str(e)))