javatips.net counter

Java Examples for java.util.HashMap

The following java examples will help you to understand the usage of java.util.HashMap. These source code samples are taken from different open source projects.

Example 1
Project: ijoomer-adv-sdk-master  File: SobiproSearchResultActivity.java View source code
/**
	 * This method is used to get intent data
	 */
@SuppressWarnings("unchecked")
public void getIntentData() {
    try {
        IN_POS = getIntent().getIntExtra("IN_POS", 0);
        optionCriteria = getIntent().getStringExtra("IN_OPTIONCRITERIA");
        searchKey = getIntent().getStringExtra("IN_SEARCH_KEY");
        section_id = getIntent().getStringExtra("IN_SECTION_ID");
        searchField = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("IN_SEARCHFIELD");
        IN_FEATUREDFIRST = getIntent().getStringExtra("IN_FEATUREDFIRST");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 2
Project: android_platform_libcore-master  File: HashMapTest.java View source code
/**
     * java.util.HashMap#HashMap(int, float)
     */
public void test_ConstructorIF() {
    // Test for method java.util.HashMap(int, float)
    HashMap hm2 = new HashMap(5, (float) 0.5);
    assertEquals("Created incorrect HashMap", 0, hm2.size());
    try {
        new HashMap(0, 0);
        fail("IllegalArgumentException expected");
    } catch (IllegalArgumentException e) {
    }
    HashMap empty = new HashMap(0, 0.75f);
    assertNull("Empty hashtable access", empty.get("nothing"));
    empty.put("something", "here");
    assertTrue("cannot get element", empty.get("something") == "here");
}
Example 3
Project: java8-tutorial-master  File: Maps1.java View source code
public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    for (int i = 0; i < 10; i++) {
        map.putIfAbsent(i, "val" + i);
    }
    map.forEach(( id,  val) -> System.out.println(val));
    map.computeIfPresent(3, ( num,  val) -> val + num);
    // val33
    System.out.println(map.get(3));
    map.computeIfPresent(9, ( num,  val) -> null);
    // false
    System.out.println(map.containsKey(9));
    map.computeIfAbsent(23,  num -> "val" + num);
    // true
    System.out.println(map.containsKey(23));
    map.computeIfAbsent(3,  num -> "bam");
    // val33
    System.out.println(map.get(3));
    // not found
    System.out.println(map.getOrDefault(42, "not found"));
    map.remove(3, "val3");
    // val33
    System.out.println(map.get(3));
    map.remove(3, "val33");
    // null
    System.out.println(map.get(3));
    map.merge(9, "val9", ( value,  newValue) -> value.concat(newValue));
    // val9
    System.out.println(map.get(9));
    map.merge(9, "concat", ( value,  newValue) -> value.concat(newValue));
    // val9concat
    System.out.println(map.get(9));
}
Example 4
Project: open-mika-master  File: AbstractMapTest.java View source code
/**
     * @tests java.util.AbstractMap#keySet()
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "Class is abstract. Functionality tested in subclasses for example in java.util.HashMap.",
        method = "keySet",
        args = {}
    )
     */
public void test_keySet() {
    AbstractMap map1 = new HashMap(0);
    assertSame("HashMap(0)", map1.keySet(), map1.keySet());
    AbstractMap map2 = new HashMap(10);
    assertSame("HashMap(10)", map2.keySet(), map2.keySet());
    Map map3 = Collections.EMPTY_MAP;
    assertSame("EMPTY_MAP", map3.keySet(), map3.keySet());
    AbstractMap map4 = new IdentityHashMap(1);
    assertSame("IdentityHashMap", map4.keySet(), map4.keySet());
    AbstractMap map5 = new LinkedHashMap(122);
    assertSame("LinkedHashMap", map5.keySet(), map5.keySet());
    AbstractMap map6 = new TreeMap();
    assertSame("TreeMap", map6.keySet(), map6.keySet());
    AbstractMap map7 = new WeakHashMap();
    assertSame("WeakHashMap", map7.keySet(), map7.keySet());
}
Example 5
Project: magnificent-mileage-master  File: TravelModeWrapperTest.java View source code
@Test
public void testToTraverseMode() {
    Map<TravelMode, TraverseMode> modeMap = new HashMap<TravelMode, TraverseMode>();
    modeMap.put(TravelMode.BICYCLE, TraverseMode.BICYCLE);
    modeMap.put(TravelMode.CAR, TraverseMode.CAR);
    modeMap.put(TravelMode.CUSTOM_MOTOR_VEHICLE, TraverseMode.CUSTOM_MOTOR_VEHICLE);
    modeMap.put(TravelMode.WALK, TraverseMode.WALK);
    modeMap.put(TravelMode.ANY_TRAIN, TraverseMode.TRAINISH);
    modeMap.put(TravelMode.ANY_TRANSIT, TraverseMode.TRANSIT);
    for (TravelMode travelMode : modeMap.keySet()) {
        TraverseMode expectedTraverseMode = modeMap.get(travelMode);
        TraverseMode actualTraverseMode = (new TravelModeWrapper(travelMode)).toTraverseMode();
        assertEquals(expectedTraverseMode, actualTraverseMode);
    }
}
Example 6
Project: spring4-showcase-master  File: PropertySourceTest.java View source code
@Test
public void test2() throws IOException {
    Map<String, Object> map = new HashMap<>();
    map.put("encoding", "gbk");
    PropertySource propertySource1 = new MapPropertySource("map", map);
    ResourcePropertySource propertySource2 = new ResourcePropertySource("resource", "classpath:resources.properties");
    CompositePropertySource compositePropertySource = new CompositePropertySource("composite");
    compositePropertySource.addPropertySource(propertySource1);
    compositePropertySource.addPropertySource(propertySource2);
    System.out.println(compositePropertySource.getProperty("encoding"));
}
Example 7
Project: sonar-java-master  File: DiamondOperatorCheck_java_7.java View source code
void foo() {
    List<Object> myList;
    // Compliant
    myList = new ArrayList<>();
    // Noncompliant [[sc=27;ec=35]]
    myList = new ArrayList<Object>();
    // Compliant
    List<String> strings1 = new ArrayList<>();
    // Noncompliant [[sc=42;ec=50]]
    List<String> strings2 = new ArrayList<String>();
    // Compliant
    Map<String, List<Integer>> map1 = new HashMap<>();
    // Noncompliant [[sc=49;ec=71]]
    Map<String, List<Integer>> map2 = new HashMap<String, List<Integer>>();
    // Compliant
    List myOtherList = new ArrayList<Object>();
    // Compliant
    new A().myList1 = new ArrayList<>();
    // Noncompliant [[sc=36;ec=44]]
    new A().myList1 = new ArrayList<Object>();
    List<Object>[] myArrayOfList = new List[10];
    // Compliant
    myArrayOfList[0] = new ArrayList<>();
    // Noncompliant [[sc=37;ec=45]]
    myArrayOfList[1] = new ArrayList<Object>();
    // Compliant
    new ArrayList<Object>().add(new Object());
    // Noncompliant [[sc=34;ec=42]]
    ((List<Object>) new ArrayList<Object>()).isEmpty();
    // Compliant
    ((List<Object>) new ArrayList<>()).isEmpty();
    Iterator<Object> iterator = new // Compliant - anonymous classes requires to be typed
    Iterator<Object>() {
    };
    // Compliant
    MyUnknownVariable = new ArrayList<Object>();
}
Example 8
Project: FeedMeAndroid-master  File: Pay.java View source code
public static void makePayment() {
    Stripe.apiKey = "L8px8dWKTJmab3qzAuq7Vh4hwp3sXbK4";
    Map<String, Object> chargeMap = new HashMap<String, Object>();
    chargeMap.put("amount", 100);
    chargeMap.put("currency", "usd");
    Map<String, Object> cardMap = new HashMap<String, Object>();
    cardMap.put("number", "4242424242424242");
    cardMap.put("exp_month", 12);
    cardMap.put("exp_year", 2012);
    chargeMap.put("card", cardMap);
    try {
        Charge charge = Charge.create(chargeMap);
        System.out.println(charge);
    } catch (StripeException e) {
        e.printStackTrace();
    }
}
Example 9
Project: extension-aws-master  File: ReplacerTest.java View source code
public void testReplacer() throws Exception {
    SearcherManager manager = (SearcherManager) getBean("searcherManager");
    Replacer replacer = new Replacer();
    replacer.setCatalogId("system");
    replacer.setAlwaysReplace(true);
    replacer.setSearcherManager(manager);
    String code = "${one}/${longvariable}/${user.email}/${notfound}/${two}/${user.id}${nogap1}${nogap2}";
    Map vars = new HashMap();
    vars.put("user", "admin");
    vars.put("one", "Uno");
    vars.put("nogap1", "123");
    vars.put("nogap2", "456");
    vars.put("two", "TOOOOLONG");
    vars.put("longvariable", "short");
    String returned = replacer.replace(code, vars);
    assertEquals("[email protected]//TOOOOLONG/admin123456", returned);
}
Example 10
Project: polly-master  File: PHCNPasteService.java View source code
@Override
public String doPaste(String message) throws IOException {
    Map<String, String> properties = new HashMap<String, String>(10);
    //$NON-NLS-1$ //$NON-NLS-2$
    properties.put("language", "");
    //$NON-NLS-1$ //$NON-NLS-2$
    properties.put("blppassword", "");
    //$NON-NLS-1$
    properties.put("input", message);
    //$NON-NLS-1$
    PostResult pr = this.postRequest(new URL("http://paste.phcn.ws/#"), properties);
    Matcher m = PATTERN.matcher(pr.getResultString());
    if (!m.find()) {
        //$NON-NLS-1$
        throw new IOException("invalid result");
    }
    return pr.getResultString().substring(m.start(), m.end());
}
Example 11
Project: sitebricks-master  File: ShowIfWidgetTest.java View source code
@Test(dataProvider = EXPRESSIONS_AND_EVALS)
public final void hideChildren(String expression, boolean should) {
    final boolean[] run = new boolean[1];
    WidgetChain mockChain = new ProceedingWidgetChain() {

        @Override
        public void render(Object bound, Respond respond) {
            run[0] = true;
        }
    };
    //try to render widget
    new ShowIfWidget(mockChain, expression, new MvelEvaluator()).render(new HashMap<String, Object>() {

        {
            put("visible", true);
        }
    }, RespondersForTesting.newRespond());
    assert run[0] == should : "ShowIf did not do as it should " + should;
}
Example 12
Project: Katari-master  File: ModuleWithEntryPointsAndWebletsTest.java View source code
@SuppressWarnings("deprecation")
public void testInit() {
    Map<String, ServletAndParameters> entryPoints;
    entryPoints = new HashMap<String, ServletAndParameters>();
    Map<String, String> weblets = new HashMap<String, String>();
    ModuleWithEntryPointsAndWeblets module;
    module = new ModuleWithEntryPointsAndWeblets(entryPoints, weblets);
    ModuleContext context = createMock(ModuleContext.class);
    context.registerEntryPoints(entryPoints);
    context.registerWeblets(weblets);
    replay(context);
    module.init(context);
    verify(context);
}
Example 13
Project: dk-master  File: IColorReportServiceImplTest.java View source code
@Test
public void testColorInvestReport() {
    Map parameterMap = new HashMap();
    parameterMap.put("investStartDate", "2014-01-01");
    parameterMap.put("investEndDate", "2014-10-13");
    PageDo page = new PageDo();
    page = colorReportService.queryColorInvest(parameterMap, page);
    List<Map<String, Object>> l = page.getPage();
    for (Map<String, Object> map : l) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            System.out.println("key:" + entry.getKey() + " / " + entry.getValue());
        }
    }
}
Example 14
Project: NucleusFramework-master  File: AgentMapTest.java View source code
@Test
public void testMap() {
    AgentMap<String, ISubscriberAgent> map = new AgentMap<String, ISubscriberAgent>() {

        Map<String, ISubscriberAgent> internalMap = new HashMap<>(10);

        @Override
        protected Map<String, ISubscriberAgent> map() {
            return internalMap;
        }
    };
    DisposableAgent agent1 = new DisposableAgent() {
    };
    DisposableAgent agent2 = new DisposableAgent() {
    };
    DisposableAgent agent3 = new DisposableAgent() {
    };
    new MapRunnable<>(map, "a", "b", "c", agent1, agent2, agent3).run();
    map.clear();
    map.put("test", agent1);
    assertEquals(1, map.size());
    agent1.dispose();
    assertEquals(0, map.size());
}
Example 15
Project: nmonvisualizer-master  File: XMLParserHelper.java View source code
public static Map<String, String> parseAttributes(String unparsedAttributes) {
    if ((unparsedAttributes == null) || "".equals(unparsedAttributes)) {
        return java.util.Collections.emptyMap();
    }
    String[] parts = ATTRIBUTE_SPLIITTER.split(unparsedAttributes);
    int size = parts.length / 2;
    Map<String, String> attributes = new java.util.HashMap<String, String>(size);
    // drop odd numbered end index from array
    size *= 2;
    for (int i = 0; i < size; ) {
        attributes.put(DataHelper.newString(parts[i++].trim()), DataHelper.newString(parts[i++].trim()));
    }
    return attributes;
}
Example 16
Project: SideScrollerGDW2012-Max-master  File: WebstartMuffin.java View source code
/**
	 * @see org.newdawn.slick.muffin.Muffin#saveFile(java.util.HashMap, java.lang.String)
	 */
public void saveFile(HashMap scoreMap, String fileName) throws IOException {
    PersistenceService ps;
    BasicService bs;
    URL configURL;
    try {
        ps = (PersistenceService) ServiceManager.lookup("javax.jnlp.PersistenceService");
        bs = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService");
        URL baseURL = bs.getCodeBase();
        // System.out.println("CodeBase was " + baseURL);
        configURL = new URL(baseURL, fileName);
    } catch (Exception e) {
        Log.error(e);
        throw new IOException("Failed to save state: ");
    }
    try {
        ps.delete(configURL);
    } catch (Exception e) {
        Log.info("No exisiting Muffin Found - First Save");
    }
    try {
        // 1024 bytes for our data
        ps.create(configURL, 1024);
        FileContents fc = ps.get(configURL);
        DataOutputStream oos = new DataOutputStream(fc.getOutputStream(false));
        // scroll through hashMap and write key and value to file
        // get the keys
        Set keys = scoreMap.keySet();
        // get values using keys
        for (Iterator i = keys.iterator(); i.hasNext(); ) {
            String key = (String) i.next();
            oos.writeUTF(key);
            if (fileName.endsWith("Number")) {
                double value = ((Double) scoreMap.get(key)).doubleValue();
                oos.writeDouble(value);
            } else {
                String value = (String) scoreMap.get(key);
                oos.writeUTF(value);
            }
        }
        oos.flush();
        oos.close();
    } catch (Exception e) {
        Log.error(e);
        throw new IOException("Failed to store map of state data");
    }
}
Example 17
Project: sosies-generator-master  File: JsonFailuresOutput.java View source code
@Override
public void write(JSONObject object) {
    super.write(object);
    failuresDict = new HashMap<>();
    int id = 0;
    for (Transformation t : getTransformations()) {
        if (t.getFailures() != null && t.getFailures().size() > 0) {
            for (String s : t.getFailures()) if (!failuresDict.containsKey(s) && s != null) {
                failuresDict.put(s, id++);
            }
        }
    }
    try {
        object.put(FAILURES_DICTIONARY, failuresDict);
    } catch (JSONException e) {
        throw new PersistenceException(e);
    }
}
Example 18
Project: sysart-itext-master  File: BookmarksTest.java View source code
@Test
public void testNoBreakSpace() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();
    writer.setPageEvent(new PdfPageEventHelper() {

        public void onParagraph(PdfWriter writer, Document document, float position) {
            PdfContentByte cb = writer.getDirectContent();
            PdfDestination destination = new PdfDestination(PdfDestination.FITH, position);
            new PdfOutline(cb.getRootOutline(), destination, TITLE);
        }
    });
    document.add(new Paragraph("Hello World"));
    document.close();
    // read bookmark back
    PdfReader r = new PdfReader(baos.toByteArray());
    List bookmarks = SimpleBookmark.getBookmark(r);
    assertEquals("bookmark size", 1, bookmarks.size());
    HashMap<String, Object> b = (HashMap<String, Object>) bookmarks.get(0);
    String title = (String) b.get("Title");
    assertEquals("bookmark title", TITLE, title);
}
Example 19
Project: Mint-Programming-Language-master  File: ViewStrings.java View source code
@Override
public Pointer apply(SmartList<Pointer> args) throws MintException {
    short i = 0;
    while (i < Short.MAX_VALUE) {
        try {
            HashMap<Integer, String> strs = Heap.strings;
            if (strs == null) {
                return EMPTY_LIST;
            }
            Table tbl = new Table();
            ArrayList<Integer> keys = new ArrayList<Integer>();
            Set<Integer> s = strs.keySet();
            for (int element : s) {
                keys.add(element);
            }
            s = null;
            for (int key : keys) {
                SmartList<Pointer> pair = new SmartList<Pointer>();
                pair.add(new Pointer(Constants.INT_TYPE, key));
                pair.add(Heap.allocateString(strs.get(key)));
                tbl.addBinding(pair);
            }
            return Heap.allocateTable(tbl);
        } catch (Throwable t) {
        }
        ++i;
    }
    try {
        return Heap.allocateString(Heap.strings.toString());
    } catch (Throwable t) {
        return ChangeString.ERROR;
    }
}
Example 20
Project: LambdaDojo-master  File: S406StreamInsteadOfFor.java View source code
private void wordCount() {
    List<String> sentences = Arrays.asList("Peter Piper picked", "a peck of pickled peppers.", "A peck of pickled peppers", "Peter Piper picked. ", "If Peter Piper picked", "a peck of pickled peppers,", "Where's the peck of pickled peppers", "Peter Piper picked? ");
    Map<String, Integer> result = new HashMap<>();
    for (String sentence : sentences) {
        String[] splitedSentence = sentence.split("[\\.,\\? ]");
        for (String word : splitedSentence) {
            String lowerWord = word.toLowerCase();
            int count = result.getOrDefault(lowerWord, 0);
            result.put(lowerWord, count + 1);
        }
    }
    System.out.println(result);
}
Example 21
Project: bigtable-sql-master  File: EntryPanelManager.java View source code
public void init(ISyntaxHighlightTokenMatcherFactory syntaxHighlightTokenMatcherFactory, ToolsPopupAccessor tpa) {
    HashMap props = new HashMap();
    props.put(IParserEventsProcessorFactory.class.getName(), null);
    if (null != syntaxHighlightTokenMatcherFactory) {
        props.put(ISyntaxHighlightTokenMatcherFactory.class.getName(), syntaxHighlightTokenMatcherFactory);
    }
    if (null != tpa) {
        props.put(ToolsPopupAccessor.class.getName(), tpa);
    }
    _entry = _session.getApplication().getSQLEntryPanelFactory().createSQLEntryPanel(_session, props);
    _component = _entry.getTextComponent();
    if (false == _entry.getDoesTextComponentHaveScroller()) {
        _component = new JScrollPane(_entry.getTextComponent());
        _component.setBorder(BorderFactory.createEmptyBorder());
    }
    new UndoHandlerImpl(_session.getApplication(), _entry);
}
Example 22
Project: hci-2011-2-master  File: Util.java View source code
public static List<? extends Map<String, ?>> getMapped(List<?> objects, String[] desired_fields) {
    ArrayList<Map<String, ?>> list = new ArrayList<Map<String, ?>>();
    for (Object object : objects) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        Class<? extends Object> c = object.getClass();
        for (Field field : c.getFields()) {
            Annotation[] ann = (Annotation[]) field.getAnnotations();
            for (Annotation annotation : ann) {
                if (annotation instanceof Element || annotation instanceof Attribute) {
                    try {
                        boolean is_in = false;
                        for (String desired_field : desired_fields) {
                            if (desired_field.equals(field.getName())) {
                                is_in = true;
                                break;
                            }
                        }
                        if (is_in) {
                            map.put(field.getName(), field.get(object));
                        }
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        list.add(map);
    }
    return list;
}
Example 23
Project: tdq-studio-se-master  File: ModeIndicatorImplTest.java View source code
/**
     * Test method for [email protected] [email protected]Computation()} .
     */
@Test
public void testfinalizeComputation() {
    HashMap<Object, Long> tempMap = new HashMap<Object, Long>();
    //$NON-NLS-1$
    tempMap.put("2", 2L);
    //$NON-NLS-1$
    tempMap.put("1", 1L);
    //$NON-NLS-1$
    tempMap.put("33", 3L);
    //$NON-NLS-1$
    tempMap.put("bb", 4L);
    //$NON-NLS-1$
    tempMap.put("5a", 5L);
    //$NON-NLS-1$
    tempMap.put("8", 8L);
    tempMap.put(null, 7L);
    modeIndicator.setValueToFreq(tempMap);
    ((ModeIndicatorImpl) modeIndicator).setUsedMapDBMode(false);
    this.modeIndicator.finalizeComputation();
    //$NON-NLS-1$
    Assert.assertTrue("8".equals(modeIndicator.getMode()));
    tempMap.put(null, 9L);
    modeIndicator.setValueToFreq(tempMap);
    this.modeIndicator.finalizeComputation();
    Assert.assertTrue(modeIndicator.getMode() == null);
}
Example 24
Project: btpka3.github.com-master  File: MyServ001Impl.java View source code
public Person get() {
    Person person = new Person();
    person.setName("xxx");
    person.setAge(99);
    try {
        person.setImageData(FileUtils.readFileToByteArray(new File(Person.class.getResource("ZhuGeLiang.jpg").getFile())));
    } catch (IOException e) {
        e.printStackTrace();
    }
    List<String> ability = new ArrayList<String>();
    ability.add("AA");
    ability.add("BB");
    person.setAbility(ability);
    Map<String, String> extraInfo = new HashMap<String, String>();
    extraInfo.put("001", "aaa");
    extraInfo.put("002", "bbb");
    person.setExtraInfo(extraInfo);
    //person.setPartner(person);
    System.out.println("====get()=====");
    System.out.println("" + person);
    return person;
}
Example 25
Project: ecologylabFundamental-master  File: ConfParser.java View source code
public HashMap<String, String> parse() throws FileNotFoundException {
    confMap = new HashMap<String, String>();
    if (!confFile.exists() || !confFile.canRead()) {
        System.err.println("Failed to parse conf file: " + confFile);
        throw new FileNotFoundException();
    }
    //go line by line and add to the hash map if it's not a comment;
    Scanner scanner = new Scanner(confFile);
    scanner.useDelimiter("=|\\n");
    while (scanner.hasNextLine()) {
        //ignore comments
        if (scanner.findInLine("#") != null) {
            scanner.nextLine();
            continue;
        }
        try {
            String key = scanner.next().trim();
            String value = scanner.next().trim();
            System.out.println(key + ": " + value);
            confMap.put(key, value);
        } catch (NoSuchElementException e) {
            break;
        }
    }
    return confMap;
}
Example 26
Project: geotoolkit-master  File: MapToStringConverterTest.java View source code
@Test
public void testConvert() {
    final WPSObjectConverter converter = WPSConverterRegistry.getInstance().getConverter(Map.class, String.class);
    final Map<String, Object> map = new HashMap<>();
    map.put("keyMap", "myValue");
    map.put("keyDouble", 10.5);
    map.put("keyInt", 2);
    map.put("10,20,30,40", "100");
    final List<Double> extentValues = new ArrayList<>();
    extentValues.add(-180.0);
    extentValues.add(-90.0);
    extentValues.add(180.0);
    extentValues.add(90.0);
    map.put("keyExtent", extentValues);
    final String convertedMap = (String) converter.convert(map, null);
    assertNotNull(convertedMap);
    assertEquals("{\"keyMap\":\"myValue\",\"10,20,30,40\":\"100\",\"keyExtent\":[-180.0,-90.0,180.0,90.0],\"keyInt\":2,\"keyDouble\":10.5}", convertedMap);
}
Example 27
Project: alien4cloud-master  File: MockLocationConfigurerFactory.java View source code
public ILocationConfiguratorPlugin newInstance(String locationType) {
    if (MockOrchestratorFactory.OPENSTACK.equals(locationType)) {
        return applicationContext.getBean(MockOpenStackLocationConfigurer.class);
    }
    if (MockOrchestratorFactory.AWS.equals(locationType)) {
        return applicationContext.getBean(MockAmazonLocationConfigurer.class);
    }
    return new ILocationConfiguratorPlugin() {

        @Override
        public List<PluginArchive> pluginArchives() {
            return new ArrayList<>();
        }

        @Override
        public List<String> getResourcesTypes() {
            return new ArrayList<>();
        }

        @Override
        public Map<String, MatchingConfiguration> getMatchingConfigurations() {
            return new HashMap<>();
        }

        @Override
        public List<LocationResourceTemplate> instances(ILocationResourceAccessor resourceAccessor) {
            return null;
        }
    };
}
Example 28
Project: avaje-ebeanorm-master  File: RawJdbcHstoreTest.java View source code
@Test
public void test() throws SQLException {
    Transaction txn = Ebean.beginTransaction();
    try {
        Connection connection = txn.getConnection();
        String insert = "update p_customer set tags = ? where id = 1";
        PreparedStatement pstmt1 = connection.prepareStatement(insert);
        Map<String, String> map = new HashMap<>();
        map.put("one", "123123");
        map.put("two", "hello");
        pstmt1.setObject(1, map);
        int rows = pstmt1.executeUpdate();
        System.out.println("updated rows " + rows);
        String sql = "select id, name, tags from p_customer";
        PreparedStatement pstmt = connection.prepareStatement(sql);
        ResultSet rset = pstmt.executeQuery();
        while (rset.next()) {
            Long id = rset.getLong(1);
            String name = rset.getString(2);
            Object tags = rset.getObject(3);
            System.out.println("rows:" + id + " " + name + " " + tags);
        }
    } finally {
        txn.end();
    }
}
Example 29
Project: org.eclipse.ecr-master  File: TestSecurityDomain.java View source code
public void testSerialization() throws IOException, ClassNotFoundException {
    AppConfigurationEntry.LoginModuleControlFlag flag1 = AppConfigurationEntry.LoginModuleControlFlag.REQUISITE;
    Map<String, Object> opts1 = new HashMap<String, Object>();
    opts1.put("key1", "value1");
    opts1.put("key2", "value2");
    String name1 = "myLoginModule";
    AppConfigurationEntry entry1 = new AppConfigurationEntry(name1, flag1, opts1);
    String name2 = "myLoginModule";
    AppConfigurationEntry.LoginModuleControlFlag flag2 = AppConfigurationEntry.LoginModuleControlFlag.REQUISITE;
    Map<String, Object> opts2 = new HashMap<String, Object>();
    AppConfigurationEntry entry2 = new AppConfigurationEntry(name2, flag2, opts2);
    String securityDomainName = "nuxeo-test";
    SecurityDomain sd = new SecurityDomain(securityDomainName, new AppConfigurationEntry[] { entry1, entry2 });
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(sd);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(bais);
    sd = (SecurityDomain) ois.readObject();
    assertEquals(securityDomainName, sd.getName());
    AppConfigurationEntry[] entries = sd.getAppConfigurationEntries();
    assertEquals(2, entries.length);
    assertEquals(entry1.getLoginModuleName(), entries[0].getLoginModuleName());
    assertEquals(entry1.getControlFlag(), entries[0].getControlFlag());
    assertEquals(entry1.getOptions(), entries[0].getOptions());
    assertEquals(entry2.getLoginModuleName(), entries[1].getLoginModuleName());
    assertEquals(entry2.getControlFlag(), entries[1].getControlFlag());
    assertEquals(entry2.getOptions(), entries[1].getOptions());
}
Example 30
Project: geotools-old-master  File: EdigeoTHFTest.java View source code
@Test
public void testReadTHFile() {
    HashMap<String, String> thfValue = null;
    String fname = "EDAB01SE";
    try {
        thfValue = eThf.readTHFile();
        // Edigeo file name for this Edigeo dataset
        assertEquals(fname, thfValue.get("genfname"));
        assertEquals(fname, thfValue.get("geofname"));
        assertEquals(fname, thfValue.get("dicfname"));
        assertEquals(fname, thfValue.get("scdfname"));
        // Vector file number
        assertEquals("4", thfValue.get("nbvec"));
        // Vector file name
        assertEquals("EDAB01T1", thfValue.get("vecfname_T1"));
        assertEquals("EDAB01T2", thfValue.get("vecfname_T2"));
        assertEquals("EDAB01T3", thfValue.get("vecfname_T3"));
        assertEquals("EDAB01S1", thfValue.get("vecfname_S1"));
    } catch (FileNotFoundException e) {
        assertFalse(e.getMessage(), true);
    }
    thfValue = null;
    fname = null;
}
Example 31
Project: checkstyle-master  File: InputLocalVariableNameOneCharVarName.java View source code
public void fooMethod() {
    for (int i = 1; i < 10; i++) {
    //ok
    //some code
    }
    //warn
    int i = 0;
    for (int index = 1; index < 10; index++) {
    //ok
    //some code
    }
    for (int I_ndex = 1; I_ndex < 10; I_ndex++) {
    //warn
    //some code
    }
    int index = 1;
    for (; index < 10; index++) {
    //ok  
    //some code
    }
    for (; i < 12; i++) {
    //ok
    //some code
    }
    Map<String, String> map = new HashMap<String, String>();
    for (Map.Entry<String, String> e : map.entrySet()) {
    //ok
    //some code
    }
    for (int a = 0, b[] = { 1 }, c[][] = { { 1 }, { 2 } }; a < 10; a++) {
    //ok
    // something
    }
    for (int i_ndex = 1; i_ndex < 10; i_ndex++) {
    //warn
    //some code
    }
    for (int ii_i1 = 1; ii_i1 < 10; ii_i1++) {
    //warn
    //some code
    }
    for (int $index = 1; $index < 10; $index++) {
    //warn
    //some code
    }
    for (int in$dex = 1; in$dex < 10; in$dex++) {
    //warn
    //some code
    }
    for (int index$ = 1; index$ < 10; index$++) {
    //warn
    //some code
    }
}
Example 32
Project: sphereMiners-master  File: Pacifist.java View source code
@Override
protected void playTurn() {
    // first check if we could split
    List<Sphere> splits = new ArrayList<>();
    for (Sphere s : ownSpheres) {
        if (s.getSize() > getConstants().getMinSplittingsize()) {
            splits.add(s);
        }
    }
    split(splits);
    // then change directions
    Sphere ownSphere = null;
    Iterator<Sphere> ownIt = ownSpheres.iterator();
    Map<Sphere, Position> newDirections = new HashMap<>();
    while (ownIt.hasNext()) {
        ownSphere = ownIt.next();
        Iterator<Sphere> dotsIt = dots.iterator();
        Sphere nextDot = dotsIt.next();
        double minDist = ownSphere.getPosition().dist(nextDot.getPosition());
        while (dotsIt.hasNext()) {
            Sphere tmpSphere = dotsIt.next();
            double tmpDist = ownSphere.getPosition().dist(tmpSphere.getPosition());
            if (tmpDist < minDist) {
                minDist = tmpDist;
                nextDot = tmpSphere;
            }
        }
        final Position moveTo = nextDot.getPosition().sub(ownSphere.getPosition());
        newDirections.put(ownSphere, moveTo);
    }
    changeMoveDirection(newDirections);
}
Example 33
Project: de.htwg.se.muehle-master  File: GamefieldDisplayTest.java View source code
@Test
public void test() {
    Controller controller = new Controller(new GamefieldAdapter(new GamefieldGraph()));
    controller.setStone(2);
    String log;
    Map<Integer, Character> map = new HashMap<>();
    for (int i = 1; i <= 24; i++) {
        map.put(i, controller.getVertexColor(i));
    }
    log = "%1-----------%2-----------%3\t\t" + "1-----------2-----------3\n" + "|           |           |\t\t" + "|           |           |\n" + "|   %4-------%5-------%6   |\t\t" + "|   4-------5-------6   |\n" + "|   |       |       |   |\t\t" + "|   |       |       |   |\n" + "|   |   %7---%8---%9   |   |\t\t" + "|   |   7---8---9   |   |\n" + "|   |   |       |   |   |\t\t" + "|   |   |       |   |   |\n" + "%10---%11---%12       %13---%14---%15\t\t" + "10--11--12      13--14--15\n" + "|   |   |       |   |   |\t\t" + "|   |   |       |   |   |\n" + "|   |   %16---%17---%18   |   |\t\t" + "|   |   16--17--18  |   |\n" + "|   |       |       |   |\t\t" + "|   |       |       |   |\n" + "|   %19-------%20-------%21   |\t\t" + "|   19------20------21  |\n" + "|           |           |\t\t" + "|           |           |\n" + "%22-----------%23-----------%24\t\t" + "22----------23----------24\n";
    formatGamefield(log, map);
}
Example 34
Project: unutopia-android-master  File: MyListActivity2.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
    for (int x = 0; x < 10; x++) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("nombre", "Pepe " + x);
        map.put("apellido", "Lopez " + x);
        data.add(map);
    }
    int layout = android.R.layout.simple_list_item_2;
    String[] from = new String[] { "nombre", "apellido" };
    int[] to = new int[] { android.R.id.text1, android.R.id.text2 };
    SimpleAdapter adapter = new SimpleAdapter(this, data, layout, from, to);
    setListAdapter(adapter);
}
Example 35
Project: raylew_algorithm-master  File: 统计字符.java View source code
public static void main(String[] args) {
    String str = "zdsgzd";
    Map map = new HashMap();
    int maxvalue = 0;
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (map.get(c) == null) {
            map.put(c, 1);
        } else {
            int total = (Integer) map.get(c);
            total++;
            map.put(c, total);
            if (maxvalue < total) {
                maxvalue = total;
            }
        }
    }
    System.out.println("maxvalue:" + maxvalue);
    System.out.println(map.toString());
    Set set = map.keySet();
    Iterator iterator = set.iterator();
    int max = 0;
    char maxkey = 0;
    char key = 0;
    while (iterator.hasNext()) {
        key = (Character) iterator.next();
        if (max <= (Integer) map.get(key)) {
            max = (Integer) map.get(key);
            maxkey = key;
        }
    }
    System.out.println(maxkey + ":" + max);
}
Example 36
Project: codemap-master  File: RegressionTestNN.java View source code
@Test
public void nearestNeighborRegression() {
    final HashMap<Point, Integer> points = new HashMap<Point, Integer>();
    QuickNDirtyMap.anotherDebugPointSet(points);
    Configuration configuration = new Configuration(points.keySet());
    MapInstance mapInstance = configuration.withSize(mapSize, new MapScheme<Double>() {

        @Override
        public Double forLocation(Point location) {
            // TODO fill in size
            return (double) points.get(location);
        }
    });
    int badCount = 0;
    for (int x = 0; x < mapInstance.width; x++) {
        for (int y = 0; y < mapInstance.height; y++) {
            Location kdTreeNearest = mapInstance.kdTreeNearest(x, y);
            Location naiveNearest = mapInstance.naiveNearest(x, y);
            if (naiveNearest.equals(kdTreeNearest))
                continue;
            badCount++;
        //                assertEquals(naiveNearest, kdTreeNearest);
        }
    }
    System.out.println("number of wrong neighbors: " + badCount);
}
Example 37
Project: bennu-master  File: FileStorageConfiguration.java View source code
public static void createMissingStorageConfigurations() {
    Map<String, FileStorageConfiguration> configs = new HashMap<>();
    for (FileStorageConfiguration config : FileSupport.getInstance().getConfigurationSet()) {
        if (FenixFramework.getDomainModel().findClass(config.getFileType()) == null) {
            config.delete();
        } else {
            configs.put(config.getFileType(), config);
        }
    }
    for (Class<? extends DomainObject> fileTypeClass : DomainModelUtil.getDomainClassHierarchy(GenericFile.class, true, false)) {
        if (!configs.containsKey(fileTypeClass.getName())) {
            new FileStorageConfiguration(fileTypeClass);
        }
    }
}
Example 38
Project: android-bankdroid-master  File: LegacyBankHelper.java View source code
private static void generateLegacyProviderReferences() {
    Map<Integer, String> references = new HashMap<>();
    Map<String, Integer> legacyIds = new HashMap<>();
    Field[] fields = IBankTypes.class.getFields();
    for (Field field : fields) {
        try {
            String reference = field.getName().toLowerCase().replaceAll("_", "-");
            Integer legacyId = field.getInt(new IBankTypes() {
            });
            references.put(legacyId, reference);
            legacyIds.put(reference, legacyId);
        } catch (IllegalAccessException e) {
            Timber.e(e, "Provider could not be mapped");
        }
    }
    legacyProviderReferences = legacyIds;
    providerReferences = references;
}
Example 39
Project: SensorsWebLogger-master  File: SendSensorData.java View source code
protected String addSensorDataToUrl(String url, HashMap parms) {
    if (!url.endsWith("?"))
        url += "?";
    List<NameValuePair> params = new LinkedList<NameValuePair>();
    Set set = parms.entrySet();
    Iterator i = set.iterator();
    while (i.hasNext()) {
        Map.Entry me = (Map.Entry) i.next();
        params.add(new BasicNameValuePair(String.valueOf(me.getKey()), String.valueOf(me.getValue())));
    }
    String paramString = URLEncodedUtils.format(params, "utf-8");
    url += paramString;
    return url;
}
Example 40
Project: park-alert-master  File: UserRankServlet.java View source code
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String ranks = "";
    int total = 10;
    HashMap<Integer, String> tmp = new HashMap<Integer, String>();
    for (String user : Container.userRank.keySet()) {
        tmp.put(Container.userRank.get(user), user);
    }
    Collection<Integer> value = Container.userRank.values();
    ArrayList<Integer> ranksList = new ArrayList<Integer>(value);
    Collections.sort(ranksList);
    for (Integer rank : ranksList) {
        if (total == 0) {
            break;
        } else {
            total--;
            ranks = ranks + tmp.get(rank) + ";" + rank + ":";
        }
    }
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    out.println(ranks);
}
Example 41
Project: Restlib-master  File: JSONRestRequest.java View source code
@Override
public boolean setContent(HashMap<String, Object> data) {
    if (this.getMethod() == RestRequest.GET_METHOD)
        buildGetURI(data);
    try {
        JSONStringer holder = new JSONStringer().object();
        Iterator<Entry<String, Object>> it = data.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> e = it.next();
            holder.key(e.getKey().toString()).value(e.getValue());
        }
        holder.endObject();
        content = holder.toString();
    } catch (Exception e) {
        return false;
    }
    return true;
}
Example 42
Project: REST-OCD-Services-master  File: NewmanModularityCombinedTest.java View source code
@Ignore
@Test
public void testOnJmol() throws AdapterException, FileNotFoundException, IllegalArgumentException, ParseException, OcdAlgorithmException, InterruptedException {
    CustomGraph graph = OcdTestGraphFactory.getJmolTestGraph();
    OcdAlgorithm algo = new CostFunctionOptimizationClusteringAlgorithm();
    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put(CostFunctionOptimizationClusteringAlgorithm.MAXIMUM_K_NAME, Integer.toString(5));
    parameters.put(CostFunctionOptimizationClusteringAlgorithm.OVERLAPPING_THRESHOLD_NAME, Double.toString(0.3));
    algo.setParameters(parameters);
    Cover cover = algo.detectOverlappingCommunities(graph);
    NewmanModularityCombined metric = new NewmanModularityCombined();
    double value = metric.measure(cover);
    System.out.println(value);
}
Example 43
Project: Desktop-master  File: MetaDataTest.java View source code
public static void main(String[] args) {
    Map<ExtractorConfigKey, Object> config = new HashMap<ExtractorConfigKey, Object>();
    config.put(CommonConfigKeys.SEARCHVALUE, "Google Scholar's ranking Algorithm: An Overview");
    try {
        for (int i = 0; i < count; i++) {
            System.out.println(i + " von " + count);
            new GoogleScholarExtractor(config);
            Collection<MetaData> result = new GoogleScholarExtractor().search("Google Scholar's ranking Algorithm: An Overview");
            System.out.println(result.size());
        }
    } catch (MalformedConfigException e) {
        e.printStackTrace();
    }
}
Example 44
Project: TextSecureSMP-master  File: CountryListLoader.java View source code
@Override
public ArrayList<Map<String, String>> loadInBackground() {
    Set<String> regions = PhoneNumberUtil.getInstance().getSupportedRegions();
    ArrayList<Map<String, String>> results = new ArrayList<Map<String, String>>(regions.size());
    for (String region : regions) {
        Map<String, String> data = new HashMap<String, String>(2);
        data.put("country_name", PhoneNumberFormatter.getRegionDisplayName(region));
        data.put("country_code", "+" + PhoneNumberUtil.getInstance().getCountryCodeForRegion(region));
        results.add(data);
    }
    Collections.sort(results, new RegionComparator());
    return results;
}
Example 45
Project: cms-ce-master  File: TranslationReaderTest.java View source code
@Test
public void testTranslate() throws Exception {
    Map<String, String> translations = new HashMap<String, String>();
    translations.put("%__example__%", "alert");
    final String xslFilename = getClass().getName().replace('.', '/') + ".xsl";
    final InputStream xslInputStream = getClass().getClassLoader().getResourceAsStream(xslFilename);
    final Reader reader = new InputStreamReader(xslInputStream, Charset.forName("UTF-8"));
    final TranslationReader translationReader = new TranslationReader(translations, reader);
    final int length = xslInputStream.available();
    final char[] xslBuffer = new char[length];
    translationReader.read(xslBuffer, 0, length);
    final String xslString = new String(xslBuffer);
    assertFalse("The XSL contains untranslated string", xslString.contains("%__example__%"));
}
Example 46
Project: FireflowEngine20-master  File: MapPairInjector.java View source code
@SuppressWarnings("unchecked")
public Object get(ServletContext sc, HttpServletRequest req, HttpServletResponse resp, Object refer) {
    Map<String, Object> map = new HashMap<String, Object>();
    Enumeration<String> enu = (Enumeration<String>) req.getParameterNames();
    while (enu.hasMoreElements()) {
        String name = enu.nextElement();
        String[] vs = req.getParameterValues(name);
        // Null Value
        if (null == vs || vs.length == 0) {
            map.put(name, null);
        } else // Has Value
        if (vs.length == 1) {
            map.put(name, vs[0]);
        } else // Array Value
        {
            map.put(name, vs);
        }
    }
    return map;
}
Example 47
Project: McMMOPlus-master  File: PartyAutoKickTask.java View source code
@Override
public void run() {
    HashMap<OfflinePlayer, Party> toRemove = new HashMap<OfflinePlayer, Party>();
    List<String> processedPlayers = new ArrayList<String>();
    long currentTime = System.currentTimeMillis();
    for (Party party : PartyManager.getParties()) {
        for (String memberName : party.getMembers()) {
            OfflinePlayer member = mcMMO.p.getServer().getOfflinePlayer(memberName);
            boolean isProcessed = processedPlayers.contains(memberName);
            if ((!member.isOnline() && (currentTime - member.getLastPlayed() > KICK_TIME)) || isProcessed) {
                toRemove.put(member, party);
            }
            if (!isProcessed) {
                processedPlayers.add(memberName);
            }
        }
    }
    for (Entry<OfflinePlayer, Party> entry : toRemove.entrySet()) {
        PartyManager.removeFromParty(entry.getKey(), entry.getValue());
    }
}
Example 48
Project: jade_agents-master  File: HashMap.java View source code
/**
                 * @see jade.util.leap.Set interface
                 */
public Iterator iterator() {
    return new Iterator() {

        java.util.Iterator it = HashMap.this.realHiddenMap.keySet().iterator();

        /**
                         * @see jade.util.leap.Iterator interface
                         */
        public boolean hasNext() {
            return it.hasNext();
        }

        /**
                         * @see jade.util.leap.Iterator interface
                         */
        public Object next() {
            return it.next();
        }

        /**
                         * @see jade.util.leap.Iterator interface
                         */
        public void remove() {
            it.remove();
        }
    };
}
Example 49
Project: eclipse.jdt.ui-master  File: CleanUpTest17.java View source code
public void testRemoveRedundantTypeArguments1() throws Exception {
    IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
    StringBuffer buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("import java.util.ArrayList;\n");
    buf.append("import java.util.HashMap;\n");
    buf.append("import java.util.List;\n");
    buf.append("import java.util.Map;\n");
    buf.append("public class E {\n");
    buf.append("    void foo() {\n");
    buf.append("        new ArrayList<String>().add(\"a\")\n");
    buf.append("        List<String> a = new ArrayList<String>();\n");
    buf.append("        Map<Integer, String> m = new HashMap<Integer, String>();\n");
    buf.append("    }\n");
    buf.append("}\n");
    ICompilationUnit cu1 = pack1.createCompilationUnit("E1.java", buf.toString(), false, null);
    enable(CleanUpConstants.REMOVE_REDUNDANT_TYPE_ARGUMENTS);
    buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("import java.util.ArrayList;\n");
    buf.append("import java.util.HashMap;\n");
    buf.append("import java.util.List;\n");
    buf.append("import java.util.Map;\n");
    buf.append("public class E {\n");
    buf.append("    void foo() {\n");
    buf.append("        new ArrayList<String>().add(\"a\")\n");
    buf.append("        List<String> a = new ArrayList<>();\n");
    buf.append("        Map<Integer, String> m = new HashMap<>();\n");
    buf.append("    }\n");
    buf.append("}\n");
    String expected1 = buf.toString();
    assertRefactoringResultAsExpected(new ICompilationUnit[] { cu1 }, new String[] { expected1 });
}
Example 50
Project: openjdk8-jdk-master  File: ZFSTests.java View source code
static void test7156873() throws Throwable {
    String DIRWITHSPACE = "testdir with spaces";
    Path dir = Paths.get(DIRWITHSPACE);
    Path path = Paths.get(DIRWITHSPACE, "file.zip");
    try {
        Files.createDirectory(dir);
        URI uri = URI.create("jar:" + path.toUri());
        Map<String, Object> env = new HashMap<String, Object>();
        env.put("create", "true");
        try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
        }
    } finally {
        Files.deleteIfExists(path);
        Files.deleteIfExists(dir);
    }
}
Example 51
Project: lucene-solr-master  File: ZkNodePropsTest.java View source code
@Test
public void testBasic() throws IOException {
    Map<String, Object> props = new HashMap<>();
    props.put("prop1", "value1");
    props.put("prop2", "value2");
    props.put("prop3", "value3");
    props.put("prop4", "value4");
    props.put("prop5", "value5");
    props.put("prop6", "value6");
    ZkNodeProps zkProps = new ZkNodeProps(props);
    byte[] bytes = Utils.toJSON(zkProps);
    ZkNodeProps props2 = ZkNodeProps.load(bytes);
    assertEquals("value1", props2.getStr("prop1"));
    assertEquals("value2", props2.getStr("prop2"));
    assertEquals("value3", props2.getStr("prop3"));
    assertEquals("value4", props2.getStr("prop4"));
    assertEquals("value5", props2.getStr("prop5"));
    assertEquals("value6", props2.getStr("prop6"));
}
Example 52
Project: AndroidListViewBackport-master  File: HorizontalListActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.horizontal_list_activity);
    final HorizontalListView listView = (HorizontalListView) findViewById(android.R.id.list);
    List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
    for (int i = 0; i < 100; ++i) {
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(PROJECTION_NAME, String.format("Item: %d", i));
        data.add(map);
    }
    ListAdapter adapter = new SimpleAdapter(this, data, R.layout.horizontal_simple_list_item, new String[] { PROJECTION_NAME }, new int[] { android.R.id.text1 });
    listView.setAdapter(adapter);
    listView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
    listView.setMultiChoiceModeListener(new AbsHorizontalListView.MultiChoiceModeListener() {

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
        }

        @Override
        public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
            getMenuInflater().inflate(R.menu.action_mode, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
            Toast.makeText(HorizontalListActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {
        }
    });
}
Example 53
Project: molgenis-master  File: ExplainedAttribute.java View source code
private static Map<String, Object> attributeToMap(Attribute attribute) {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put(AttributeMetadata.NAME, attribute.getName());
    map.put(AttributeMetadata.LABEL, attribute.getLabel());
    map.put(AttributeMetadata.DESCRIPTION, attribute.getDescription());
    map.put(AttributeMetadata.TYPE, attribute.getDataType().toString());
    map.put(AttributeMetadata.IS_NULLABLE, attribute.isNillable());
    map.put(AttributeMetadata.IS_UNIQUE, attribute.isUnique());
    if (attribute.getRefEntity() != null) {
        map.put(AttributeMetadata.REF_ENTITY_TYPE, attribute.getRefEntity().getName());
    }
    return map;
}
Example 54
Project: flink-master  File: RichOutputFormatTest.java View source code
@Test
public void testCheckRuntimeContextAccess() {
    final SerializedOutputFormat<Value> inputFormat = new SerializedOutputFormat<Value>();
    final TaskInfo taskInfo = new TaskInfo("test name", 3, 1, 3, 0);
    inputFormat.setRuntimeContext(new RuntimeUDFContext(taskInfo, getClass().getClassLoader(), new ExecutionConfig(), new HashMap<String, Future<Path>>(), new HashMap<String, Accumulator<?, ?>>(), new UnregisteredMetricsGroup()));
    assertEquals(inputFormat.getRuntimeContext().getIndexOfThisSubtask(), 1);
    assertEquals(inputFormat.getRuntimeContext().getNumberOfParallelSubtasks(), 3);
}
Example 55
Project: dimple-master  File: NonNullTest.java View source code
@Test
public void test() {
    // NonNull.list
    List<Integer> list = NotNull.list(null);
    assertNotNull(list);
    assertTrue(list.isEmpty());
    ArrayList<Integer> list2 = new ArrayList<Integer>();
    list2.add(42);
    list = NotNull.list(list2);
    assertNotNull(list);
    assertEquals(list, list2);
    // NonNull.map
    Map<Integer, Integer> map = NotNull.map(null);
    assertNotNull(map);
    assertTrue(map.isEmpty());
    HashMap<Integer, Integer> map2 = new HashMap<Integer, Integer>();
    map2.put(42, 23);
    map = NotNull.map(map2);
    assertNotNull(map);
    assertEquals(map, map2);
    // NonNull.list
    Set<Integer> set = NotNull.set(null);
    assertNotNull(set);
    assertTrue(set.isEmpty());
    HashSet<Integer> set2 = new HashSet<Integer>();
    set2.add(42);
    set = NotNull.set(set2);
    assertNotNull(set);
    assertEquals(set, set2);
}
Example 56
Project: wpcleaner-master  File: ApiLanguageLinksRequest.java View source code
/**
   * Get a language link in a page to a specific wiki.
   * 
   * @param page Page.
   * @param toWiki Destination wiki.
   */
public String getLanguageLink(Page page, EnumWikipedia toWiki) throws APIException {
    Map<String, String> properties = getProperties(ACTION_QUERY, result.getFormat());
    properties.put(PROPERTY_PROP, PROPERTY_PROP_LANGLINKS);
    properties.put(PROPERTY_CONTINUE, PROPERTY_CONTINUE_DEFAULT);
    String toWikiCode = toWiki.getSettings().getCode();
    properties.put(PROPERTY_LANG, toWikiCode);
    properties.put(PROPERTY_LIMIT, LIMIT_MAX);
    properties.put(PROPERTY_REDIRECTS, "");
    properties.put(PROPERTY_TITLES, page.getTitle());
    Map<String, String> languageLinks = new HashMap<String, String>();
    while (result.getLanguageLinks(properties, languageLinks) && !languageLinks.containsKey(toWikiCode)) {
    //
    }
    return languageLinks.get(toWikiCode);
}
Example 57
Project: hank-master  File: DomainGroupController.java View source code
protected void doUpdateDomainVersions(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String dgName = URLEnc.decode(req.getParameter("name"));
    DomainGroup dg = coordinator.getDomainGroup(dgName);
    Map<Domain, Integer> domainVersions = new HashMap<Domain, Integer>();
    for (Domain domain : coordinator.getDomains()) {
        String version = req.getParameter(domain.getName() + "_version");
        if (version == null) {
            continue;
        }
        domainVersions.put(domain, Integer.parseInt(version));
    }
    dg.setDomainVersions(domainVersions);
    resp.sendRedirect("/domain_group.jsp?n=" + dgName);
}
Example 58
Project: androiddevice.info-master  File: OtacertsProperty.java View source code
private static HashMap<String, X509Certificate> getTrustedCerts(File keystore) throws IOException, GeneralSecurityException {
    HashMap<String, X509Certificate> certs = new HashMap<String, X509Certificate>();
    ZipFile zip = new ZipFile(keystore);
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            InputStream is = zip.getInputStream(entry);
            try {
                certs.put(entry.getName(), (X509Certificate) cf.generateCertificate(is));
            } finally {
                is.close();
            }
        }
    } finally {
        zip.close();
    }
    return certs;
}
Example 59
Project: mkgmap-master  File: UtilsTest.java View source code
/**
	 * Very simple test that the coord2Long method is working.
	 */
@Test
public void testCoord2Long() {
    HashMap<Long, Coord> map = new HashMap<>();
    Coord lowerLeft = new Coord(-89.0, -179.0);
    Coord upperRight = new Coord(89.0, 179.0);
    for (int lat30 = -10; lat30 < 10; lat30++) {
        for (int lon30 = -10; lon30 < 10; lon30++) {
            for (int k = 0; k < 3; k++) {
                Coord co;
                if (k == 0)
                    co = Coord.makeHighPrecCoord(lat30, lon30);
                else if (k == 1)
                    co = Coord.makeHighPrecCoord(lat30 + lowerLeft.getHighPrecLat(), lon30 + lowerLeft.getHighPrecLon());
                else
                    co = Coord.makeHighPrecCoord(lat30 + upperRight.getHighPrecLat(), lon30 + upperRight.getHighPrecLon());
                long key = Utils.coord2Long(co);
                Coord old = map.put(key, co);
                assertTrue("key not unique", old == null);
            }
        }
    }
}
Example 60
Project: openjdk-master  File: CompatibilityTest.java View source code
@BeforeClass
public static void setup() throws Exception {
    compositeTypeV6 = new CompositeType(StackTraceElement.class.getName(), "StackTraceElement", new String[] { "className", "methodName", "fileName", "nativeMethod", "lineNumber" }, new String[] { "className", "methodName", "fileName", "nativeMethod", "lineNumber" }, new OpenType[] { SimpleType.STRING, SimpleType.STRING, SimpleType.STRING, SimpleType.BOOLEAN, SimpleType.INTEGER });
    itemsV6 = new HashMap<>();
    itemsV6.put("className", "MyClass");
    itemsV6.put("methodName", "myMethod");
    itemsV6.put("fileName", "MyClass.java");
    itemsV6.put("nativeMethod", false);
    itemsV6.put("lineNumber", 123);
    compositeDataV6 = new CompositeDataSupport(compositeTypeV6, itemsV6);
}
Example 61
Project: kabeja-master  File: Demo.java View source code
/**
	 * @param args
	 */
public static void main(String[] args) {
    Parser parser = DXFParserBuilder.createDefaultParser();
    try {
        DraftDocument doc = parser.parse(new FileInputStream("/home/simon/Desktop/kabeja/test4martin.dxf"), new HashMap());
        Layer layer = doc.getLayer("0");
        List solids = layer.getEntitiesByType(Type.TYPE_3DSOLID);
        Iterator i = solids.iterator();
        while (i.hasNext()) {
            Solid3D solid = (Solid3D) i.next();
            List acisData = solid.getACISDATA();
            Iterator lines = acisData.iterator();
            System.out.println("ACISData from=" + solid.getID() + ">>>>>>>>");
            while (lines.hasNext()) {
                System.out.println(lines.next());
            }
            System.out.println("<<<<<<<<<<<<<<");
        }
    } catch (Exception e) {
    }
}
Example 62
Project: teiid-designer-master  File: TeiidExecutionService.java View source code
@Override
public Runnable createSimpleSQLResultRunnable(Connection con, String sql, boolean closeCon, IConnectionTracker tracker, IProgressMonitor parentMonitor, DatabaseIdentifier databaseIdentifier, ILaunchConfiguration configuration, HashMap addInfo) {
    return new TeiidAdHocScriptRunnable(con, //$NON-NLS-1$
    Messages.getString("TeiidExecutionService.panelDescription"), //$NON-NLS-1$
    sql, //$NON-NLS-1$
    closeCon, //$NON-NLS-1$
    tracker, parentMonitor, databaseIdentifier, configuration);
}
Example 63
Project: erlide-master  File: UserMyRefacContribution.java View source code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
protected IContributionItem[] getContributionItems() {
    final List<UserRefactoringInfo> refacs = UserRefactoringsManager.getInstance().getMyElementary();
    if (refacs.size() == 0) {
        final CommandContributionItemParameter param = new CommandContributionItemParameter(PlatformUI.getWorkbench(), null, "org.erlide.wrangler.refactoring.empty", CommandContributionItem.STYLE_PUSH);
        param.label = "<Empty>";
        final CommandContributionItem item = new CommandContributionItem(param);
        return new IContributionItem[] { item };
    }
    final IContributionItem[] items = new IContributionItem[refacs.size()];
    int i = 0;
    for (final UserRefactoringInfo info : refacs) {
        final CommandContributionItemParameter param = new CommandContributionItemParameter(PlatformUI.getWorkbench(), info.getCallback(), "org.erlide.wrangler.refactoring.gen_refac", CommandContributionItem.STYLE_PUSH);
        param.label = info.getLabel();
        param.parameters = new HashMap();
        param.parameters.put("org.erlide.wrangler.refactoring.gen_refac.callback", info.getCallback());
        param.parameters.put("org.erlide.wrangler.refactoring.gen_refac.name", info.getLabel());
        items[i] = new CommandContributionItem(param);
        i++;
    }
    return items;
}
Example 64
Project: liferay-ide-master  File: FindDependenciesVisitor.java View source code
@Override
public void visitMapExpression(MapExpression expression) {
    List<MapEntryExpression> mapEntryExpressions = expression.getMapEntryExpressions();
    Map<String, String> dependenceMap = new HashMap<String, String>();
    for (MapEntryExpression mapEntryExpression : mapEntryExpressions) {
        String key = mapEntryExpression.getKeyExpression().getText();
        String value = mapEntryExpression.getValueExpression().getText();
        dependenceMap.put(key, value);
    }
    dependencies.add(new GradleDependency(dependenceMap));
    super.visitMapExpression(expression);
}
Example 65
Project: tcf-master  File: TCFChildrenModules.java View source code
@Override
protected boolean startDataRetrieval() {
    TCFNodeExecContext exe = (TCFNodeExecContext) node;
    TCFDataCache<MemoryRegion[]> map_cache = exe.getMemoryMap();
    if (!map_cache.validate(this))
        return false;
    MemoryRegion[] map = map_cache.getData();
    Map<String, TCFNode> data = new HashMap<String, TCFNode>();
    if (map != null) {
        int cnt = 0;
        for (int index = 0; index < map.length; index++) {
            String id = exe.id + ".Module-" + index;
            TCFNodeModule module = (TCFNodeModule) node.model.getNode(id);
            if (module == null)
                module = new TCFNodeModule(exe, id, index);
            module.setSortPosition(cnt++);
            data.put(id, module);
        }
    }
    set(null, map_cache.getError(), data);
    return true;
}
Example 66
Project: sslcertx-master  File: ColumnNameMap.java View source code
public int getIndex(String name) throws SQLException {
    if (columnInfo == null) {
        throw new SQLException("No such column :" + name);
    }
    // The specs in JDBC 4.0 specify that ResultSet.findColumn and
    // ResultSet.getXXX(String name) should use column alias (AS in the query). If label is not found, we use 
    // original table name.
    Integer res = getLabelIndex(name);
    if (res != null) {
        return res;
    }
    if (map == null) {
        map = new HashMap<String, Integer>();
        int i = 0;
        for (ColumnInformation ci : columnInfo) {
            String columnName = ci.getOriginalName().toLowerCase();
            if (columnName.equals("")) {
                // for name-less columns (there CAN be some), use their alias
                columnName = ci.getName().toLowerCase();
            }
            map.put(columnName, i);
            String tableName = ci.getTable().toLowerCase();
            if (!tableName.equals("")) {
                map.put(tableName + "." + columnName, i);
            }
            i++;
        }
    }
    res = map.get(name.toLowerCase());
    if (res == null) {
        throw new SQLException("No such column :" + name);
    }
    return res;
}
Example 67
Project: wso2-synapse-master  File: URITemplateBasedDispatcher.java View source code
public Resource findResource(MessageContext synCtx, Collection<Resource> resources) {
    String url = RESTUtils.getSubRequestPath(synCtx);
    for (Resource r : resources) {
        DispatcherHelper helper = r.getDispatcherHelper();
        if (helper instanceof URITemplateHelper) {
            URITemplateHelper templateHelper = (URITemplateHelper) helper;
            Map<String, String> variables = new HashMap<String, String>();
            if (templateHelper.getUriTemplate().matches(url, variables)) {
                for (Map.Entry<String, String> entry : variables.entrySet()) {
                    synCtx.setProperty(RESTConstants.REST_URI_VARIABLE_PREFIX + entry.getKey(), entry.getValue());
                }
                return r;
            }
        }
    }
    return null;
}
Example 68
Project: Android-automation-master  File: ListViewActivity.java View source code
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.listview_layout);
    ListView listview = (ListView) findViewById(R.id.my_listview);
    ArrayList<HashMap<String, Object>> listitem = new ArrayList<HashMap<String, Object>>();
    for (int i = 0; i < 100; i++) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("itemimage", R.drawable.icon);
        map.put("itemTitle", "Item" + i);
        map.put("itemText", "Thank you!");
        listitem.add(map);
    }
    SimpleAdapter listitemAdapter = new SimpleAdapter(this, listitem, R.layout.listview_item_layout, new String[] { "itemimage", "itemTitle", "itemText" }, new int[] { R.id.ItemImage, R.id.ItemTitle, R.id.ItemText });
    listview.setAdapter(listitemAdapter);
    listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        }
    });
    listview.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
            menu.setHeaderTitle("Hello");
            menu.add(0, 0, 0, "Item One");
            menu.add(0, 1, 0, "Item Two");
        }
    });
}
Example 69
Project: mind-compiler-master  File: TestExtensionLoader.java View source code
@BeforeMethod(alwaysRun = true)
public void setUp() {
    final Injector injector = Guice.createInjector(new PluginLoaderModule(), new CommonFrontendModule(), new AbstractMindModule() {

        protected void configureTargetDescriptorLoader() {
            bind(TargetDescriptorLoader.class).toChainStartingWith(InterpolationLoader.class).followedBy(ExtensionLoader.class).endingWith(BasicTargetDescriptorLoader.class);
        }
    });
    loader = injector.getInstance(TargetDescriptorLoader.class);
    context = new HashMap<Object, Object>();
    context.put("classloader", this.getClass().getClassLoader());
}
Example 70
Project: databus-master  File: MapFieldGenerate.java View source code
public Map<Utf8, Object> generateMap() throws UnknownTypeException {
    Map<Utf8, Object> map = new HashMap<Utf8, Object>(randGenerator.getNextInt() % maxNumberOfMapFields);
    Field fakeField = new Field(field.name(), field.schema().getValueType(), null, null);
    int count = randGenerator.getNextInt() % getMaxNumberOfMapFields();
    for (int i = 0; i < count; i++) {
        // create a new filler each time to emulate null-able fields
        SchemaFiller filler = SchemaFiller.createRandomField(fakeField);
        map.put(new Utf8(field.name() + i), filler.generateRandomObject());
    }
    return map;
}
Example 71
Project: cdo-master  File: BasicDawnLockingHandler.java View source code
@Override
public void handleLocksChangedEvent(CDOViewLocksChangedEvent event) {
    CDOViewLocksChangedEvent lockEvent = event;
    CDOLockState[] lockStates = lockEvent.getLockStates();
    Map<Object, DawnState> changedObjects = new HashMap<Object, DawnState>();
    for (CDOLockState state : lockStates) {
        Object lockedObject = state.getLockedObject();
        CDOView view = editor.getDawnEditorSupport().getView();
        CDOID id;
        if (lockedObject instanceof CDOID) {
            id = (CDOID) lockedObject;
        } else if (lockedObject instanceof CDOIDAndBranch) {
            id = ((CDOIDAndBranch) lockedObject).getID();
        } else {
            throw new RuntimeException("Unexpected object type: " + lockedObject);
        }
        if (id != null) {
            CDOObject object = view.getObject(id);
            if (object.cdoWriteLock().isLockedByOthers()) {
                changedObjects.put(object, DawnState.LOCKED_REMOTELY);
            } else {
                changedObjects.put(object, DawnState.CLEAN);
            }
        }
    }
    IDawnEditorSupport dawnEditorSupport = editor.getDawnEditorSupport();
    dawnEditorSupport.handleRemoteLockChanges(changedObjects);
}
Example 72
Project: Payara-master  File: CleanupPostBoot.java View source code
@Override
public void event(Event event) {
    if (event.is(EventTypes.SERVER_READY)) {
        logger.info("Cleaning JarFileFactory Cache to prevent jar FD leaks");
        try {
            // Ensure JarFile is closed
            Class clazz = Class.forName("sun.net.www.protocol.jar.JarFileFactory", true, URL.class.getClassLoader());
            Field fields[] = clazz.getDeclaredFields();
            for (Field field : fields) {
                if ("fileCache".equals(field.getName())) {
                    field.setAccessible(true);
                    HashMap<String, JarFile> files = (HashMap<String, JarFile>) field.get(null);
                    Set<JarFile> jars = new HashSet<>();
                    jars.addAll(files.values());
                    for (JarFile file : jars) {
                        file.close();
                    }
                }
            }
        } catch (ClassNotFoundExceptionIllegalAccessException | SecurityException | IllegalArgumentException |  ex) {
            logger.log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }
}
Example 73
Project: FrameCode-master  File: HttpNetUtilActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /**
         * 先定义基础地址
         */
    String baseAddress = "http://m.dahanis.com:24080/BasicService.asmx/GetVehicleLengthList";
    /**
         * 然后再实例一个相应的参数对象并设值
         */
    RequestParams params = new RequestParams();
    /**
         * 支持headers的添加
         */
    Map<String, String> headers = new HashMap<>();
    headers.put("user-agent", "android-volley-dahanis-foundation-app");
    params.setHeaders(headers);
    params.putParams("token", "Zrmp6OJN8JilVNd66DSRntEQAzPtNXNdQzGUK8FDhavb9Lv%2BGSEmpqVvPXLgk0S00F1isuQY5R4%3D");
    params.putParams("userId", "600000032");
    ProgressDialogUtil.showProgressDialog(this);
    AutoPrintHttpNetUtils.getData(baseAddress, params, new AutoPrintHttpNetUtils.RequestListener<ReturnObj>() {

        @Override
        public void onSuccess(ReturnObj returnObj) {
            TruckBean truckBean = returnObj.getTruckBeanList().get(0);
            ToastUtils.toastLongTime(truckBean.getId() + "\n" + truckBean.getLengthValue());
        }

        @Override
        public void onFailed(Throwable throwable) {
        }

        @Override
        public void onFinished() {
            ProgressDialogUtil.dismissProgressDialog();
        }
    }).setTag(toString());
}
Example 74
Project: flare-spork-master  File: URLPARSE.java View source code
public Map<String, Object> exec(Tuple input) throws IOException {
    if (input == null || input.size() == 0)
        return null;
    String url;
    try {
        url = (String) input.get(0);
    } catch (Exception e) {
        System.out.println("Can't convert field to a string; error = " + e.getMessage());
        return null;
    }
    HashMap<String, Object> output = new HashMap<String, Object>();
    if (url == null) {
        return null;
    }
    String[] s = url.split(",");
    output.put("url", s[0]);
    output.put("name", s[1]);
    return output;
}
Example 75
Project: keycloak-master  File: KcSamlSignedBrokerTest.java View source code
@Override
protected List<ClientRepresentation> createProviderClients() {
    List<ClientRepresentation> clientRepresentationList = super.createProviderClients();
    for (ClientRepresentation client : clientRepresentationList) {
        client.setClientAuthenticatorType("client-secret");
        client.setSurrogateAuthRequired(false);
        Map<String, String> attributes = client.getAttributes();
        if (attributes == null) {
            attributes = new HashMap<>();
            client.setAttributes(attributes);
        }
        attributes.put("saml.assertion.signature", "true");
        attributes.put("saml.server.signature", "true");
        attributes.put("saml.client.signature", "true");
        attributes.put("saml.signature.algorithm", "RSA_SHA256");
        attributes.put("saml.signing.private.key", IDP_SAML_SIGN_KEY);
        attributes.put("saml.signing.certificate", IDP_SAML_SIGN_CERT);
    }
    return clientRepresentationList;
}
Example 76
Project: revapi-master  File: ToStringsTest.java View source code
@Test
public void testMethodParameterStringRepresentation() throws Exception {
    Jar.Environment env = jar.compile("ToStrings.java");
    Element cls = env.getElementUtils().getTypeElement("ToStrings");
    List<ExecutableElement> methods = ElementFilter.methodsIn(cls.getEnclosedElements());
    ExecutableElement method = methods.stream().filter( m -> m.getSimpleName().contentEquals("methodWithTypeParamsInMethodParams")).findAny().get();
    VariableElement secondParam = method.getParameters().get(1);
    String humanReadable = Util.toHumanReadableString(secondParam);
    Assert.assertEquals("void ToStrings::methodWithTypeParamsInMethodParams(int, ===java.util.function.Function<java.lang.String, ?>===, java.util.HashMap<?, ?>)", humanReadable);
}
Example 77
Project: k3po-master  File: OptionsResolver.java View source code
public Map<String, Object> resolve() {
    if (resolved == null) {
        resolved = new HashMap<String, Object>();
        for (String name : options.keySet()) {
            Object value = options.get(name);
            if (value instanceof AstExpressionValue) {
                AstExpressionValue expressionValue = (AstExpressionValue) value;
                value = expressionValue.getValue().getValue(environment);
            } else if (value instanceof AstLocationExpression) {
                AstLocationExpression location = (AstLocationExpression) value;
                value = location.getValue().getValue(environment);
            } else if (value instanceof AstLocationLiteral) {
                AstLocationLiteral location = (AstLocationLiteral) value;
                value = location.getValue();
            }
            resolved.put(name, value);
        }
    }
    return resolved;
}
Example 78
Project: Valkyrie-RCP-master  File: BeanPropertyAccessStrategyTests.java View source code
/**
     * Test the metadata on type/readability/writeability.
     */
@Test
public void testMetaData() {
    PropertyMetadataAccessStrategy mas = pas.getMetadataAccessStrategy();
    assertPropertyMetadata(mas, "simpleProperty", String.class, true, true);
    assertPropertyMetadata(mas, "mapProperty", Map.class, true, true);
    assertPropertyMetadata(mas, "listProperty", List.class, true, true);
    assertPropertyMetadata(mas, "readOnly", Object.class, true, false);
    assertPropertyMetadata(mas, "writeOnly", Object.class, false, true);
    // test nested property
    // when null, no type, not readable, not writeable
    assertPropertyMetadata(mas, "nestedProperty.simpleProperty", null, false, false);
    final TestBean nestedProperty = new TestBean();
    testBean.setNestedProperty(nestedProperty);
    // when provided, type/readable/writeable deducted from nested object
    assertPropertyMetadata(mas, "nestedProperty.simpleProperty", String.class, true, true);
    // test access to map
    final Map map = new HashMap();
    testBean.setMapProperty(map);
    map.put("key", new Integer(1));
    assertPropertyMetadata(mas, "mapProperty[key]", Integer.class, true, true);
}
Example 79
Project: ISAcreator-master  File: InvestigationUtils.java View source code
/**
     * Method return all the unannotated freetext found in the Investigation
     *
     * @param investigation @see Investigation
     * @return Map from Assay object (general container for spreadsheet) to a Map from the Column Name to its unannotated values
     */
public static Map<Assay, Map<String, Set<String>>> getFreeTextInInvestigationSpreadsheets(Investigation investigation) {
    Map<Assay, Map<String, Set<String>>> result = new HashMap<Assay, Map<String, Set<String>>>();
    Map<String, Study> studies = investigation.getStudies();
    for (String studyId : studies.keySet()) {
        Study study = studies.get(studyId);
        result.put(study.getStudySample(), SpreadsheetUtils.getFreetextInSpreadsheet(((AssaySpreadsheet) ApplicationManager.getUserInterfaceForISASection(study.getStudySample())).getSpreadsheet()));
        for (Assay assay : study.getAssays().values()) {
            result.put(assay, SpreadsheetUtils.getFreetextInSpreadsheet(((AssaySpreadsheet) ApplicationManager.getUserInterfaceForISASection(assay)).getSpreadsheet()));
        }
    }
    return result;
}
Example 80
Project: aws-sdk-android-master  File: DynamoDBSaveExpressionTest.java View source code
@Test
public void testWithMethods() {
    DynamoDBSaveExpression se = new DynamoDBSaveExpression();
    ConditionalOperator co = ConditionalOperator.AND;
    assertNotNull(se.withConditionalOperator(co));
    assertEquals(se.getConditionalOperator(), co.toString());
    assertNotNull(se.withConditionalOperator("OR"));
    assertEquals(se.getConditionalOperator(), ConditionalOperator.OR.toString());
    Map<String, ExpectedAttributeValue> expected = new HashMap<String, ExpectedAttributeValue>();
    assertNotNull(se.withExpected(expected));
    assertSame(se.getExpected(), expected);
    ExpectedAttributeValue eav = new ExpectedAttributeValue();
    assertNotNull(se.withExpectedEntry("eav", eav));
    assertSame(se.getExpected().get("eav"), eav);
}
Example 81
Project: cids-server-master  File: AllAttributesToStringConverter.java View source code
//~ Methods ----------------------------------------------------------------
@Override
public String convert(final Sirius.server.localserver.object.Object o, final HashMap classes) {
    // NOI18N
    String stringRepresentation = "";
    final ObjectAttribute[] attrs = o.getAttribs();
    for (int i = 0; i < attrs.length; i++) {
        if (!attrs[i].referencesObject()) {
            // NOI18N
            stringRepresentation += (attrs[i].toString() + " ");
        } else {
            // NOI18N
            stringRepresentation += (((MetaObject) attrs[i].getValue()).toString(classes) + " ");
        }
    }
    return stringRepresentation;
}
Example 82
Project: OpenClinica-master  File: PformSubmissionNotificationService.java View source code
public void notify(String studyOid, HashMap<String, String> subjectContext) {
    try {
        Integer studyEventDefnId = Integer.valueOf(subjectContext.get("studyEventDefinitionID"));
        Integer studyEventOrdinal = Integer.valueOf(subjectContext.get("studyEventOrdinal"));
        String crfVersionOid = subjectContext.get("crfVersionOID");
        String pManageUrl = CoreResources.getField("portalURL") + "/app/rest/oc/submission";
        Submission submission = new Submission();
        Study pManageStudy = new Study();
        pManageStudy.setInstanceUrl(CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOid);
        pManageStudy.setStudyOid(studyOid);
        submission.setStudy(pManageStudy);
        submission.setStudy_event_def_id(studyEventDefnId);
        submission.setStudy_event_def_ordinal(studyEventOrdinal);
        submission.setCrf_version_id(crfVersionDao.findByOcOID(crfVersionOid).getCrfVersionId());
        RestTemplate rest = new RestTemplate();
        String result = rest.postForObject(pManageUrl, submission, String.class);
        logger.debug("Notified Participate of CRF submission with a result of: " + result);
    } catch (Exception e) {
        logger.error("Unable to notify Participate of successful CRF submission.");
        logger.error(e.getMessage());
        logger.error(ExceptionUtils.getStackTrace(e));
    }
}
Example 83
Project: jena-master  File: ExampleDBpedia3.java View source code
public static void main(String... argv) {
    String serviceURI = "http://dbpedia-live.openlinksw.com/sparql";
    String queryString = "SELECT * WHERE { " + "    SERVICE <" + serviceURI + "> { " + "        SELECT DISTINCT ?company where {?company a <http://dbpedia.org/ontology/Company>} LIMIT 20" + "    }" + "}";
    Query query = QueryFactory.create(queryString);
    try (QueryExecution qexec = QueryExecutionFactory.create(query, ModelFactory.createDefaultModel())) {
        Map<String, Map<String, List<String>>> serviceParams = new HashMap<String, Map<String, List<String>>>();
        Map<String, List<String>> params = new HashMap<String, List<String>>();
        List<String> values = new ArrayList<String>();
        values.add("2000");
        params.put("timeout", values);
        serviceParams.put(serviceURI, params);
        qexec.getContext().set(ARQ.serviceParams, serviceParams);
        ResultSet rs = qexec.execSelect();
        ResultSetFormatter.out(System.out, rs, query);
    }
}
Example 84
Project: application-cafe-jeunesse-android-master  File: ServiceDetailsFragment.java View source code
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_service_list_item_details, container, false);
    Bundle b = getArguments();
    String title = b.getString(Service.SERVICE_TITLE);
    String description = b.getString(Service.SERVICE_DESCR);
    HashMap<String, Object> mInfo = (HashMap) b.getSerializable(Service.SERVICE_MAP_INFO);
    // Chargement du titre et de la description
    ((TextView) view.findViewById(R.id.service_details_title)).setText(title);
    ((TextView) view.findViewById(R.id.service_details_description)).setText(description);
    // Chargement de la liste des informations
    mListView = (ListView) view.findViewById(R.id.listview_services_details);
    ServiceInfoArrayAdapter mServiceInfoAdapter = new ServiceInfoArrayAdapter(getActivity().getApplicationContext(), new ArrayList<ServiceInfoElement>());
    mListView.setAdapter(mServiceInfoAdapter);
    for (Map.Entry<String, Object> entry : mInfo.entrySet()) {
        if (!(entry.getValue() instanceof String))
            continue;
        ServiceInfoElement mElement = new ServiceInfoElement(entry.getKey(), entry.getValue());
        mServiceInfoAdapter.add(mElement);
    }
    return view;
}
Example 85
Project: Hungry-master  File: HungrySetHungerCommand.java View source code
/**
	 * Sets a player hunger to the specified value. Expects a command of the
	 * format: "/<command> <playername> <hunger>"
	 * 
	 * @return true on success, false on failure
	 */
@Override
public boolean onCommand(CommandSender sender, Command command, String cmdLabel, String[] args) {
    // Requires two arguments (playername and hunger)
    if (args.length < 2) {
        return false;
    }
    if (sender instanceof Player && !Hungry.permissions.hasGuard((Player) sender, "hungry.admin.sethunger")) {
        return true;
    }
    HashMap<String, Integer> playerHungers = this.plugin.getConfig().playerHungers;
    Integer playerHunger;
    try {
        playerHunger = Integer.parseInt(args[1]);
    } catch (NumberFormatException e) {
        sender.sendMessage(this.plugin.getConfig().getMessage(HungryMessages.ERR_INVALID_HUNGER_FORMAT));
        return true;
    }
    // Set the key args[0] (the player name) in playerHungers to the value
    // specified in args[1] and parsed
    // above (the new player hunger)
    playerHungers.put(args[0], playerHunger);
    sender.sendMessage(this.plugin.getConfig().getMessage(HungryMessages.VAR_SETHUNGER, args[0], args[1]));
    return true;
}
Example 86
Project: crux-master  File: ConverterScanner.java View source code
/**
	 * 
	 */
protected void initializeConverters() {
    if (!initialized) {
        converters = new HashMap<String, String>();
        JClassType[] converterTypes;
        try {
            converterTypes = jClassScanner.searchClassesByAnnotation(Converter.class);
        } catch (Exception e) {
            throw new CruxGeneratorException("Error initializing Converters scanner.", e);
        }
        if (converterTypes != null) {
            for (JClassType converterClass : converterTypes) {
                Converter annot = converterClass.getAnnotation(Converter.class);
                if (converters.containsKey(annot.value())) {
                    throw new CruxGeneratorException("Duplicated alias for Converter found: [" + annot.value() + "].");
                }
                converters.put(annot.value(), converterClass.getQualifiedSourceName());
            }
        }
        initialized = true;
    }
}
Example 87
Project: hibernate-core-ogm-master  File: DynamicMapOneToOneTest.java View source code
@Test
public void testOneToOneOnSubclass() {
    Map person = new HashMap();
    person.put("name", "Steve");
    Map address = new HashMap();
    address.put("zip", "12345");
    address.put("state", "TX");
    address.put("street", "123 Main St");
    person.put("address", address);
    address.put("owner", person);
    Session s = openSession();
    s.beginTransaction();
    s.persist("Person", person);
    s.getTransaction().commit();
    s.close();
    s = openSession();
    s.beginTransaction();
    EntityStatistics addressStats = sessionFactory().getStatistics().getEntityStatistics("Address");
    person = (Map) s.createQuery("from Person p join fetch p.address").uniqueResult();
    assertNotNull("could not locate person", person);
    assertNotNull("could not locate persons address", person.get("address"));
    s.clear();
    Object[] tuple = (Object[]) s.createQuery("select p.name, p from Person p join fetch p.address").uniqueResult();
    assertEquals(tuple.length, 2);
    person = (Map) tuple[1];
    assertNotNull("could not locate person", person);
    assertNotNull("could not locate persons address", person.get("address"));
    s.delete("Person", person);
    s.getTransaction().commit();
    s.close();
    assertEquals(addressStats.getFetchCount(), 0);
}
Example 88
Project: koubei-mongo-master  File: AdvancedQueryTest.java View source code
@Test
public void testAdvancedQuery() {
    System.out.println("=== testAdvancedQuery ===");
    // between
    MongoBetweenQuery between = new MongoBetweenQuery();
    between.setGreaterThan(1);
    between.setLessThanEqualTo(27);
    // equal
    MongoEqualQuery equal = new MongoEqualQuery();
    equal.setEqualto("1333715943");
    // condition
    Map<String, MongoAdvancedQuery> condition = new HashMap<String, MongoAdvancedQuery>();
    condition.put("age", between);
    condition.put("_id", equal);
    List<POJO> list = dao.advancedFindByCondition(condition, null, 1, 10);
    if (null != list && 0 < list.size()) {
        for (POJO pojo : list) {
            System.out.println(pojo.get_id() + "-" + pojo.getAge());
        }
    }
    assertEquals(true, true);
}
Example 89
Project: astrid-master  File: StatisticsService.java View source code
/**
     * Indicates an event should be reported
     * @param event
     */
public static void reportEvent(String event, String... attributes) {
    if (dontCollectStatistics())
        return;
    if (localyticsSession != null) {
        if (attributes.length > 0) {
            HashMap<String, String> attrMap = new HashMap<String, String>();
            for (int i = 1; i < attributes.length; i += 2) {
                if (attributes[i] != null)
                    attrMap.put(attributes[i - 1], attributes[i]);
            }
            localyticsSession.tagEvent(event, attrMap);
        } else
            localyticsSession.tagEvent(event);
    }
}
Example 90
Project: eclipse-commons-master  File: PlayPauseViewParameterValues.java View source code
@Override
public Map<String, String> getParameterValues() {
    final Map<String, String> result = new HashMap<String, String>();
    IConfigurationElement[] configurationElements = Platform.getExtensionRegistry().getConfigurationElementsFor(org.eclipse.ui.views.file.Activator.getId(), FileView.BINDINGS);
    for (IConfigurationElement configurationElement : configurationElements) {
        try {
            Object type = configurationElement.createExecutableExtension(FileView.TYPE);
            if (type instanceof IFileViewType) {
                IFileViewType<?> fileViewType = (IFileViewType<?>) type;
                if (fileViewType instanceof MidiViewType) {
                    for (IViewDescriptor view : PlatformUI.getWorkbench().getViewRegistry().getViews()) {
                        if (view.getId().equals(configurationElement.getAttribute(FileView.VIEW_ID))) {
                            result.put(view.getLabel(), view.getId());
                        }
                    }
                }
            }
        } catch (CoreException e) {
            Activator.logError(format("Can''t determine type of file view {0}", configurationElement.getAttribute(FileView.VIEW_ID)), e);
        }
    }
    return result;
}
Example 91
Project: Android_Paint-master  File: FBFeedDialog.java View source code
private void loadExtendedPermissionPage() {
    Map<String, String> getParams = new HashMap<String, String>();
    getParams.put("display", "touch");
    getParams.put("callback", "fbconnect://success");
    getParams.put("cancel", "fbconnect://cancel");
    Map<String, String> postParams = new HashMap<String, String>();
    postParams.put("api_key", _session.getApiKey());
    postParams.put("session_key", _session.getSessionKey());
    postParams.put("preview", "1");
    postParams.put("attachment", _attachment);
    postParams.put("action_links", _actionLinks);
    postParams.put("target_id", _targetId);
    postParams.put("user_message_prompt", _messagePrompt);
    try {
        loadURL(kPublishURL, "POST", getParams, postParams);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
}
Example 92
Project: xchain-master  File: TestValidate3.java View source code
public boolean execute(JXPathContext context) throws Exception {
    Session session = HibernateLifecycle.getCurrentSession(getName(context));
    Map contextHolder = new HashMap();
    List beans = new LinkedList();
    Person bean1 = new Person();
    beans.add(bean1);
    Person bean2 = new Person();
    beans.add(bean2);
    Person bean3 = new Person();
    bean3.setId(new Integer(1234));
    bean3.setName("Test Person");
    beans.add(bean3);
    contextHolder.put("beans", beans);
    context.getVariables().declareVariable("test-validate-beans", contextHolder);
    // execute the chain 
    return super.execute(context);
}
Example 93
Project: rsimulator-master  File: HttpModule.java View source code
/*
     * (non-Javadoc)
     * 
     * @see com.google.inject.AbstractModule#configure()
     */
@Override
protected void configure() {
    // ***** Simulator content types *****
    Map<String, String> simulatorContentTypes = new HashMap<String, String>();
    simulatorContentTypes.put("application/json", "json");
    simulatorContentTypes.put("application/xml", "xml");
    simulatorContentTypes.put("application/soap+xml", "xml");
    simulatorContentTypes.put("text/xml", "xml");
    simulatorContentTypes.put("default", "txt");
    bind(new TypeLiteral<Map<String, String>>() {
    }).annotatedWith(Names.named("simulatorContentTypes")).toInstance(simulatorContentTypes);
    // ***** Accepts *****
    Map<String, String> accepts = new HashMap<String, String>();
    accepts.put("application/json", "json");
    accepts.put("default", "txt");
    bind(new TypeLiteral<Map<String, String>>() {
    }).annotatedWith(Names.named("accepts")).toInstance(accepts);
    // ***** Response content types *****
    Map<String, String> responseContentTypes = new HashMap<String, String>();
    responseContentTypes.put("json", "application/json");
    responseContentTypes.put("txt", "text/plain");
    responseContentTypes.put("xml", "application/xml");
    responseContentTypes.put("default", "text/plain");
    bind(new TypeLiteral<Map<String, String>>() {
    }).annotatedWith(Names.named("responseContentTypes")).toInstance(responseContentTypes);
}
Example 94
Project: android-essentials-toolbox-master  File: ApplyPermissionMappingsHandler.java View source code
@Override
public void run() {
    String prefix = "";
    String appliedVersions = "";
    for (Integer apiVersion : PermissionMapping.getAvailableMappings()) {
        if (AndroidEssentialsPreferences.isMappingEnabled(apiVersion)) {
            HashMap<Permission, AtlasHashSet<GraphElement>> result = PermissionMapping.applyTags(apiVersion);
            long totalNodesTagged = 0;
            for (AtlasHashSet<GraphElement> nodes : result.values()) {
                totalNodesTagged += nodes.size();
            }
            Log.info("Applied " + totalNodesTagged + " tags for Android API version " + apiVersion);
            appliedVersions += (prefix + apiVersion);
            prefix = ", ";
        }
    }
    DisplayUtils.showMessage("Applied permission tags for Android APIs: [" + appliedVersions + "].");
}
Example 95
Project: schach-master  File: Fingerprint.java View source code
/*
     * Gibt einen eindeutigen Fingerprint des aktuellen Spielfeldes
     * (Schachfiguren auf Brett) zurueck, um eine Situation zu identifizieren
     * 
     * @param map HashMap<Integer,Byte> mit Situation von der Fingerprint
     * erstellt werden soll
     * 
     * @return String Fingerprint als String als Format
     * "pos1,figwert1--pos2,figwert2--..."
     */
@SuppressWarnings("unchecked")
public static String getFingerprint(HashMap<Integer, Byte> map) {
    HashMap<Integer, Byte> cloneMap = (HashMap<Integer, Byte>) map.clone();
    String fingerprint = "";
    Iterator<Entry<Integer, Byte>> it = cloneMap.entrySet().iterator();
    /*
         * Da die HashMap die Eintraege unterschiedlich ausliest, ist hier die Moeglichkeit,
         * FigureValue mit position zu verknuepfen um sie dann sortieren zu koennen.
         */
    class Identifier implements Comparable {

        byte figureValue;

        int position;

        public Identifier(byte figureValue, int position) {
            this.figureValue = figureValue;
            this.position = position;
        }

        public byte getFigureValue() {
            return this.figureValue;
        }

        public int getPosition() {
            return this.position;
        }

        public int compareTo(Object id) {
            int position;
            if (id instanceof Identifier) {
                position = ((Identifier) id).getPosition();
                return (position - this.position);
            } else {
                return 0;
            }
        }
    }
    List<Identifier> id = new LinkedList<Identifier>();
    while (it.hasNext()) {
        Map.Entry<Integer, Byte> pair = (Map.Entry<Integer, Byte>) it.next();
        byte figureValue = pair.getValue();
        int position = pair.getKey().intValue();
        id.add(new Identifier(figureValue, position));
        it.remove();
    }
    //fuer einen eindeutigen Fingerprint, muss Liste sortiert werden.
    Collections.sort(id);
    while (id.size() > 0) {
        fingerprint += id.get(0).getPosition() + "," + id.get(0).getFigureValue() + "--";
        id.remove(0);
    }
    fingerprint = fingerprint.substring(0, fingerprint.length() - 2);
    return fingerprint;
}
Example 96
Project: milton2-master  File: LockTokenValueWriterTest.java View source code
public void testWriteValue() {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    XmlWriter xmlWriter = new XmlWriter(out);
    LockInfo lockInfo = new LockInfo(LockInfo.LockScope.EXCLUSIVE, LockInfo.LockType.READ, null, LockInfo.LockDepth.ZERO);
    LockTimeout lockTimeout = new LockTimeout(1000l);
    LockToken token = new LockToken("abc123", lockInfo, lockTimeout);
    Map<String, String> prefixes = new HashMap<String, String>();
    valueWriter.writeValue(xmlWriter, "ns", "pre", "lock", token, "/test", prefixes);
    xmlWriter.flush();
    String xml = out.toString();
    System.out.println(xml);
    System.out.println("---------------------------------");
// Should look like this:
//<D:lockdiscovery>
//<D:activelock>
//<D:locktype><D:read/></D:locktype>
//<D:lockscope><D:exclusive/></D:lockscope>
//<D:depth>Infinity</D:depth>
//<D:owner/><D:timeout>Second-1000</D:timeout>
//<D:locktoken>
//<D:href>opaquelocktoken:abc123</D:href>
//</D:locktoken>
//<D:lockroot>
//<D:href>/test</D:href>
//</D:lockroot>
//</D:activelock>
//</D:lockdiscovery>		
}
Example 97
Project: jeboorker-master  File: ComicBookMetadataWriter.java View source code
@Override
public void writeMetadata(List<MetadataProperty> props) {
    try {
        final ComicBookReader reader = new ComicBookReader(resource);
        final ComicBookDocument doc = reader.getDocument();
        final ComicBookWriter writer = new ComicBookWriter(doc, resource);
        final HashMap<String, Object> docInfo = doc.getInfo();
        //			final List<ComicBookPageInfo> docPages = doc.getPages();
        docInfo.clear();
        for (MetadataProperty prop : props) {
            String name = prop.getName();
            String value = prop.getValueAsString();
            if (IMetadataReader.COMMON_METADATA_TYPES.COVER.getName().equalsIgnoreCase(name)) {
                continue;
            }
            docInfo.put(name, value);
        }
        writer.writeDocument();
    } catch (IOException e) {
        LoggerFactory.getLogger().log(Level.WARNING, "Failed to store metadata to " + resource, e);
    }
}
Example 98
Project: castor-master  File: ConverterTest.java View source code
@Test
public void testNonamespaces() throws SchemaException, DTDException, IOException, SAXException, URISyntaxException {
    Converter convertor = new Converter();
    URL in = getClass().getResource("test.dtd");
    File inFile = new File(in.toURI());
    String encoding = "US-ASCII";
    StringWriter writer = new StringWriter();
    convertor.process(new FileReader(inFile), writer, encoding, null, new HashMap<String, String>());
    String generatedSchema = writer.toString();
    System.out.println(generatedSchema);
    assertNotNull(generatedSchema);
    assertFalse(generatedSchema.contains("targetNameSpace"));
    assertFalse(generatedSchema.contains("xmlns:test=\"http://test\""));
    assertTrue(generatedSchema.contains("<element ref=\"description\"/>"));
}
Example 99
Project: picard-tools-master  File: PedFileTest.java View source code
@Test(dataProvider = "testFromSexMapDataProvider")
public void testFromSexMap(final Collection<String> females, final Collection<String> males) throws Exception {
    final Map<String, Sex> data = new HashMap<String, Sex>();
    for (final String sample : females) {
        data.put(sample, Sex.Female);
    }
    for (final String sample : males) {
        data.put(sample, Sex.Male);
    }
    final PedFile pedFile = PedFile.fromSexMap(data);
    // Check that sizes agree
    Assert.assertEquals(pedFile.size(), females.size() + males.size());
    // Check that every entry in the PedFile came from one of the two collections
    for (final Map.Entry<String, PedFile.PedTrio> pedTrioEntry : pedFile.entrySet()) {
        Assert.assertTrue(females.contains(pedTrioEntry.getValue().getIndividualId()) | males.contains(pedTrioEntry.getValue().getIndividualId()));
    }
    // Check that all the females are there and are listed as female
    for (final String female : females) {
        Assert.assertEquals(pedFile.get(female).getSex(), Sex.Female);
    }
    // Check that all the males are there and are listed as male
    for (final String male : males) {
        Assert.assertEquals(pedFile.get(male).getSex(), Sex.Male);
    }
}
Example 100
Project: lucene-addons-master  File: TopNList.java View source code
public static void main(String[] args) {
    //def m = [ 'cat' : 4, 'bison' : 5, 'dog' : 6,
    //'aardvark' : 15, 'the' : 120, 'a' : 50, 'centipede' : 1]
    Map<String, Integer> m = new HashMap<String, Integer>();
    m.put("z", 150);
    m.put("y", 115);
    m.put("x", 110);
    m.put("cat2", 4);
    m.put("bison", 5);
    m.put("dog", 6);
    m.put("aardvark", 15);
    m.put("the", 120);
    TopNList<TermDoublePair> list = new TopNList<TermDoublePair>(3, new DescendingValueComparator());
    for (Map.Entry<String, Integer> e : m.entrySet()) {
        System.out.println("adding " + e.getKey() + " " + e.getValue());
        list.add(new TermDoublePair(e.getKey(), e.getValue()));
    }
    System.out.println(list);
}
Example 101
Project: wampspring-demos-master  File: SchedulerHandler.java View source code
@WampPublishListener(value = "schdemo#clientDoAdd", replyTo = "schdemo#serverDoAdd", excludeSender = true)
public Map<String, List<Object>> add(PublishMessage message, List<Map<String, Object>> records) {
    List<Object> updatedRecords = new ArrayList<>();
    List<Map<String, Object>> ids = new ArrayList<>();
    for (Map<String, Object> r : records) {
        @SuppressWarnings("unchecked") Map<String, Object> record = (Map<String, Object>) r.get("data");
        String internalId = (String) r.get("internalId");
        CustomEvent event = mapper.convertValue(record, CustomEvent.class);
        CustomEventDb.create(event);
        updatedRecords.add(event);
        Map<String, Object> result = new HashMap<>();
        result.put("internalId", internalId);
        result.put("record", event);
        ids.add(result);
    }
    this.eventMessenger.sendTo("schdemo#serverSyncId", Collections.singletonMap("records", ids), message.getWebSocketSessionId());
    return Collections.singletonMap("records", updatedRecords);
}