List of usage examples for org.apache.commons.collections BidiMap getKey
Object getKey(Object value);
From source file:HashMapExampleV1.java
public static void main(String args[]) { BidiMap agentToCode = new DualHashBidiMap(); agentToCode.put("007", "Bond"); agentToCode.put("006", "Trevelyan"); agentToCode.put("002", "Fairbanks"); System.err.println("Agent name from code: " + agentToCode.get("007")); System.err.println("Code from Agent name: " + agentToCode.getKey("Bond")); }
From source file:br.ufal.cideei.soot.instrument.bitrep.BitConfigRep.java
public static boolean isValid(int index, BidiMap atoms, FeatureSetChecker checker) { if (checker == null) return true; Set<String> enabledFeatures = new HashSet<String>(); Set<String> disabledFeatures = new HashSet<String>(); Collection<Integer> values = atoms.values(); for (Integer featureId : values) { String featureStr = (String) atoms.getKey(featureId); if ((featureId & index) == featureId) enabledFeatures.add(featureStr); else/*from w w w . j a v a 2 s . c o m*/ disabledFeatures.add(featureStr); } return checker.check(enabledFeatures, disabledFeatures); }
From source file:br.ufpe.cin.emergo.instrument.bitrep.BitConfigRep.java
public static boolean isValid(int identifier, BidiMap atoms, FeatureSetChecker checker) { if (checker == null) return true; Set<String> enabledFeatures = new HashSet<String>(); Set<String> disabledFeatures = new HashSet<String>(); Collection<Integer> values = atoms.values(); for (Integer featureId : values) { String featureStr = (String) atoms.getKey(featureId); if ((featureId & identifier) == featureId) enabledFeatures.add(featureStr); else//from w w w . j a v a2 s . co m disabledFeatures.add(featureStr); } return checker.check(enabledFeatures, disabledFeatures); }
From source file:de.tudarmstadt.ukp.dkpro.tc.svmhmm.util.SVMHMMUtils.java
/** * Reads the prediction file (each line is a integer) and converts them into original outcome * labels using the mapping provided by the bi-directional map * * @param predictionsFile predictions from classifier * @param labelsToIntegersMapping mapping outcomeLabel:integer * @return list of outcome labels/* w w w . jav a2s. co m*/ * @throws IOException */ public static List<String> extractOutcomeLabelsFromPredictions(File predictionsFile, BidiMap labelsToIntegersMapping) throws IOException { List<String> result = new ArrayList<>(); for (String line : FileUtils.readLines(predictionsFile)) { Integer intLabel = Integer.valueOf(line); String outcomeLabel = (String) labelsToIntegersMapping.getKey(intLabel); result.add(outcomeLabel); } return result; }
From source file:de.tudarmstadt.ukp.dkpro.tc.svmhmm.util.SVMHMMUtils.java
/** * Saves the feature mapping to readable format, each line is a feature id and feature name, * sorted by feature id/* w w w . j av a2 s . com*/ * * @param mapping mapping (name:id) * @param outputFile output file * @throws IOException */ public static void saveMappingTextFormat(BidiMap mapping, File outputFile) throws IOException { PrintWriter pw = new PrintWriter(new FileOutputStream(outputFile)); // sort values (feature indexes) SortedSet<Object> featureIndexes = new TreeSet<Object>(mapping.values()); for (Object featureIndex : featureIndexes) { pw.printf(Locale.ENGLISH, "%5d %s%n", (int) featureIndex, mapping.getKey(featureIndex).toString()); } IOUtils.closeQuietly(pw); }
From source file:cerrla.modular.ModularPolicy.java
/** * Transforms the given goal replacements into potentially different (but * always smaller/equal size) replacements based on how this policy is * defined./*from w w w . j a v a 2 s . c o m*/ * * @param originalGoalReplacements * The original goal replacements to modify. * @return The transformed replacements. Always smaller/equal size and using * the same args. */ private BidiMap transformGoalReplacements(BidiMap originalGoalReplacements) { // Modify the goal replacements based on the moduleParamReplacements BidiMap goalReplacements = originalGoalReplacements; if (moduleParamReplacements_ != null && !moduleParamReplacements_.isEmpty()) { // Swap any terms shown in the replacements BidiMap modGoalReplacements = new DualHashBidiMap(); for (RelationalArgument ruleParam : moduleParamReplacements_.keySet()) { RelationalArgument goalParam = moduleParamReplacements_.get(ruleParam); modGoalReplacements.put(goalReplacements.getKey(goalParam), ruleParam); } goalReplacements = modGoalReplacements; } return goalReplacements; }
From source file:com.runwaysdk.mobile.IdConversionTest.java
public void testConvertGlobalAndLocalIds() { mobileIdToSessionId = new DualHashBidiMap(); // Maps a session to a bi-directional hash map BidiMap<globalId, localId> final HashMap<String, BidiMap> idMap = new HashMap<String, BidiMap>(); // Log all our threads in, and map the session ids to our mobile ids. // Do it twice so that we can ensure we can update an existing sessionId mapping with no problem. for (int i = 0; i < 2; ++i) { lock = new CountDownLatch(mobileIds.length); for (final String mobileId : mobileIds) { Thread t = new Thread() { public void run() { idConverter = IdConverter.getInstance(); ClientSession clientSession = ClientSession.createUserSession("default", customUsernameAndPassword, customUsernameAndPassword, new Locale[] { CommonProperties.getDefaultLocale() }); mobileIdToSessionId.put(mobileId, clientSession.getSessionId()); idConverter.mapSessionIdToMobileId(clientSession.getSessionId(), mobileId); onThreadStart(mobileId); onThreadEnd();/* w w w. j a v a 2 s. c om*/ clientSession.logout(); } }; t.setDaemon(true); t.start(); } waitOnThreads(); } System.out.println("Session ids mapped to mobile ids."); // Generate a bunch of local ids lock = new CountDownLatch(mobileIds.length); for (final String mobileId : mobileIds) { Thread t = new Thread() { public void run() { onThreadStart(mobileId); BidiMap globalIdToLocalIdMap = new DualHashBidiMap(); idMap.put(mobileId, globalIdToLocalIdMap); for (String globalId : globalIds) { String localId = idConverter.generateLocalIdFromGlobalId(mobileId, globalId); globalIdToLocalIdMap.put(globalId, localId); //System.out.println(mobileId + "\n" + globalId + "\n" + localId + "\n\n"); } onThreadEnd(); } }; t.setDaemon(true); t.start(); } waitOnThreads(); System.out.println("localIds generated and mapped to globalIds"); // Assert that we can get the globalId back from the localId lock = new CountDownLatch(mobileIds.length); for (final String mobileId : mobileIds) { Thread t = new Thread() { @SuppressWarnings("unchecked") public void run() { onThreadStart(mobileId); BidiMap globalIdToLocalIdMap = idMap.get(mobileId); Collection<String> localIds = globalIdToLocalIdMap.values(); for (String localId : localIds) { String globalId = idConverter.getGlobalIdFromLocalId(mobileId, localId); assertEquals((String) globalIdToLocalIdMap.getKey(localId), globalId); } onThreadEnd(); } }; t.setDaemon(true); t.start(); } waitOnThreads(); System.out.println("globalIds retrieved from localIds."); // Generate local ids from the same mobile ids again and make sure we got the same local ids lock = new CountDownLatch(mobileIds.length); for (final String mobileId : mobileIds) { Thread t = new Thread() { public void run() { onThreadStart(mobileId); BidiMap globalIdToLocalIdMap = idMap.get(mobileId); for (String globalId : globalIds) { String localId = idConverter.generateLocalIdFromGlobalId(mobileId, globalId); assertEquals(localId, (String) globalIdToLocalIdMap.get(globalId)); } onThreadEnd(); } }; t.setDaemon(true); t.start(); } waitOnThreads(); System.out.println("Generated local ids from the same mobile ids."); // Delete all the global ids idConverter = IdConverter.getInstance(); lock = new CountDownLatch(globalIds.length); for (final String globalId : globalIds) { Thread t = new Thread() { public void run() { waitRandomAmount(); //System.out.println("Invalidating globalId " + globalId); idConverter.invalidateGlobalId(globalId); onThreadEnd(); } }; t.setDaemon(true); t.start(); } waitOnThreads(); System.out.println("Deleted all global ids."); // Try to retrieve them and assert that they're null. lock = new CountDownLatch(mobileIds.length); for (final String mobileId : mobileIds) { Thread t = new Thread() { public void run() { onThreadStart(mobileId); BidiMap globalIdToLocalIdMap = idMap.get(mobileId); for (String globalId : globalIds) { try { String retval = idConverter.getGlobalIdFromLocalId(mobileId, (String) globalIdToLocalIdMap.get(globalId)); fail("The globalId is still mapped. globalId = " + retval); } catch (IdConversionException e) { } } onThreadEnd(); } }; t.setDaemon(true); t.start(); } waitOnThreads(); System.out.println("Tried to retrieve previously deleted global ids."); // Generate more localIds, just to flex the stacks lock = new CountDownLatch(mobileIds.length); for (final String mobileId : mobileIds) { Thread t = new Thread() { public void run() { onThreadStart(mobileId); BidiMap globalIdToLocalIdMap = new DualHashBidiMap(); idMap.put(mobileId, globalIdToLocalIdMap); for (String globalId : globalIds) { String localId = idConverter.generateLocalIdFromGlobalId(mobileId, globalId); globalIdToLocalIdMap.put(globalId, localId); } onThreadEnd(); } }; t.setDaemon(true); t.start(); } waitOnThreads(); System.out.println("Generated more localIds, to flex the stacks."); // Assert that we can get the globalId back from the localId lock = new CountDownLatch(mobileIds.length); for (final String mobileId : mobileIds) { Thread t = new Thread() { @SuppressWarnings("unchecked") public void run() { onThreadStart(mobileId); BidiMap globalIdToLocalIdMap = idMap.get(mobileId); Collection<String> localIds = globalIdToLocalIdMap.values(); for (String localId : localIds) { String globalId = idConverter.getGlobalIdFromLocalId(mobileId, localId); assertEquals((String) globalIdToLocalIdMap.getKey(localId), globalId); } onThreadEnd(); } }; t.setDaemon(true); t.start(); } waitOnThreads(); System.out.println("globalids retrieved from localids."); // Delete all the global ids idConverter = IdConverter.getInstance(); lock = new CountDownLatch(globalIds.length); for (final String globalId : globalIds) { Thread t = new Thread() { public void run() { waitRandomAmount(); //System.out.println("Invalidating globalId " + globalId); idConverter.invalidateGlobalId(globalId); onThreadEnd(); } }; t.setDaemon(true); t.start(); } waitOnThreads(); System.out.println("Deleted all global id, test complete."); }
From source file:cn.nukkit.Server.java
@SuppressWarnings("unchecked") Server(MainLogger logger, final String filePath, String dataPath, String pluginPath) { Preconditions.checkState(instance == null, "Already initialized!"); currentThread = Thread.currentThread(); // Saves the current thread instance as a reference, used in Server#isPrimaryThread() instance = this; this.logger = logger; this.filePath = filePath; if (!new File(dataPath + "worlds/").exists()) { new File(dataPath + "worlds/").mkdirs(); this.getLogger().info(TextFormat.AQUA + dataPath + "worlds/ was created!"); }/* w w w .j a v a 2s . c om*/ if (!new File(dataPath + "players/").exists()) { new File(dataPath + "players/").mkdirs(); this.getLogger().info(TextFormat.AQUA + dataPath + "players/ was created!"); } if (!new File(pluginPath).exists()) { new File(pluginPath).mkdirs(); this.getLogger().info(TextFormat.AQUA + pluginPath + "plugins/ was created!"); this.getLogger().info(TextFormat.AQUA + dataPath + "worlds/ ?????"); } if (!new File(dataPath + "players/").exists()) { new File(dataPath + "players/").mkdirs(); this.getLogger().info(TextFormat.AQUA + dataPath + "players/ ?????"); } if (!new File(pluginPath).exists()) { new File(pluginPath).mkdirs(); this.getLogger().info(TextFormat.AQUA + pluginPath + " ?????"); } if (!new File(dataPath + "unpackedPlugins/").exists()) { new File(dataPath + "unpackedPlugins/").mkdirs(); this.getLogger().info(TextFormat.AQUA + pluginPath + "unpackedPlugins/ ?????"); } if (!new File(dataPath + "compileOrder/").exists()) { new File(dataPath + "compileOrder/").mkdirs(); this.getLogger().info(TextFormat.AQUA + pluginPath + "compileOrder/ ?????"); } this.dataPath = new File(dataPath).getAbsolutePath() + "/"; this.pluginPath = new File(pluginPath).getAbsolutePath() + "/"; this.console = new CommandReader(); //todo: VersionString ?? if (!new File(this.dataPath + "nukkit.yml").exists()) { this.getLogger().info(TextFormat.GREEN + "Welcome! Please choose a language first!"); try { String[] lines = Utils .readFile(this.getClass().getClassLoader().getResourceAsStream("lang/language.list")) .split("\n"); for (String line : lines) { this.getLogger().info(line); } } catch (IOException e) { throw new RuntimeException(e); } String fallback = BaseLang.FALLBACK_LANGUAGE; String language = null; while (language == null) { String lang = this.console.readLine(); InputStream conf = this.getClass().getClassLoader() .getResourceAsStream("lang/" + lang + "/lang.ini"); if (conf != null) { language = lang; } } InputStream advacedConf = this.getClass().getClassLoader() .getResourceAsStream("lang/" + language + "/nukkit.yml"); if (advacedConf == null) { advacedConf = this.getClass().getClassLoader() .getResourceAsStream("lang/" + fallback + "/nukkit.yml"); } try { Utils.writeFile(this.dataPath + "nukkit.yml", advacedConf); } catch (IOException e) { throw new RuntimeException(e); } } this.console.start(); this.logger.info(TextFormat.GREEN + "nukkit.yml" + TextFormat.WHITE + "?????..."); this.config = new Config(this.dataPath + "nukkit.yml", Config.YAML); this.logger .info(TextFormat.GREEN + "server.properties" + TextFormat.WHITE + "?????..."); this.properties = new Config(this.dataPath + "server.properties", Config.PROPERTIES, new ConfigSection() { { put("motd", "Jupiter Server For Minecraft: PE"); put("server-port", 19132); put("server-ip", "0.0.0.0"); put("view-distance", 10); put("white-list", false); put("achievements", true); put("announce-player-achievements", true); put("spawn-protection", 16); put("max-players", 20); put("allow-flight", false); put("spawn-animals", true); put("spawn-mobs", true); put("gamemode", 0); put("force-gamemode", false); put("hardcore", false); put("pvp", true); put("difficulty", 1); put("generator-settings", ""); put("level-name", "world"); put("level-seed", ""); put("level-type", "DEFAULT"); put("enable-query", true); put("enable-rcon", false); put("rcon.password", Base64.getEncoder() .encodeToString(UUID.randomUUID().toString().replace("-", "").getBytes()).substring(3, 13)); put("auto-save", true); put("force-resources", false); } }); this.logger.info(TextFormat.GREEN + "jupiter.yml" + TextFormat.WHITE + "?????..."); if (!new File(this.dataPath + "jupiter.yml").exists()) { InputStream advacedConf = this.getClass().getClassLoader().getResourceAsStream("lang/jpn/jupiter.yml"); if (advacedConf == null) this.getLogger().error( "Jupiter.yml????????????????"); try { Utils.writeFile(this.dataPath + "jupiter.yml", advacedConf); } catch (IOException e) { throw new RuntimeException(e); } } this.loadJupiterConfig(); InputStream advacedConf1 = this.getClass().getClassLoader().getResourceAsStream("lang/jpn/jupiter.yml"); if (advacedConf1 == null) this.getLogger().error( "Jupiter.yml????????????????"); try { Utils.writeFile(this.dataPath + "jupiter1.yml", advacedConf1); } catch (IOException e) { throw new RuntimeException(e); } //get Jupiter.yml in the jar Config jupiter = new Config(this.getDataPath() + "jupiter1.yml"); Map<String, Object> jmap = jupiter.getAll(); Collection<Object> objj = jmap.values(); Object[] objj1 = objj.toArray(); Object objj2 = objj1[objj1.length - 1]; BidiMap mapp = new DualHashBidiMap(jmap); String keyy = (String) mapp.getKey(objj2); //get JupiterConfig key in the delectory Collection<Object> obj = jupiterconfig.values(); Object[] obj1 = obj.toArray(); Object obj2 = obj1[obj1.length - 1]; BidiMap map = new DualHashBidiMap(jupiterconfig); String key1 = (String) map.getKey(obj2); //delete jupiter1.yml File jf = new File(this.dataPath + "jupiter1.yml"); jf.delete(); if (!keyy.equals(key1)) { File conf = new File(this.dataPath + "jupiter.yml"); conf.delete(); InputStream advacedConf = this.getClass().getClassLoader().getResourceAsStream("lang/jpn/jupiter.yml"); if (advacedConf == null) this.getLogger().error( "Jupiter.yml????????????????"); try { Utils.writeFile(this.dataPath + "jupiter.yml", advacedConf); } catch (IOException ex) { throw new RuntimeException(ex); } this.getLogger() .info(TextFormat.AQUA + "Jupiter.yml????????????"); this.loadJupiterConfig(); } if (this.getJupiterConfigBoolean("destroy-block-particle")) { Level.sendDestroyParticle = true; } else { Level.sendDestroyParticle = false; } this.forceLanguage = (Boolean) this.getConfig("settings.force-language", false); this.baseLang = new BaseLang((String) this.getConfig("settings.language", BaseLang.FALLBACK_LANGUAGE)); this.logger.info(this.getLanguage().translateString("language.selected", new String[] { getLanguage().getName(), getLanguage().getLang() })); this.logger.info(this.getLanguage().translateString("nukkit.server.start", TextFormat.AQUA + this.getVersion() + TextFormat.WHITE)); Object poolSize = this.getConfig("settings.async-workers", "auto"); if (!(poolSize instanceof Integer)) { try { poolSize = Integer.valueOf((String) poolSize); } catch (Exception e) { poolSize = Math.max(Runtime.getRuntime().availableProcessors() + 1, 4); } } ServerScheduler.WORKERS = (int) poolSize; int threshold; try { threshold = Integer.valueOf(String.valueOf(this.getConfig("network.batch-threshold", 256))); } catch (Exception e) { threshold = 256; } if (threshold < 0) { threshold = -1; } Network.BATCH_THRESHOLD = threshold; this.networkCompressionLevel = (int) this.getConfig("network.compression-level", 7); this.networkCompressionAsync = (boolean) this.getConfig("network.async-compression", true); this.networkCompressionLevel = (int) this.getConfig("network.compression-level", 7); this.networkCompressionAsync = (boolean) this.getConfig("network.async-compression", true); this.autoTickRate = (boolean) this.getConfig("level-settings.auto-tick-rate", true); this.autoTickRateLimit = (int) this.getConfig("level-settings.auto-tick-rate-limit", 20); this.alwaysTickPlayers = (boolean) this.getConfig("level-settings.always-tick-players", false); this.baseTickRate = (int) this.getConfig("level-settings.base-tick-rate", 1); this.scheduler = new ServerScheduler(); if (this.getPropertyBoolean("enable-rcon", false)) { this.rcon = new RCON(this, this.getPropertyString("rcon.password", ""), (!this.getIp().equals("")) ? this.getIp() : "0.0.0.0", this.getPropertyInt("rcon.port", this.getPort())); } this.entityMetadata = new EntityMetadataStore(); this.playerMetadata = new PlayerMetadataStore(); this.levelMetadata = new LevelMetadataStore(); this.operators = new Config(this.dataPath + "ops.txt", Config.ENUM); this.whitelist = new Config(this.dataPath + "white-list.txt", Config.ENUM); this.banByName = new BanList(this.dataPath + "banned-players.json"); this.banByName.load(); this.banByIP = new BanList(this.dataPath + "banned-ips.json"); this.banByIP.load(); this.maxPlayers = this.getPropertyInt("max-players", 20); this.setAutoSave(this.getPropertyBoolean("auto-save", true)); if (this.getPropertyBoolean("hardcore", false) && this.getDifficulty() < 3) { this.setPropertyInt("difficulty", 3); } Nukkit.DEBUG = (int) this.getConfig("debug.level", 1); if (this.logger instanceof MainLogger) { this.logger.setLogDebug(Nukkit.DEBUG > 1); } this.logger.info(this.getLanguage().translateString("nukkit.server.networkStart", new String[] { this.getIp().equals("") ? "*" : this.getIp(), String.valueOf(this.getPort()) })); this.serverID = UUID.randomUUID(); this.network = new Network(this); this.network.setName(this.getMotd()); this.logger.info(this.getLanguage().translateString("nukkit.server.info", this.getName(), TextFormat.YELLOW + this.getNukkitVersion() + TextFormat.WHITE, TextFormat.AQUA + this.getCodename() + TextFormat.WHITE, this.getApiVersion())); this.logger.info(this.getLanguage().translateString("nukkit.server.license", this.getName())); this.consoleSender = new ConsoleCommandSender(); this.commandMap = new SimpleCommandMap(this); this.registerEntities(); this.registerBlockEntities(); Block.init(); Enchantment.init(); Item.init(); Biome.init(); Effect.init(); Potion.init(); Attribute.init(); this.craftingManager = new CraftingManager(); this.resourcePackManager = new ResourcePackManager(new File(Nukkit.DATA_PATH, "resource_packs")); this.pluginManager = new PluginManager(this, this.commandMap); this.pluginManager.subscribeToPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, this.consoleSender); this.pluginManager.registerInterface(JavaPluginLoader.class); this.queryRegenerateEvent = new QueryRegenerateEvent(this, 5); this.network.registerInterface(new RakNetInterface(this)); Calendar now = Calendar.getInstance(); int y = now.get(Calendar.YEAR); int mo = now.get(Calendar.MONTH) + 1; int d = now.get(Calendar.DATE); int h = now.get(Calendar.HOUR_OF_DAY); int m = now.get(Calendar.MINUTE); int s = now.get(Calendar.SECOND); this.logger.info(TextFormat.AQUA + "=================================================================================="); this.logger.info(TextFormat.AQUA + ""); this.logger.info( " || || || || || || || ||"); this.logger.info(" | | | | | | | || | | | | | | | | || |"); this.logger.info(" | | | | | | | | | | | | | | | | "); this.logger.info(" _| | | | | | | | | | | | | | | | "); this.logger.info(" |____| |_____| |_| |__| |__| | | |_| _|"); this.logger.info(""); this.logger.info(TextFormat.AQUA + ""); this.logger.info(TextFormat.AQUA + "----------------------------------------------------------------------------------"); this.logger.info(TextFormat.GREEN + "Jupiter - Nukkit Fork"); this.logger.info(TextFormat.YELLOW + "JupiterDevelopmentTeam "); this.logger.info(TextFormat.AQUA + "----------------------------------------------------------------------------------"); this.logger.info( ": " + TextFormat.BLUE + y + "/" + mo + "/" + d + " " + h + "" + m + "" + s + ""); this.logger.info("???: " + TextFormat.GREEN + this.getMotd()); this.logger.info("ip: " + TextFormat.GREEN + this.getIp()); this.logger.info("?: " + TextFormat.GREEN + this.getPort()); this.logger.info("Nukkit?: " + TextFormat.LIGHT_PURPLE + this.getNukkitVersion()); this.logger.info("API?: " + TextFormat.LIGHT_PURPLE + this.getApiVersion()); this.logger.info("?: " + TextFormat.LIGHT_PURPLE + this.getCodename()); this.logger.info(TextFormat.AQUA + "=================================================================================="); if (this.getJupiterConfigBoolean("jupiter-compiler-mode")) { this.logger.info(TextFormat.YELLOW + "----------------------------------------------------------------------------------"); getLogger().info(TextFormat.AQUA + "?????..."); File f = new File(dataPath + "compileOrder/"); File[] list = f.listFiles(); for (int i = 0; i < list.length; i++) { if (new PluginCompiler().Compile(list[i])) getLogger().info(list[i].toPath().toString() + " :" + TextFormat.GREEN + ""); else getLogger().info(list[i].toPath().toString() + " :" + TextFormat.RED + ""); } this.logger.info(TextFormat.YELLOW + "----------------------------------------------------------------------------------"); } this.logger.info(TextFormat.LIGHT_PURPLE + "----------------------------------------------------------------------------------"); getLogger().info(TextFormat.AQUA + "?????..."); this.pluginManager.loadPlugins(this.pluginPath); this.enablePlugins(PluginLoadOrder.STARTUP); LevelProviderManager.addProvider(this, Anvil.class); LevelProviderManager.addProvider(this, McRegion.class); LevelProviderManager.addProvider(this, LevelDB.class); Generator.addGenerator(Flat.class, "flat", Generator.TYPE_FLAT); Generator.addGenerator(Normal.class, "normal", Generator.TYPE_INFINITE); Generator.addGenerator(Normal.class, "default", Generator.TYPE_INFINITE); Generator.addGenerator(Nether.class, "nether", Generator.TYPE_NETHER); //todo: add old generator and hell generator for (String name : ((Map<String, Object>) this.getConfig("worlds", new HashMap<>())).keySet()) { if (!this.loadLevel(name)) { long seed; try { seed = ((Integer) this.getConfig("worlds." + name + ".seed")).longValue(); } catch (Exception e) { seed = System.currentTimeMillis(); } Map<String, Object> options = new HashMap<>(); String[] opts = ((String) this.getConfig("worlds." + name + ".generator", Generator.getGenerator("default").getSimpleName())).split(":"); Class<? extends Generator> generator = Generator.getGenerator(opts[0]); if (opts.length > 1) { String preset = ""; for (int i = 1; i < opts.length; i++) { preset += opts[i] + ":"; } preset = preset.substring(0, preset.length() - 1); options.put("preset", preset); } this.generateLevel(name, seed, generator, options); } } if (this.getDefaultLevel() == null) { String defaultName = this.getPropertyString("level-name", "world"); if (defaultName == null || "".equals(defaultName.trim())) { this.getLogger().warning("level-name cannot be null, using default"); defaultName = "world"; this.setPropertyString("level-name", defaultName); } if (!this.loadLevel(defaultName)) { long seed; String seedString = String.valueOf(this.getProperty("level-seed", System.currentTimeMillis())); try { seed = Long.valueOf(seedString); } catch (NumberFormatException e) { seed = seedString.hashCode(); } this.generateLevel(defaultName, seed == 0 ? System.currentTimeMillis() : seed); } this.setDefaultLevel(this.getLevelByName(defaultName)); } this.properties.save(true); if (this.getDefaultLevel() == null) { this.getLogger().emergency(this.getLanguage().translateString("nukkit.level.defaultError")); this.forceShutdown(); return; } if ((int) this.getConfig("ticks-per.autosave", 6000) > 0) { this.autoSaveTicks = (int) this.getConfig("ticks-per.autosave", 6000); } this.enablePlugins(PluginLoadOrder.POSTWORLD); this.logger.info(TextFormat.LIGHT_PURPLE + "----------------------------------------------------------------------------------"); this.start(); }
From source file:nmsu.cs.DocParser.java
/** * @throws IndexOutOfBoundsException if pubid is not contained in pubid2doc. *///from ww w. j a v a 2s . c o m public int getBugsId2PubId(int bugsid, BidiMap pubid2bugsid) { if (!pubid2bugsid.containsValue(bugsid)) { throw new IndexOutOfBoundsException("Bugsid " + bugsid + " not found in pubid2bugsid " + pubid2bugsid); } int pubid = (Integer) pubid2bugsid.getKey(bugsid); return pubid; }
From source file:org.dkpro.tc.ml.svmhmm.report.SVMHMMOutcomeIDReport.java
@Override public void execute() throws Exception { // load gold and predicted labels loadGoldAndPredictedLabels();/* w w w. j a v a 2 s .co m*/ File testFile = locateTestFile(); // original tokens List<String> originalTokens = SVMHMMUtils.extractOriginalTokens(testFile); // sequence IDs List<Integer> sequenceIDs = SVMHMMUtils.extractOriginalSequenceIDs(testFile); // sanity check if (goldLabels.size() != originalTokens.size() || goldLabels.size() != sequenceIDs.size()) { throw new IllegalStateException("Gold labels, original tokens or sequenceIDs differ in size!"); } File evaluationFolder = getContext().getFolder("", AccessMode.READWRITE); File evaluationFile = new File(evaluationFolder, ID_OUTCOME_KEY); File mappingFile = getContext().getFile(SVMHMMUtils.LABELS_TO_INTEGERS_MAPPING_FILE_NAME, AccessMode.READONLY); BidiMap id2label = SVMHMMUtils.loadMapping(mappingFile); String header = buildHeader(id2label); Properties prop = new SortedKeyProperties(); BidiMap label2id = id2label.inverseBidiMap(); for (int idx = 0; idx < goldLabels.size(); idx++) { String gold = goldLabels.get(idx); String pred = predictedLabels.get(idx); int g = (int) label2id.getKey(gold); int p = (int) label2id.getKey(pred); // we decrement all gold/pred labels by one because the evaluation modules seems to // expect that the numbering starts with 0 which is seemingly a problem for SVMHMM - // thus we decrement all labels and shifting the entire outcome numbering by one g--; p--; prop.setProperty("" + String.format("%05d", idx), p + SEPARATOR_CHAR + g + SEPARATOR_CHAR + THRESHOLD_DUMMY_CONSTANT); } OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(evaluationFile), "utf-8"); prop.store(osw, header); osw.close(); }