/** * Sets our "real" texture values * * <p>TODO: Exception error reporting */ public void setTextureFilenameMapping(HashMap<String, Integer> texmap) throws BlockTypeLoadException { // First the "main" texture if (texmap.containsKey(this.tex)) { this.tex_idx = texmap.get(this.tex); } else { throw new BlockTypeLoadException("No texture mapping found for " + this.tex); } // Now data the data mapping if (this.tex_data != null && this.tex_data.size() > 0) { this.texture_data_map = new HashMap<Byte, Integer>(); for (Map.Entry<Integer, String> entry : this.tex_data.entrySet()) { if (texmap.containsKey(entry.getValue())) { this.texture_data_map.put(entry.getKey().byteValue(), texmap.get(entry.getValue())); } else { throw new BlockTypeLoadException("No texture mapping found for " + entry.getValue()); } } } // Now direction data mapping if (this.tex_direction_int != null && this.tex_direction_int.size() > 0) { this.texture_dir_map = new HashMap<DIRECTION_REL, Integer>(); for (Map.Entry<DIRECTION_REL, String> entry : this.tex_direction_int.entrySet()) { if (texmap.containsKey(entry.getValue())) { this.texture_dir_map.put(entry.getKey(), texmap.get(entry.getValue())); } else { throw new BlockTypeLoadException("No texture mapping found for " + entry.getValue()); } } } }
@org.junit.Test public void StoreCommandVariables() { StoredVariables variables = new StoredVariables(); HashMap<String, String> hVars; String[] key1 = {"var1", "replacedText1"}; String[] key2 = {"Var2", "replacedText2"}; String[] key3 = {"VaR!", "replacedText3"}; variables.storeIfCommandVariable( Globals.variablePrefix + key1[0] + Globals.variableSuffix, key1[1]); variables.storeIfCommandVariable( Globals.variablePrefix + key2[0] + Globals.variableSuffix, key2[1]); variables.storeIfCommandVariable( Globals.variablePrefix + key3[0] + Globals.variableSuffix, key3[1]); hVars = variables.getCurrentVariables(); assertEquals(hVars.size(), 3); assertTrue(hVars.containsKey(key1[0])); assertTrue(hVars.containsKey(key2[0])); assertTrue(hVars.containsKey(key3[0])); assertEquals(hVars.get(key1[0]), key1[1]); assertEquals(hVars.get(key2[0]), key2[1]); assertEquals(hVars.get(key3[0]), key3[1]); }
public void endDocument() throws SAXException { // time to actually set up the edges IntIterator rows = m_edges.rows(); while (rows.hasNext()) { int r = rows.nextInt(); String src = m_edges.getString(r, SRCID); if (!m_nodeMap.containsKey(src)) { throw new SAXException( "Tried to create edge with source node id=" + src + " which does not exist."); } int s = ((Integer) m_nodeMap.get(src)).intValue(); m_edges.setInt(r, SRC, s); String trg = m_edges.getString(r, TRGID); if (!m_nodeMap.containsKey(trg)) { throw new SAXException( "Tried to create edge with target node id=" + trg + " which does not exist."); } int t = ((Integer) m_nodeMap.get(trg)).intValue(); m_edges.setInt(r, TRG, t); } m_edges.removeColumn(SRCID); m_edges.removeColumn(TRGID); // now create the graph m_graph = new Graph(m_nodes, m_edges, m_directed); if (m_graphid != null) m_graph.putClientProperty(ID, m_graphid); }
public int longestConsecutive(int[] num) { HashMap<Integer, Integer> maps = new HashMap<>(); for (int i = 0; i < num.length; ++i) { int n = num[i]; int c = 1; if (maps.containsKey(n)) continue; if (maps.containsKey(n - 1)) { c += maps.get(n - 1); } if (maps.containsKey(n + 1)) { c += maps.get(n + 1); } if (maps.containsKey(n - 1)) { int k = n - maps.get(n - 1); maps.put(k, c); } if (maps.containsKey(n + 1)) { int k = n + maps.get(n + 1); maps.put(k, c); } maps.put(n, c); } int max = 0; for (Integer v : maps.values()) { max = Math.max(max, v); } return max; }
private int getCurrentMaxFallForWeakBlock( int currentY, Entry<ColumnCoord, Integer> entry, int currentMaxFall, int minY) { int tempCurrentMaxFall = 0; for (int y = currentY - 1; true; y--) { Material currentBlockMaterial = world.getBlockAt(entry.getKey().x, y, entry.getKey().z).getType(); if (y < 0) { currentMaxFall = Math.min(1024, currentMaxFall); break; } else if (isMaterialWeak(currentBlockMaterial)) { tempCurrentMaxFall++; } else if (blocks.containsKey(new Location(entry.getKey().x, y, entry.getKey().z))) { currentY = y + 1; break; } else { currentMaxFall = Math.min(tempCurrentMaxFall, currentMaxFall); int tempY = 0; for (tempY = y; tempY >= minY; tempY--) { if (blocks.containsKey(new Location(entry.getKey().x, tempY, entry.getKey().z))) { currentY = tempY; break; } } break; } } return currentMaxFall; }
private void pvp(final Player p, final Player d) { if (pvp.containsKey(p)) if (pvp.get(p).isSync()) pvp.get(p).cancel(); pvp.put( p, new BukkitRunnable() { @Override public void run() { if (pvp.containsKey(p)) pvp.remove(p); } }.runTaskLater(Main.getInstance(), 8 * 20L)); if (pvp.containsKey(d)) if (pvp.get(d).isSync()) pvp.get(d).cancel(); pvp.put( d, new BukkitRunnable() { @Override public void run() { if (pvp.containsKey(d)) pvp.remove(d); } }.runTaskLater(Main.getInstance(), 8 * 20L)); }
@Override public void reduce(Text key, Iterable<HMapStIW> values, Context context) throws IOException, InterruptedException { Iterator<HMapStIW> iter = values.iterator(); HMapStIW map = new HMapStIW(); while (iter.hasNext()) { map.plus(iter.next()); } HMapStFW writeMap = new HMapStFW(); double pmi = 0.0; for (MapKI.Entry<String> entry : map.entrySet()) { String k = entry.getKey(); if (map.get(k) >= 10) { if (wordCounts.containsKey(key.toString()) && wordCounts.containsKey(k)) { int px = wordCounts.get(key.toString()); int py = wordCounts.get(k); pmi = Math.log10(((double) (map.get(k)) / (px * py)) * wordCounts.get("numLines*")); writeMap.put(k, (float) pmi); } } } if (writeMap.size() > 0) { context.write(key, writeMap); } }
@Override public boolean open(HashMap<String, Object> initParams) { wb = new SXSSFWorkbook(10000); dicoLocations = new HashMap<>(); baos = new ByteArrayOutputStream(); ps = new PrintStream(baos); boolean success = true; String dirName; String fileName; if (initParams.containsKey(LoggerParamsNames.DirectoryName.toString())) dirName = initParams.get(LoggerParamsNames.DirectoryName.toString()).toString(); else dirName = System.getProperty("user.dir"); if (initParams.containsKey(LoggerParamsNames.FileName.toString())) fileName = initParams.get(LoggerParamsNames.FileName.toString()).toString(); else fileName = "monfichier.xls"; try { fileOut = new FileOutputStream(dirName + "\\" + fileName); } catch (FileNotFoundException e) { success = false; System.err.println("Logger " + this.getClass().getCanonicalName() + " n'a pu être créé.)"); System.err.println( dirName + "\\" + fileName + " est sans doute ouvert ou n'existe pas (chemin non existant au préalable par exemple)"); } return success; }
private String getUniqueName( DbObject obj, HashMap<String, ? extends SchemaObject> map, String prefix) { String hash = Integer.toHexString(obj.getName().hashCode()).toUpperCase(); String name = null; synchronized (temporaryUniqueNames) { for (int i = 1, len = hash.length(); i < len; i++) { name = prefix + hash.substring(0, i); if (!map.containsKey(name) && !temporaryUniqueNames.contains(name)) { break; } name = null; } if (name == null) { prefix = prefix + hash + "_"; for (int i = 0; ; i++) { name = prefix + i; if (!map.containsKey(name) && !temporaryUniqueNames.contains(name)) { break; } } } temporaryUniqueNames.add(name); } return name; }
public String getHint(String secret, String guess) { HashMap<Character, Integer> secretMap = new HashMap<Character, Integer>(); int bullNum = 0; for (int i = 0; i < secret.length(); i++) { char c = secret.charAt(i); if (guess.charAt(i) == c) bullNum++; if (!secretMap.containsKey(c)) { secretMap.put(c, 1); } else { secretMap.put(c, secretMap.get(c) + 1); } } // count cow int tempCount = 0; for (int i = 0; i < guess.length(); i++) { char c = guess.charAt(i); if (secretMap.containsKey(c)) { if (secretMap.get(c) > 1) { secretMap.put(c, secretMap.get(c) - 1); tempCount++; } else { secretMap.remove(c); tempCount++; } } } return bullNum + "A" + (tempCount - bullNum) + "B"; }
@Override public void sawOpcode(int seen) { if (seen == PUTFIELD) { XField xField = getXFieldOperand(); if (xField != null && xField.getClassDescriptor().equals(getClassDescriptor())) { Item first = stack.getStackItem(0); boolean isPutOfDefaultValue = first.isNull(); // huh?? || first.isInitialParameter(); if (!isPutOfDefaultValue && first.getConstant() != null) { Object constant = first.getConstant(); if (constant instanceof Number && ((Number) constant).intValue() == 0 || constant.equals(Boolean.FALSE)) isPutOfDefaultValue = true; } if (isPutOfDefaultValue) { if (getMethodName().equals("<init>")) transientFieldsSetToDefaultValueInConstructor.add(xField); } else { String nameOfField = getNameConstantOperand(); if (transientFieldsUpdates.containsKey(xField)) { if (getMethodName().equals("<init>")) transientFieldsSetInConstructor.add(xField); else transientFieldsUpdates.put(xField, transientFieldsUpdates.get(xField) + 1); } else if (fieldsThatMightBeAProblem.containsKey(nameOfField)) { try { JavaClass classStored = first.getJavaClass(); if (classStored == null) { return; } double isSerializable = DeepSubtypeAnalysis.isDeepSerializable(classStored); if (isSerializable <= 0.2) { XField f = fieldsThatMightBeAProblem.get(nameOfField); String sig = f.getSignature(); // System.out.println("Field signature: " + sig); // System.out.println("Class stored: " + // classStored.getClassName()); String genSig = "L" + classStored.getClassName().replace('.', '/') + ";"; if (!sig.equals(genSig)) { double bias = 0.0; if (!getMethodName().equals("<init>")) bias = 1.0; int priority = computePriority(isSerializable, bias); fieldWarningList.add( new BugInstance(this, "SE_BAD_FIELD_STORE", priority) .addClass(getThisClass().getClassName()) .addField(f) .addType(genSig) .describe("TYPE_FOUND") .addSourceLine(this)); } } } catch (Exception e) { // ignore it } } } } } }
public int[] intersect(int[] nums1, int[] nums2) { HashMap<Integer, Integer> set = new HashMap<Integer, Integer>(); ArrayList<Integer> res = new ArrayList<Integer>(); for (int i = 0; i < nums1.length; i++) { if (set.containsKey(nums1[i])) { set.put(nums1[i], set.get(nums1[i]) + 1); } else { set.put(nums1[i], 1); } } for (int i = 0; i < nums2.length; i++) { if (set.containsKey(nums2[i])) { res.add(nums2[i]); if (set.get(nums2[i]) > 1) { set.put(nums2[i], set.get(nums2[i]) - 1); } else { set.remove(nums2[i]); } } } Iterator<Integer> iter = res.iterator(); int[] resArray = new int[res.size()]; for (int i = 0; iter.hasNext(); i++) { resArray[i] = iter.next(); } return resArray; }
// Hashmap public boolean isAnagram(String s, String t) { if (s == null && t == null) return true; if (s.length() != t.length()) return false; HashMap<Character, Integer> str = new HashMap<Character, Integer>(); for (int i = 0; i < s.length(); i++) { if (str.containsKey(s.charAt(i))) { str.put(s.charAt(i), str.get(s.charAt(i)) + 1); } else { str.put(s.charAt(i), 1); } } for (int i = 0; i < t.length(); i++) { if (str.containsKey(t.charAt(i))) { str.put(t.charAt(i), str.get(t.charAt(i)) - 1); } else { return false; } } for (Map.Entry<Character, Integer> entry : str.entrySet()) { if (entry.getValue() != 0) { return false; } } return true; }
public List<Integer> findSubstring(String s, String[] words) { ArrayList<Integer> result = new ArrayList<Integer>(); HashMap<String, Integer> dict = new HashMap<String, Integer>(); int wlen = words[0].length(); int totalWords = words.length; for (String w : words) { addToDict(dict, w); } for (int i = 0; i <= s.length() - wlen * totalWords; i++) { HashMap<String, Integer> visited = new HashMap<String, Integer>(); int j = 0; for (; j < totalWords; j++) { String word = s.substring(i + j * wlen, i + (j + 1) * wlen); if (dict.containsKey(word) && (!visited.containsKey(word) || dict.get(word) > visited.get(word))) { addToDict(visited, word); } else { break; } } if (j == totalWords) { result.add(i); } } return result; }
@Test public void test() { String newWord = "爸爸去哪儿"; String nature = "aaaaa"; String str = "上海电力2012年财务报表如下怎爸爸去哪儿么办"; // 增加新词 UserDefineLibrary.insertWord(newWord, nature, 1000); List<Term> parse = ToAnalysis.parse(str); HashMap<String, Term> hs = new HashMap<String, Term>(); for (Term term : parse) { hs.put(term.getName(), term); } Assert.assertTrue(hs.containsKey(newWord)); Assert.assertEquals(hs.get(newWord).natrue().natureStr, nature); // 删除词 UserDefineLibrary.removeWord(newWord); parse = ToAnalysis.parse(str); hs = new HashMap<String, Term>(); for (Term term : parse) { hs.put(term.getName(), term); } Assert.assertTrue(!hs.containsKey(newWord)); }
public static void main(String[] args) { /*HashMap<Integer, List<TestMap>> map = new HashMap<Integer, List<TestMap>>(); List<TestMap> list = new ArrayList<TestMap>(); list.add(new TestMap("1")); list.add(new TestMap("2")); list.add(new TestMap("3")); list.add(new TestMap("4")); list.add(new TestMap("5")); list.add(new TestMap("6")); map.put(1, list); map.put(2, list); System.out.println(map.toString().replaceAll("\\{", "").replaceAll("\\[", "").replaceAll("], ", ";").replaceAll(", ", "_").replaceAll("]}", ""));*/ HashMap<Long, Long> map = new HashMap<Long, Long>(); map.put(11l, 10l); map.put(13l, 12l); map.put(14l, 15l); map.put(17l, 16l); System.out.println(map.containsKey(11l)); System.out.println(map.containsKey(11l)); System.out.println(map.containsKey(12l)); System.out.println(map.containsKey(12l)); System.out.println(map.containsValue(11l)); System.out.println(map.containsValue(11l)); System.out.println(map.containsValue(12l)); System.out.println(map.containsValue(12l)); }
public static void readHiveResult(String uuid, OutputStreamWriter outStream) throws SQLException, IOException { Map stormconf = Utils.readStormConfig(); String hdpConf = (String) stormconf.get("hadoop.conf.dir"); String connstr = (String) stormconf.get("higo.download.offline.conn"); String uname = (String) stormconf.get("higo.download.offline.username"); String passwd = (String) stormconf.get("higo.download.offline.passwd"); MySqlConn conn = new MySqlConn(connstr, uname, passwd); Configuration conf = new Configuration(); HadoopBaseUtils.grabConfiguration(hdpConf, conf); MysqlInfo info = new MysqlInfo(conn); HashMap<String, String> result = info.get(uuid); String exehql = ""; if (result != null && result.containsKey("storedir")) { exehql = result.get("_exehql"); } if (result != null && result.containsKey("storedir") && result.containsKey("cols")) { outStream.write(result.get("cols").replaceAll("\001", ",").replaceAll("\t", ",") + "\n"); AdhocOfflineService.readHiveResult(result.get("storedir"), outStream, conf); } // outStream.write(exehql.replaceAll("\001", ",").replaceAll("\t", // "\t")+"\n"); }
/** Time Complexity: L[0].length() * S compared to S * L Think why use this way */ public ArrayList<Integer> findSubstring(String S, String[] L) { HashMap<String, Integer> need = new HashMap<String, Integer>(); HashMap<String, Integer> has = new HashMap<String, Integer>(); ArrayList<Integer> ans = new ArrayList<Integer>(); for (int i = 0; i < L.length; i++) { need.put(L[i], need.containsKey(L[i]) ? need.get(L[i]) + 1 : 1); } int k = L[0].length(); for (int i = 0; i < k; i++) { has.clear(); int start = i; for (int end = start; end <= S.length() - k; end += k) { String cur = S.substring(end, end + k); if (need.containsKey(cur)) { // NOTE while (has.get(cur) == need.get( cur)) { // NOTE compare with MimimumWindowSubstring, we need get all results, so // we need to compare end_cursor in has and need String temp = S.substring(start, start + k); has.put(temp, has.get(temp) - 1); start += k; } has.put(cur, has.containsKey(cur) ? has.get(cur) + 1 : 1); if ((end - start + k) == L.length * k) { // NOTE ans.add(start); } } else { has.clear(); start = end + k; } } } return ans; }
public static void addNewStickerSet(final TLRPC.TL_messages_stickerSet set) { if (stickerSetsById.containsKey(set.set.id) || stickerSetsByName.containsKey(set.set.short_name)) { return; } stickerSets.add(0, set); stickerSetsById.put(set.set.id, set); stickerSetsByName.put(set.set.short_name, set); for (int a = 0; a < set.documents.size(); a++) { TLRPC.Document document = set.documents.get(a); stickersById.put(document.id, document); } for (int a = 0; a < set.packs.size(); a++) { TLRPC.TL_stickerPack stickerPack = set.packs.get(a); stickerPack.emoticon = stickerPack.emoticon.replace("\uFE0F", ""); ArrayList<TLRPC.Document> arrayList = allStickers.get(stickerPack.emoticon); if (arrayList == null) { arrayList = new ArrayList<>(); allStickers.put(stickerPack.emoticon, arrayList); } for (int c = 0; c < stickerPack.documents.size(); c++) { Long id = stickerPack.documents.get(c); if (!stickersByEmoji.containsKey(id)) { stickersByEmoji.put(id, stickerPack.emoticon); } arrayList.add(stickersById.get(id)); } } loadHash = calcStickersHash(stickerSets); NotificationCenter.getInstance().postNotificationName(NotificationCenter.stickersDidLoaded); StickersQuery.loadStickers(false, true); }
public Object getClassInstance(String classname, HashMap<Class<?>, Object> parameters) { if (entryList.containsKey(classname.toLowerCase())) { Object Interface; final String className = entryList.get(classname.toLowerCase()); // check whether an instance for given type is already created if (!instanceCache.containsKey(classname.toLowerCase())) { // not yet cached->create instance and add to cache try { if (parameters != null && parameters.size() > 0) { final Set<Class<?>> cs = parameters.keySet(); final Class<?>[] classes = cs.toArray(new Class[cs.size()]); final Object[] arguments = parameters.values().toArray(); final Constructor<?> co = Class.forName(className).getConstructor(classes); Interface = co.newInstance(arguments); } else { Interface = Class.forName(className).newInstance(); } instanceCache.put(classname.toLowerCase(), Interface); } catch (final Exception e) { logger.error(e.getMessage(), e); return null; } } else { // is already cached then give cached instance back Interface = instanceCache.get(classname.toLowerCase()); } return Interface; } return null; }
/** * Breadth first traversal of the topology DAG * * @param topologies * @param td * @param spouts * @return A partial ordering of components */ private Queue<Component> bfs(Topologies topologies, TopologyDetails td, List<Component> spouts) { // Since queue is a interface Queue<Component> ordered__Component_list = new LinkedList<Component>(); HashMap<String, Component> visited = new HashMap<String, Component>(); /* start from each spout that is not visited, each does a breadth-first traverse */ for (Component spout : spouts) { if (!visited.containsKey(spout.id)) { Queue<Component> queue = new LinkedList<Component>(); queue.offer(spout); while (!queue.isEmpty()) { Component comp = queue.poll(); visited.put(comp.id, comp); ordered__Component_list.add(comp); List<String> neighbors = new ArrayList<String>(); neighbors.addAll(comp.children); neighbors.addAll(comp.parents); for (String nbID : neighbors) { if (!visited.containsKey(nbID)) { Component child = topologies.getAllComponents().get(td.getId()).get(nbID); queue.offer(child); } } } } } return ordered__Component_list; }
/** * Method for assigned generating UUID to ComponentConnectionID. * * @return id ComponentConnectionID. */ private String getUniqueID() { String id; do { id = UUID.randomUUID().toString(); } while (connectionTable.containsKey(id) || componentStateList.containsKey(id)); return id; }
private int getMaximumFallDistance( Map<ColumnCoord, Integer> columnsMinHeight, Map<ColumnCoord, Integer> columnsMaxHeight) { int currentMaxFall = Integer.MAX_VALUE; for (Map.Entry<ColumnCoord, Integer> entry : columnsMaxHeight.entrySet()) { // Loop columns in each X&Z coordinate int minY = columnsMinHeight.get(entry.getKey()); int maxY = entry.getValue(); for (int currentY = maxY; currentY >= minY; currentY--) { // Loop all blocks in a XZ-column from top to bottom if (isMaterialWeak( world.getBlockAt(entry.getKey().x, currentY - 1, entry.getKey().z).getType())) { currentMaxFall = getCurrentMaxFallForWeakBlock(currentY, entry, currentMaxFall, minY); } else if (blocks.containsKey(new Location(entry.getKey().x, currentY, entry.getKey().z))) { if (!blocks.containsKey(new Location(entry.getKey().x, currentY - 1, entry.getKey().z))) { return 0; } } } } if (currentMaxFall > 1024) { return 0; } return currentMaxFall; }
public void store(String packageName) { Log.d("HarvestJournal", "store"); HashMap sessions; if (data.containsKey(packageName)) { sessions = (HashMap) data.get(packageName); } else { sessions = new HashMap(); data.put(packageName, sessions); } Long started = settings.getStarted(null); HarvestEntry entry; if (sessions.containsKey(started)) { entry = (HarvestEntry) sessions.get(started); } else { entry = new HarvestEntry(packageName); entry.started = started; sessions.put(started, entry); } Long delta = settings.getRealNowSeconds() - lastStored; if (delta > HarvestSettings.INTERVAL) { delta = HarvestSettings.INTERVAL; } entry.increment(delta); Log.d( "HarvestJournal", String.format("%s %d %d", entry.packageName, entry.started, entry.duration)); display(); }
public static boolean isAnagram(String one, String two) { HashMap<Character, Integer> temp = new HashMap<Character, Integer>(); if (one.length() != two.length()) { return false; } for (int i = 0; i < one.length(); i++) { if (temp.containsKey(one.charAt(i))) { Integer num = temp.get(one.charAt(i)); num++; temp.put(one.charAt(i), num); } else { temp.put(one.charAt(i), 1); } } for (int i = 0; i < two.length(); i++) { if (temp.containsKey(two.charAt(i))) { Integer num = temp.get(two.charAt(i)); num--; if (num < 0) { return false; } else { temp.put(two.charAt(i), num); } } else { return false; } } return true; }
public static boolean findShortestPath(Node a, Node b, HashMap<Node, Node> path) { Node prev = null; if (a == b) { prev = a; } // Starting node has no prev (unless start equals end) path.put(a, prev); LinkedList<Node> q = new LinkedList<Node>(); q.add(a); while (!q.isEmpty()) { Node r = q.removeFirst(); for (Node c : r.adj) { // Use path datastructure to track whether nodes are visited if (!path.containsKey(c)) { path.put(c, r); } } } if (!path.containsKey(b)) { return false; } return true; }
/** * Override the update of Observer, After notify event * * @param Observable o * @param Object arg */ @Override public void update(Observable o, Object arg) { if (o == view) { if (arg != null && arg.getClass().getName().equals("java.lang.String") == true) { String[] args = ((String) arg).split(" "); boolean dos = false; String s = null; for (int i = 0; i < args.length; i++) { if (commandsMap.containsKey(s) == true && dos == false) { dos = true; } else { if (dos == false) { if (s == null) s = args[i]; else if (s != null) s = s + " " + args[i]; } } } if (commandsMap.containsKey(s) == true) { commandsMap.get(s).doCommand(args); } else { view.displayString("Error"); } } } else if (o == model) { if (arg != null && arg.getClass().getName().equals("java.lang.String") == true) { // System.out.println("presenter update = "+(String)arg); if (((String) arg).contains("has")) { view.displayClient((String) arg); } else { view.displayString((String) arg); } } } }
public static List<List<Integer>> threeSum2(int[] nums, int target) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if (nums == null || nums.length < 3) { return res; } Arrays.sort(nums); for (int i = 0; i < nums.length; i++) { int subTarget = target - nums[i]; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int j = i + 1; j < nums.length; j++) { if (map.containsKey(subTarget - nums[j])) { for (int k = 0; k < map.get(subTarget - nums[j]); k++) { List<Integer> list = new ArrayList<Integer>(); list.add(nums[i]); list.add(subTarget - nums[j]); list.add(nums[j]); res.add(list); } } else if (map.containsKey(nums[j])) { map.put(nums[j], map.get(nums[j]) + 1); } else { map.put(nums[j], 1); } } } return res; }
public void loadtfidf(LinkedHashMap<String, Ngram> orderedGrams) { HashMap<String, Double> idf = ic.getIdfCollection(); for (String s : orderedGrams.keySet()) { // defining size of ngrams to be counted, used with idfs for special // ngram size Ngram temp = orderedGrams.get(s); if (config.prop.containsKey("extractSize")) { if (idf.containsKey(s)) { temp.setSingleTfidf(idf.get(s) * temp.frequency); } else { temp.setSingleTfidf(0.1 * temp.frequency); } } else { // when size of ngram not defined we count each word // separately for (int i = 0; i < temp.gram.length; i++) { if (idf.containsKey(temp.gram[i])) { temp.tfidf[i] += idf.get(temp.gram[i]) * temp.frequency; } else { temp.tfidf[i] += 0.1 * temp.frequency; } } } } }
/** * Calculate spearmans rho on the wordSim353 dataset (or any other dataset with similar * formatting). * * @param wordSimPairs * @param wordEmbeddings * @return * @throws Exception */ private static double spearmansScore( List<Pair<Pair<String, String>, Float>> wordSimPairs, HashMap<String, float[]> wordEmbeddings) throws Exception { final double[] predictions = new double[wordSimPairs.size()]; final double[] labels = new double[wordSimPairs.size()]; int pairNum = 0; for (Pair<Pair<String, String>, Float> wordPair : wordSimPairs) { // Find the cosine of the word embeddings. String word1 = wordPair.getFirst().getFirst(); String word2 = wordPair.getFirst().getSecond(); if (wordEmbeddings.containsKey(word1) && wordEmbeddings.containsKey(word2)) { predictions[pairNum] = cosineSimilarity(wordEmbeddings.get(word1), wordEmbeddings.get(word2)); } else { // Unmodelled words have 0.5 similarity. predictions[pairNum] = 0.5; } labels[pairNum] = wordPair.getSecond(); pairNum++; } NaturalRanking ranking = new NaturalRanking(NaNStrategy.REMOVED); SpearmansCorrelation spearman = new SpearmansCorrelation(ranking); return spearman.correlation(predictions, labels); }