javatips.net counter

Java Examples for java.util.ArrayList

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

Example 1
Project: android_platform_libcore-master  File: nodeinsertbeforenewchildexists.java View source code
/**
    * Runs the test case.
    * @throws Throwable Any uncaught exception causes test to fail
    */
public void runTest() throws Throwable {
    Document doc;
    NodeList elementList;
    Node employeeNode;
    NodeList childList;
    Node refChild;
    Node newChild;
    Node child;
    int length;
    String childName;
    Node insertedNode;
    java.util.List expectedWhitespace = new java.util.ArrayList();
    expectedWhitespace.add("#text");
    expectedWhitespace.add("#text");
    expectedWhitespace.add("name");
    expectedWhitespace.add("#text");
    expectedWhitespace.add("position");
    expectedWhitespace.add("#text");
    expectedWhitespace.add("salary");
    expectedWhitespace.add("#text");
    expectedWhitespace.add("gender");
    expectedWhitespace.add("#text");
    expectedWhitespace.add("employeeId");
    expectedWhitespace.add("address");
    expectedWhitespace.add("#text");
    java.util.List expectedNoWhitespace = new java.util.ArrayList();
    expectedNoWhitespace.add("name");
    expectedNoWhitespace.add("position");
    expectedNoWhitespace.add("salary");
    expectedNoWhitespace.add("gender");
    expectedNoWhitespace.add("employeeId");
    expectedNoWhitespace.add("address");
    java.util.List expected = new java.util.ArrayList();
    java.util.List result = new java.util.ArrayList();
    doc = (Document) load("staff", true);
    elementList = doc.getElementsByTagName("employee");
    employeeNode = elementList.item(1);
    childList = employeeNode.getChildNodes();
    length = (int) childList.getLength();
    if (equals(6, length)) {
        expected = expectedNoWhitespace;
        refChild = childList.item(5);
        newChild = childList.item(0);
    } else {
        expected = expectedWhitespace;
        refChild = childList.item(11);
        newChild = childList.item(1);
    }
    insertedNode = employeeNode.insertBefore(newChild, refChild);
    for (int indexN100DD = 0; indexN100DD < childList.getLength(); indexN100DD++) {
        child = (Node) childList.item(indexN100DD);
        childName = child.getNodeName();
        result.add(childName);
    }
    assertEquals("childNames", expected, result);
}
Example 2
Project: queueing-simulation-master  File: CustomXYURLGeneratorTests.java View source code
/**
     * Confirm that cloning works.
     */
public void testCloning() {
    CustomXYURLGenerator g1 = new CustomXYURLGenerator();
    List u1 = new java.util.ArrayList();
    u1.add("URL A1");
    u1.add("URL A2");
    u1.add("URL A3");
    g1.addURLSeries(u1);
    CustomXYURLGenerator g2 = null;
    try {
        g2 = (CustomXYURLGenerator) g1.clone();
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }
    assertTrue(g1 != g2);
    assertTrue(g1.getClass() == g2.getClass());
    assertTrue(g1.equals(g2));
    // check independence
    List u2 = new java.util.ArrayList();
    u2.add("URL XXX");
    g1.addURLSeries(u2);
    assertFalse(g1.equals(g2));
    g2.addURLSeries(new java.util.ArrayList(u2));
    assertTrue(g1.equals(g2));
}
Example 3
Project: RoboBuggy-master  File: CustomCategoryURLGeneratorTest.java View source code
/**
     * Some checks for the equals() method.
     */
@Test
public void testEquals() {
    CustomCategoryURLGenerator g1 = new CustomCategoryURLGenerator();
    CustomCategoryURLGenerator g2 = new CustomCategoryURLGenerator();
    assertEquals(g1, g2);
    List<String> u1 = new java.util.ArrayList<String>();
    u1.add("URL A1");
    u1.add("URL A2");
    u1.add("URL A3");
    g1.addURLSeries(u1);
    assertFalse(g1.equals(g2));
    List<String> u2 = new java.util.ArrayList<String>();
    u2.add("URL A1");
    u2.add("URL A2");
    u2.add("URL A3");
    g2.addURLSeries(u2);
    assertEquals(g1, g2);
}
Example 4
Project: molgenis-master  File: AbstractCategoryAlgorithmGenerator.java View source code
public List<Category> convertToCategory(Attribute attribute) {
    List<Category> categories = new ArrayList<>();
    EntityType refEntity = attribute.getRefEntity();
    if (refEntity != null) {
        dataService.findAll(refEntity.getName()).forEach( entity -> {
            String code = DataConverter.toString(entity.get(refEntity.getIdAttribute().getName()));
            String label = DataConverter.toString(entity.get(refEntity.getLabelAttribute().getName()));
            Category category = Category.create(code, label, CategoryMapperUtil.convertDescriptionToAmount(label));
            if (!categories.contains(category)) {
                categories.add(category);
            }
        });
    }
    return categories;
}
Example 5
Project: schach-master  File: ListReader.java View source code
public static ArrayList<String> loadStrings(File aFile) {
    ArrayList<String> pVec = new ArrayList<String>();
    if (!aFile.exists())
        return pVec;
    try {
        BufferedReader pReader = new BufferedReader(new FileReader(aFile));
        String pLine;
        while ((pLine = pReader.readLine()) != null) {
            pLine = pLine.trim();
            if (pLine.startsWith("#") || pLine.equals(""))
                continue;
            pVec.add(pLine);
        }
        pReader.close();
    } catch (IOException aE) {
        aE.printStackTrace();
    }
    return pVec;
}
Example 6
Project: compomics-utilities-master  File: KeyUtils.java View source code
/**
     * Returns the key corresponding to a list of integers.
     *
     * @param list the list
     *
     * @return a key in the form of a string
     */
public static String getKey(ArrayList<Integer> list) {
    StringBuilder stringBuilder = new StringBuilder(2 * list.size());
    for (Integer value : list) {
        if (stringBuilder.length() > 0) {
            stringBuilder.append(SEPARATOR);
        }
        stringBuilder.append(value);
    }
    return stringBuilder.toString();
}
Example 7
Project: openjdk-master  File: ModuleTest.java View source code
@Test
public void testComplex(Path base) throws Exception {
    Path m1 = base.resolve("m1");
    ModuleDescriptor moduleDescriptor = new ModuleDescriptor("m1").exports("pack1").exports("pack3").exportsTo("packTo1", "m2").exportsTo("packTo3", "m3").requires("jdk.compiler").requires("m2", RequiresFlag.TRANSITIVE).requires("m3", RequiresFlag.STATIC).requires("m4", RequiresFlag.TRANSITIVE, RequiresFlag.STATIC).provides("java.util.List", "pack1.C", "pack2.D").uses("java.util.List").uses("java.nio.file.Path").requires("jdk.jdeps", RequiresFlag.STATIC, RequiresFlag.TRANSITIVE).requires("m5", RequiresFlag.STATIC).requires("m6", RequiresFlag.TRANSITIVE).requires("java.compiler").exportsTo("packTo4", "java.compiler").exportsTo("packTo2", "java.compiler").exports("pack4").exports("pack2").write(m1);
    tb.writeJavaFiles(m1, "package pack1; public class C extends java.util.ArrayList{ }", "package pack2; public class D extends java.util.ArrayList{ }", "package pack3; public class D extends java.util.ArrayList{ }", "package pack4; public class D extends java.util.ArrayList{ }");
    tb.writeJavaFiles(m1, "package packTo1; public class T1 {}", "package packTo2; public class T2 {}", "package packTo3; public class T3 {}", "package packTo4; public class T4 {}");
    tb.writeJavaFiles(base.resolve("m2"), "module m2 { }");
    tb.writeJavaFiles(base.resolve("m3"), "module m3 { }");
    tb.writeJavaFiles(base.resolve("m4"), "module m4 { }");
    tb.writeJavaFiles(base.resolve("m5"), "module m5 { }");
    tb.writeJavaFiles(base.resolve("m6"), "module m6 { }");
    compile(base, "--module-source-path", base.toString(), "-d", base.toString());
    testModuleAttribute(m1, moduleDescriptor);
}
Example 8
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 9
Project: ohmagePhone-master  File: TimestampPromptBuilder.java View source code
@Override
public void build(Prompt prompt, String id, String displayType, String displayLabel, String promptText, String abbreviatedText, String explanationText, String defaultValue, String condition, String skippable, String skipLabel, ArrayList<KVLTriplet> properties) {
    TimestampPrompt timestampPrompt = (TimestampPrompt) prompt;
    timestampPrompt.setId(id);
    timestampPrompt.setDisplayType(displayType);
    timestampPrompt.setDisplayLabel(displayLabel);
    timestampPrompt.setPromptText(promptText);
    timestampPrompt.setAbbreviatedText(abbreviatedText);
    timestampPrompt.setExplanationText(explanationText);
    timestampPrompt.setDefaultValue(defaultValue);
    timestampPrompt.setCondition(condition);
    timestampPrompt.setSkippable(skippable);
    timestampPrompt.setSkipLabel(skipLabel);
    timestampPrompt.setProperties(properties);
}
Example 10
Project: LambdaDojo-master  File: S201LambdaInsteadOfAnonClass.java View source code
// 2-1 Lambda 式で書きかえてみましょう
private void rewriteByLambda() {
    // この匿名クラスを Lambda 式で書きかえ
    Comparator<Integer> comparator = new Comparator<Integer>() {

        @Override
        public int compare(Integer x, Integer y) {
            return Integer.compare(x, y);
        }
    };
    List<Integer> numbers = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        numbers.add(i);
    }
    Random random = new Random();
    for (int i = 0; i < 10; i++) {
        Integer number = numbers.remove(random.nextInt(10 - i));
        numbers.add(number);
    }
    System.out.println("Before Sort: " + numbers);
    // 整数のリストをソート
    Collections.sort(numbers, comparator);
    System.out.println("After Sort: " + numbers);
}
Example 11
Project: btpka3.github.com-master  File: TestRegex.java View source code
/**
     * 处理字符串时,常常会有转义字符。
     * 顺序很重要。reg1 和 reg2 中的或是调换顺序的。
     */
public static void testEscape() {
    // mysqldump出的VARCHAR字段可能会是这样 :
    // INSERT INTO `my_table` VALUES ('aa\'bb','',NULL,0),('cc\'dd','',NULL,0);
    String sql = "INSERT INTO `my_table` VALUES ('aa\\'bb','',NULL,0,'111'),('cc\\'dd','',NULL,0,'222');\n";
    String reg1 = "'(\\\\'|[^'])*'";
    Pattern p1 = Pattern.compile(reg1);
    Matcher m1 = p1.matcher(sql);
    List<String> reusltList1 = new ArrayList<String>();
    while (m1.find()) {
        reusltList1.add(m1.group(0));
    }
    System.out.println("reg1 match result : " + reusltList1);
    String reg2 = "'([^']|\\\\')*'";
    Pattern p2 = Pattern.compile(reg2);
    Matcher m2 = p2.matcher(sql);
    List<String> reusltList2 = new ArrayList<String>();
    while (m2.find()) {
        reusltList2.add(m2.group(0));
    }
    System.out.println("reg2 match result : " + reusltList2);
/*
         * output:
         * reg1 match result : ['aa\'bb', '', '111', 'cc\'dd', '', '222']
         * reg2 match result : ['aa\', ',', ',NULL,0,', '),(', 'dd', '', '222']
         */
}
Example 12
Project: expenditures-master  File: MissionProcessProvider.java View source code
@Override
public Collection getSearchResults(Map<String, String> argsMap, String value, int maxCount) {
    final String currentValue = StringUtils.trim(value);
    final List<MissionProcess> result = new ArrayList<MissionProcess>();
    final MissionSystem missionSystem = MissionSystem.getInstance();
    for (final MissionProcess missionProcess : missionSystem.getMissionProcessesSet()) {
        String[] processIdParts = missionProcess.getProcessNumber().split("/M");
        if (missionProcess.getProcessIdentification().equals(currentValue) || processIdParts[processIdParts.length - 1].equals(currentValue)) {
            result.add(missionProcess);
        }
    }
    return result;
}
Example 13
Project: xbnjava-master  File: OrderIntListXmpl.java View source code
public static final void main(String[] ignored) {
    int[] aiNums = new int[] { 1, 11, 29, 12, 13, 19, 7, 2, 6, 16, 10, 15, 112, 18, 20, 3, 8, 5, 9, 14 };
    System.out.println("Unsorted: " + Arrays.toString(aiNums));
    ArrayList<Integer> alNums = new ArrayList<Integer>(aiNums.length);
    for (int i : aiNums) {
        alNums.add(i);
    }
    Collections.sort(alNums);
    System.out.println("Sorted: " + Arrays.toString(alNums.toArray()));
    int ixOf12 = Collections.<Integer>binarySearch(alNums, 12);
    System.out.println("Index of number 12: " + ixOf12);
}
Example 14
Project: sonar-java-master  File: SerializableObjectInSessionCheck.java View source code
void foo() {
    javax.servlet.http.HttpSession session = request.getSession();
    // Noncompliant [[sc=37;ec=50]] {{Make "Address" serializable or don't store it in the session.}}
    session.setAttribute("address", new Address());
    // Noncompliant {{Make "Person" serializable or don't store it in the session.}}
    session.setAttribute("person", new Person());
    session.setAttribute("person", 1);
    session.setAttribute("person", new Integer(1));
    session.setAttribute("addressString", "address");
    session.setAttribute("intArray", new int[] { 1, 2 });
    session.setAttribute("stringArray", new String[] { "one", "two" });
    // Noncompliant {{Make "Person[]" serializable or don't store it in the session.}}
    session.setAttribute("personArray", new Person[] { new Person() });
    session.setAttribute("stringArrayList", new java.util.ArrayList<>(java.util.Arrays.asList("one", "two")));
    // Noncompliant {{Make "ArrayList" and its parameters serializable or don't store it in the session.}}
    session.setAttribute("personArrayList", new java.util.ArrayList<>(java.util.Arrays.asList(new Person(), new Person())));
    session.setAttribute("stringList", java.util.Arrays.asList("one", "two"));
    // Noncompliant {{Make "CustomStack" and its parameters serializable or don't store it in the session.}}
    session.setAttribute("nonSerializableParameterized", new CustomStack<String>());
}
Example 15
Project: milton2-master  File: SendMailScratch.java View source code
public static void main(String[] arr) {
    String host = "XXX";
    String user = "XXX";
    String password = "XXX";
    int port = 465;
    RemoteSmtpMailSender sender = new RemoteSmtpMailSender(host, user, password, port);
    sender.setUseSsl(true);
    sender.start();
    StandardMessageImpl sm = new StandardMessageImpl();
    sm.setFrom(MailboxAddress.parse("[email protected]"));
    List<MailboxAddress> to = new ArrayList();
    to.add(MailboxAddress.parse("[email protected]"));
    sm.setTo(to);
    sm.setSubject("hello!");
    sender.sendMail(sm);
}
Example 16
Project: castor-master  File: NodeBuilder.java View source code
/**
     * Build the object we expect when we unmarshal 'input.xml'.
     */
public Object buildInstance() {
    NodeList nodeList = new NodeList();
    Node nodeOne = new Node();
    nodeOne.setNodeNum(1);
    Node nodeTwo = new Node();
    nodeTwo.setNodeNum(2);
    Node nodeThree = new Node();
    nodeThree.setNodeNum(3);
    List siblings = new ArrayList();
    siblings.add(nodeTwo);
    siblings.add(nodeThree);
    nodeOne.setSiblings(siblings);
    siblings = new ArrayList();
    siblings.add(nodeOne);
    siblings.add(nodeThree);
    nodeTwo.setSiblings(siblings);
    siblings = new ArrayList();
    siblings.add(nodeOne);
    siblings.add(nodeTwo);
    nodeThree.setSiblings(siblings);
    nodeList.addNode(nodeOne);
    nodeList.addNode(nodeTwo);
    nodeList.addNode(nodeThree);
    return nodeList;
}
Example 17
Project: tapestry-model-master  File: PropertyDescriptorFactoryImpl.java View source code
/**
	 * Build the set of property descriptors for this type
	 *
	 * @param beanType the aggregating class
	 * @param beanInfo the BeanInfo, already gathered
	 * @return
	 * @throws Exception
	 */
public ArrayList<TynamoPropertyDescriptor> buildPropertyDescriptors(Class beanType, BeanInfo beanInfo) throws InvocationTargetException, IllegalAccessException {
    ArrayList<TynamoPropertyDescriptor> result = new ArrayList<TynamoPropertyDescriptor>();
    for (PropertyDescriptor beanPropDescriptor : beanInfo.getPropertyDescriptors()) {
        if (!Utils.isExcluded(beanPropDescriptor.getName(), propertyExcludes)) {
            Class<?> propertyType = beanPropDescriptor.getPropertyType();
            TynamoPropertyDescriptorImpl propDescriptor = new TynamoPropertyDescriptorImpl(beanType, propertyType);
            BeanUtils.copyProperties(propDescriptor, beanPropDescriptor);
            result.add(propDescriptor);
        }
    }
    return result;
}
Example 18
Project: eclipse.jdt.ui-master  File: ControlBodyUpdates.java View source code
private void foo() {
    for (int i = 0; i < arraylists.get(0); i++) arraylists = null;
    for (int intValue : ints) arraylists = new ArrayList(arraylists.size());
    while (ints.length != 0) arraylists = null;
    if (arraylists == null)
        arraylists = null;
    int[] newRange = new int[8];
    for (int i = 0; i < arraylists.get(0); i++) {
        arraylists = null;
    }
    for (int intValue : ints) {
        arraylists = new ArrayList(arraylists.size());
    }
    while (ints.length != 0) {
        arraylists = null;
    }
    if (arraylists == null) {
        arraylists = null;
    }
    if (newRange[0] > 0)
        // line number start at 0!
        fNewStart = newRange[0] - 1;
    else
        fNewStart = 0;
    if (newRange[0] > 0) {
        // line number start at 0!
        fNewStart = newRange[0] - 1;
    } else {
        fNewStart = 0;
    }
}
Example 19
Project: TFC2-master  File: DungeonSchemManager.java View source code
public void loadRooms(String theme, ArrayList<String> roomNames, String path) {
    DungeonTheme themeObject;
    if (themeMap.containsKey(theme.toLowerCase()))
        themeObject = themeMap.get(theme.toLowerCase());
    else
        themeObject = new DungeonTheme(theme);
    themeObject.loadRooms(roomNames, path);
    themeMap.put(theme.toLowerCase(), themeObject);
}
Example 20
Project: violetumleditor-master  File: MenuUtils.java View source code
public static void alterMenuBar(JMenuBar menuBar) {
    MenuElement[] subMenuElements = menuBar.getSubElements();
    List<MenuElement> menuEntryStack = new ArrayList<MenuElement>();
    if (subMenuElements.length > 0) {
        menuEntryStack.addAll(Arrays.asList(subMenuElements));
    }
    while (!menuEntryStack.isEmpty()) {
        MenuElement menuElement = menuEntryStack.get(0);
        if (menuElement instanceof JMenuItem) {
            final JMenuItem menuItem = (JMenuItem) menuElement;
            menuItem.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    System.out.println(menuItem.getName());
                }
            });
        }
        MenuElement[] subElements = menuElement.getSubElements();
        if (subElements.length > 0) {
            menuEntryStack.addAll(Arrays.asList(subElements));
        }
        menuEntryStack.remove(0);
    }
}
Example 21
Project: CarpoolBackend-master  File: UserSearchHistoryResource.java View source code
@Get
public Representation getUserSearchHistory() {
    int userId = -1;
    ArrayList<SearchRepresentation> searchHistory = new ArrayList<SearchRepresentation>();
    JSONArray resultArr = new JSONArray();
    try {
        userId = Integer.parseInt(this.getAttribute("id"));
        searchHistory = AwsMain.getUserSearchHistory(userId);
        resultArr = JSONFactory.toJSON(searchHistory);
    } catch (Exception e) {
        return this.doException(e);
    }
    Representation response = new JsonRepresentation(resultArr);
    addCORSHeader();
    return response;
}
Example 22
Project: OpenClinica-master  File: SubjectStatusFilter.java View source code
//AVAILABLE, PENDING, PRIVATE, UNAVAILABLE, LOCKED, DELETED,
// AUTO_DELETED, SIGNED, FROZEN,SOURCE_DATA_VERIFICATION
@Override
protected List<Option> getOptions() {
    List<Option> options = new ArrayList<Option>();
    options.add(new Option("available", "Available"));
    options.add(new Option("pending", "Pending"));
    options.add(new Option("private", "Private"));
    options.add(new Option("unavailable", "Unavailable"));
    options.add(new Option("locked", "Locked"));
    options.add(new Option("deleted", "Deleted"));
    options.add(new Option("auto_deleted", "Auto deleted"));
    options.add(new Option("signed", "Signed"));
    options.add(new Option("frozen", "Frozen"));
    options.add(new Option("source_data_verification", "SDV"));
    return options;
}
Example 23
Project: jade_agents-master  File: ArrayList.java View source code
/**
     * @see jade.util.leap.Collection interface
     */
public Iterator iterator() {
    return new Iterator() {

        java.util.Iterator it = ArrayList.this.realHiddenList.iterator();

        /**
             * Method declaration
             * 
             * @return
             * 
             */
        public boolean hasNext() {
            return it.hasNext();
        }

        /**
             * Method declaration
             * 
             * @return
             * 
             */
        public Object next() {
            return it.next();
        }

        /**
             * Method declaration
             * 
             */
        public void remove() {
            it.remove();
        }
    };
}
Example 24
Project: spring-framework-2.5.x-master  File: ListFactoryBean.java View source code
protected Object createInstance() {
    if (this.sourceList == null) {
        throw new IllegalArgumentException("'sourceList' is required");
    }
    List result = null;
    if (this.targetListClass != null) {
        result = (List) BeanUtils.instantiateClass(this.targetListClass);
    } else {
        result = new ArrayList(this.sourceList.size());
    }
    Class valueType = null;
    if (this.targetListClass != null && JdkVersion.isAtLeastJava15()) {
        valueType = GenericCollectionTypeResolver.getCollectionType(this.targetListClass);
    }
    if (valueType != null) {
        TypeConverter converter = getBeanTypeConverter();
        for (Iterator it = this.sourceList.iterator(); it.hasNext(); ) {
            result.add(converter.convertIfNecessary(it.next(), valueType));
        }
    } else {
        result.addAll(this.sourceList);
    }
    return result;
}
Example 25
Project: nmonvisualizer-master  File: TopasOutParser.java View source code
// topas -a outputs sorted data; unsort it by looking for the header records and outputting them first
// once the ZZZZ records are parsed output them then all the corresponding data records for that timestamp
public NMONDataSet parse(String filename, TimeZone timeZone, boolean scaleProcessesByCPU) throws IOException {
    File file = new File(filename);
    BufferedReader in = null;
    StringWriter writer = null;
    try {
        in = new BufferedReader(new FileReader(file));
        writer = new StringWriter((int) file.length());
        // LinkedHashMap so insertion order is maintained; removes need to reparse headers later
        Map<String, List<String>> headersToLines = new java.util.LinkedHashMap<String, List<String>>(32);
        List<String> headers = new java.util.ArrayList<String>(32);
        List<String> timestamps = new java.util.ArrayList<String>(128);
        String line = null;
        while ((line = in.readLine()) != null) {
            int idx = line.indexOf(",");
            String header = line.substring(0, idx);
            if ("AAA".equals(header)) {
                // put all the AAA records at the top by writing them out now
                writer.write(line);
                writer.write('\n');
            } else if ("ZZZZ".equals(header)) {
                timestamps.add(line);
            } else {
                // save all the data by header name
                List<String> lines = headersToLines.get(header);
                if (lines == null) {
                    LOGGER.trace("found {} " + "header", header);
                    lines = new java.util.ArrayList<String>(218);
                    headersToLines.put(header, lines);
                }
                if (line.charAt(idx + 1) == 'T') {
                    lines.add(line);
                } else {
                    if ("LPAR".equals(header)) {
                        // fix capitalization of LPAR data to match NMON
                        line = "LPAR,LPAR Stats,PhysicalCPU,virtualCPUs,logicalCPUs,poolCPUs,entitled,weight,PoolIdle,usedAllCPU%,usedPoolCPU%,SharedCPU";
                    }
                    headers.add(line);
                }
            }
        }
        LOGGER.debug("found {} " + "data types", headers.size());
        LOGGER.debug("found {} " + "ZZZZ timestamps", timestamps.size());
        LOGGER.debug("found {} " + "data types", headersToLines.size());
        for (String header : headers) {
            writer.write(header);
            writer.write('\n');
        }
        // assume all arrays are the same size, i.e. there is data at each timestamp for all values
        for (int i = 0; i < timestamps.size(); i++) {
            writer.write(timestamps.get(i));
            writer.write('\n');
            for (List<String> lines : headersToLines.values()) {
                writer.write(lines.get(i));
                writer.write('\n');
            }
        }
        return nmonParser.parse(filename, new StringReader(writer.toString()), timeZone, scaleProcessesByCPU);
    } finally {
        if (in != null) {
            in.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}
Example 26
Project: cloudbees-api-client-master  File: CloudResourceProvider.java View source code
/**
     * Lists up all the cloud resources.
     */
public Iterator<CloudResource> iterator() {
    try {
        JsonNode res = getOwner().retrieve().get("resources");
        if (res == null || !res.isArray())
            throw new IllegalStateException("Expected a JSON array but " + getOwner() + " gave us " + res);
        ReferencedResource[] dto = CloudResource.MAPPER.readValue(res, ReferencedResource[].class);
        List<CloudResource> r = new ArrayList<CloudResource>(dto.length);
        for (ReferencedResource rr : dto) {
            r.add(rr.toCloudResource(getOwner()));
        }
        return r.iterator();
    } catch (IOException e) {
        throw new Error(e);
    }
}
Example 27
Project: dr-radio-android-master  File: Netvaerksstatus.java View source code
@Override
public void onReceive(Context context, Intent intent) {
    NetworkInfo networkInfo = App.connectivityManager.getActiveNetworkInfo();
    Status nyStatus;
    if (networkInfo == null || !networkInfo.isConnected()) {
        nyStatus = Status.INGEN;
    } else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
        nyStatus = Status.WIFI;
    } else {
        nyStatus = Status.MOBIL;
    }
    if (status != nyStatus) {
        status = nyStatus;
        Log.d("Netvaerksstatus\n" + intent + "\n" + networkInfo);
        //if (App.fejlsøgning) App.kortToast("Netvaerksstatus\n" + status);
        for (Runnable o : new ArrayList<Runnable>(observatører)) o.run();
    }
}
Example 28
Project: openmap-master  File: SimpleBeanObjectBeanInfo.java View source code
public PropertyDescriptor[] getPropertyDescriptors() {
    ArrayList<PropertyDescriptor> list = new ArrayList<PropertyDescriptor>(4);
    try {
        list.add(new PropertyDescriptor("id", SimpleBeanObject.class));
        list.add(new PropertyDescriptor("latitude", SimpleBeanObject.class));
        list.add(new PropertyDescriptor("longitude", SimpleBeanObject.class));
        list.add(new PropertyDescriptor("bearingInDeg", SimpleBeanObject.class));
    } catch (IntrospectionException e) {
        e.printStackTrace();
    }
    return list.toArray(new PropertyDescriptor[list.size()]);
}
Example 29
Project: R2015-master  File: TestMain.java View source code
public static void main(String[] args) {
    System.out.println("Hello");
    printArray(new int[] { 1, 2, 3 });
    List<String> li = new ArrayList<String>();
    for (int i = 0; i < 6; i++) {
        li.add("element " + i);
    }
    for (int count = 0; count < li.size(); count++) {
        System.out.println(count + " " + li.get(count));
    }
    li.remove(1);
    System.out.println("After 1st removal (element 1 removed) --------------------");
    for (int count = 0; count < li.size(); count++) {
        System.out.println(count + " " + li.get(count));
    }
    li.remove(3);
    System.out.println("After 2nd removal (element 3 (4 in original) removed) --------------------");
    for (int count = 0; count < li.size(); count++) {
        System.out.println(count + " " + li.get(count));
    }
    System.out.println(li.get(2));
}
Example 30
Project: WS171-development-master  File: ClassSourcerTest.java View source code
@Test
public void testTemplateClassSource() throws Exception {
    StringWriter sw = new StringWriter();
    ClassReader cr = new ClassReader("data/TestTemplateClass");
    ClassSourcer jw = new ClassSourcer(new Output(sw));
    cr.accept(jw, 0);
    assertSourceEquals("package data;\n" + "public class TestTemplateClass<T extends java.io.InputStream, U extends java.lang.Object> extends java.lang.Object {\n" + "    private final java.util.Map<T, U> mMap_T_U;\n" + "    public java.util.Map<java.util.ArrayList<T>, java.util.Map<java.lang.String, java.util.ArrayList<U>>> mMap_T_S_U;\n" + "    public TestTemplateClass() {\n" + "        throw new RuntimeException(\"Stub\");\n" + "    }\n" + "    public java.util.Map<T, U> getMap_T_U() {\n" + "        throw new RuntimeException(\"Stub\");\n" + "    }\n" + "    public java.util.Map<java.util.ArrayList<T>, java.util.Map<java.lang.String, java.util.ArrayList<U>>> getMap_T_S_U() {\n" + "        throw new RuntimeException(\"Stub\");\n" + "    }\n" + "    public void draw(java.util.List<? extends org.w3c.dom.css.Rect> arg0) {\n" + "        throw new RuntimeException(\"Stub\");\n" + "    }\n" + "    public static <T extends java.lang.Comparable<? super T>> void sort(java.util.List<T> arg0) {\n" + "        throw new RuntimeException(\"Stub\");\n" + "    }\n" + "    public <X extends T, Y extends java.lang.Object> void getMap(java.util.List<T> arg0, java.util.Map<T, U> arg1, java.util.Map<X, java.util.Set<? super Y>> arg2) {\n" + "        throw new RuntimeException(\"Stub\");\n" + "    }\n" + "}", sw.toString());
}
Example 31
Project: tuberun_android-master  File: NearbyStationsForDeparturesFetcher.java View source code
@Override
protected ArrayList<Station> doInBackground(Location... at) {
    // android.os.Debug.waitForDebugger();
    ArrayList<Station> res = new ArrayList<Station>();
    DatabaseHelper myDbHelper = new DatabaseHelper(context);
    try {
        myDbHelper.openDataBase();
        res = myDbHelper.getEverythingNearbyForDepartures((long) (at[0].getLatitude() * 1000000), (long) (at[0].getLongitude() * 1000000));
        res = getNearbyStations(at[0], res, 8);
    } catch (Exception e) {
        Log.w("NearbyStationsForDeparturesFetcher", e);
    } finally {
        myDbHelper.close();
    }
    return res;
}
Example 32
Project: OrganicBuilder-master  File: RandomConstructor.java View source code
@Override
public Configuration construct() throws GeneratorException {
    final Collection<Atom> atoms = new ArrayList<Atom>();
    float currentWidth = 5 * Atom.getAtomSize();
    float currentHeight = 5 * Atom.getAtomSize();
    final float maximumWidth = partialConfiguration.getWidth() - currentWidth;
    final float maximumHeigth = partialConfiguration.getHeight() - currentHeight;
    while (currentHeight < maximumHeigth) {
        if (currentWidth >= maximumWidth) {
            currentWidth = Atom.getAtomSize();
            currentHeight += 6 * Atom.getAtomSize();
        } else {
            atoms.add(Atoms.createMobileAtomWithRandomSpeed(getRandomAtomType(), getRandomState(), currentWidth, currentHeight));
            currentWidth += 6 * Atom.getAtomSize();
        }
    }
    return new Configuration(partialConfiguration.getHeight(), partialConfiguration.getWidth(), atoms);
}
Example 33
Project: SimpleRep-master  File: RequestProcessor.java View source code
private ProcessingStatus processFlow(MessageContext unprocessedMsg, ArrayList<AbstractHandler> handlers) {
    for (AbstractHandler h : handlers) {
        if (h.invoke(unprocessedMsg) == ProcessingStatus.ABORT) {
            return ProcessingStatus.ABORT;
        }
    }
    return ProcessingStatus.CONTINUE;
}
Example 34
Project: dlna-master  File: FileFilterUtil.java View source code
public static List<File> getFiles(String path, String[] postfix) {
    File file = new File(path);
    File[] files = file.listFiles();
    List<File> lists = new ArrayList();
    if (files == null || files.length == 0) {
        return null;
    }
    for (int i = 0; i < files.length; i++) {
        File childFile = files[i];
        System.out.println("" + childFile.getPath());
        if (childFile.isFile()) {
            childFile.getName();
            int index = childFile.getName().lastIndexOf(".");
            index++;
            String name = childFile.getName().substring(index, childFile.getName().length());
            for (int j = 0; j < postfix.length; j++) {
                if (name.equalsIgnoreCase(postfix[j])) {
                    lists.add(childFile);
                }
            }
        } else if (childFile.isDirectory() && formateToDepth(childFile.getAbsolutePath())) {
            List<File> lsts = getFiles(childFile.getAbsolutePath(), postfix);
            if (lsts != null && lsts.size() != 0) {
                lists.addAll(lsts);
            }
        }
    }
    return lists;
}
Example 35
Project: oobd-master  File: JcaCRLStore.java View source code
private static Collection convertCRLs(Collection collection) throws CRLException {
    List list = new ArrayList(collection.size());
    for (Iterator it = collection.iterator(); it.hasNext(); ) {
        Object crl = it.next();
        if (crl instanceof X509CRL) {
            try {
                list.add(new X509CRLHolder(((X509CRL) crl).getEncoded()));
            } catch (IOException e) {
                throw new CRLException("cannot read encoding: " + e.getMessage());
            }
        } else {
            list.add((X509CRLHolder) crl);
        }
    }
    return list;
}
Example 36
Project: teiid-designer-master  File: ModelObjectTableModelFactory.java View source code
public static ModelObjectTableModel createModelObjectTableModel(boolean supportsDescriptions, EClass tabClass, ArrayList instanceList) {
    UiPlugin.getDefault().getEObjectPropertiesOrderPreferences().addOrUpdateProperty(tabClass.getName(), LOCATION_KEY);
    UiPlugin.getDefault().getEObjectPropertiesOrderPreferences().addOrUpdateEObject(tabClass.getName(), (EObject) instanceList.get(0));
    if (supportsDescriptions) {
        UiPlugin.getDefault().getEObjectPropertiesOrderPreferences().addOrUpdateProperty(tabClass.getName(), DESCRIPTION_KEY);
    }
    ModelObjectTableModel model = new ModelObjectTableModel(tabClass.getName(), instanceList, supportsDescriptions);
    return model;
}
Example 37
Project: erlide-master  File: LaunchUtils.java View source code
public static IProject[] getErlangLaunchConfigurationProjects(final ILaunchConfiguration configuration) throws CoreException {
    final String projectNamesString = configuration.getAttribute(ErlRuntimeAttributes.PROJECTS, "");
    final String[] projectNames = projectNamesString.split(";");
    final List<IProject> projects = new ArrayList<>();
    final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    for (final String s : projectNames) {
        if (s != null && s.length() > 0) {
            final IProject p = root.getProject(s);
            if (p != null) {
                projects.add(p);
            }
        }
    }
    return projects.toArray(new IProject[projects.size()]);
}
Example 38
Project: liferay-ide-master  File: FindJavaProblemsHandler.java View source code
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    try {
        Liferay7UpgradeAssistantSettings settings = UpgradeAssistantSettingsUtil.getObjectFromStore(Liferay7UpgradeAssistantSettings.class);
        String[] projectLocations = settings.getJavaProjectLocations();
        List<IPath> locations = new ArrayList<>();
        for (String projectLocation : projectLocations) {
            locations.add(new Path(projectLocation));
        }
        new MigrateProjectHandler().findMigrationProblems(locations.toArray(new IPath[0]));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Example 39
Project: AudioPlayer-master  File: QianQianParser.java View source code
public static List<LyricResults> parseXml(String xml) {
    List<LyricResults> list = new ArrayList<LyricResults>();
    try {
        XmlPullParser xrp = XmlPullParserFactory.newInstance().newPullParser();
        xrp.setInput(new StringReader(xml));
        // 直到文档的结尾处
        while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {
            // 如果遇到了开始标签
            if (xrp.getEventType() == XmlResourceParser.START_TAG) {
                String // 获取标签的名字
                tagName = // 获取标签的名字
                xrp.getName();
                if (tagName.equals("lrc")) {
                    LyricResults result = new LyricResults();
                    result.id = Integer.valueOf(// 通过属性名来获取属性值
                    xrp.getAttributeValue(// 通过属性名来获取属性值
                    0));
                    result.artist = // 通过属性索引来获取属性值
                    xrp.getAttributeValue(// 通过属性索引来获取属性值
                    1);
                    result.track = xrp.getAttributeValue(2);
                    list.add(result);
                }
            }
            // 获取解析下一个事件
            xrp.next();
        }
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return list.size() == 0 ? null : list;
}
Example 40
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 41
Project: dashboard-master  File: HudsonBuildStatusImpl.java View source code
@Override
public List<Dot> getValue() {
    List<Build> builds = service.getBuilds(project);
    ArrayList<Dot> result = new ArrayList<Dot>();
    for (int i = 0; i < Math.min(5, builds.size()); i++) {
        Build build = builds.get(i);
        if (build.isBuilding()) {
            result.add(new Dot(DotColor.GRAY, build.getJob().getCode()));
        } else {
            switch(build.getResult()) {
                case SUCCESS:
                    result.add(new Dot(DotColor.GREEN, build.getJob().getCode()));
                    break;
                case UNSTABLE:
                    result.add(new Dot(DotColor.YELLOW, build.getJob().getCode()));
                    break;
                case FAILURE:
                    result.add(new Dot(DotColor.RED, build.getJob().getCode()));
                    break;
            }
        }
    }
    return result;
}
Example 42
Project: cloudtm-data-platform-master  File: ConverterClassAwareDmlCompiler.java View source code
public static void main(String[] args) throws Exception {
    final int c = args.length;
    final int offset = c - 3;
    final File dir = new File(args[offset]);
    final String[] baseArgs;
    if (dir.exists() && dir.isDirectory()) {
        final List<String> dmlFilenames = new ArrayList<String>();
        for (final File file : dir.listFiles()) {
            if (file.isFile() && file.getName().endsWith(".dml")) {
                dmlFilenames.add(file.getCanonicalPath());
            }
        }
        Collections.sort(dmlFilenames);
        List<URL> pluginDmlUrlList = PluginDmlUrlLoader.getPluginDmlUrlList();
        baseArgs = new String[c - 3 + dmlFilenames.size() + pluginDmlUrlList.size()];
        System.arraycopy(args, 0, baseArgs, 0, offset);
        int i = offset;
        for (URL pluginDmlUrl : pluginDmlUrlList) {
            baseArgs[i++] = pluginDmlUrl.toExternalForm();
        }
        for (final String dmlFilename : dmlFilenames) {
            baseArgs[i++] = dmlFilename;
        }
    } else {
        baseArgs = Arrays.copyOfRange(args, 0, c - 2);
    }
    DmlCompiler.main(baseArgs);
}
Example 43
Project: cdo-master  File: SelectionHandler.java View source code
protected List<Object> getSelectedObjects(ExecutionEvent event) {
    List<Object> objects = new ArrayList<Object>();
    ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().getSelection();
    if (selection != null & selection instanceof IStructuredSelection) {
        IStructuredSelection structuredSelection = (IStructuredSelection) selection;
        for (@SuppressWarnings("unchecked") Iterator<Object> iterator = structuredSelection.iterator(); iterator.hasNext(); ) {
            Object element = iterator.next();
            objects.add(element);
        }
    }
    return objects;
}
Example 44
Project: Eclipse-Postfix-Code-Completion-master  File: FileFinder.java View source code
private static void find0(File f, String pattern, ArrayList collector) {
    if (f.isDirectory()) {
        String[] files = f.list();
        if (files == null)
            return;
        for (int i = 0, max = files.length; i < max; i++) {
            File current = new File(f, files[i]);
            if (current.isDirectory()) {
                find0(current, pattern, collector);
            } else {
                if (current.getName().toUpperCase().endsWith(pattern)) {
                    collector.add(current.getAbsolutePath());
                }
            }
        }
    }
}
Example 45
Project: Android_Blog_Demos-master  File: Droid.java View source code
public static List<Droid> generateDatas() {
    List<Droid> datas = new ArrayList<Droid>();
    datas.add(new Droid("Lorem ipsum dolor sit amet, orci nullam cra", "3分钟前", -1, "alex"));
    datas.add(new Droid("Omnis aptent magnis suspendisse ipsum, semper egestas", "12分钟前", R.drawable.joanna, "john"));
    datas.add(new Droid("eu nibh, rhoncus wisi posuere lacus, ad erat egestas", "17分钟前", -1, "7heaven"));
    datas.add(new Droid("eu nibh, rhoncus wisi posuere lacus, ad erat egestas", "33分钟前", R.drawable.shailen, "Lseven"));
    return datas;
}
Example 46
Project: revapi-master  File: TestUseChainReporting.java View source code
@Test
public void testCustomReportedCodes() throws Exception {
    String config = "{\"revapi\": {\"java\": {\"reportUsesFor\": [\"java.method.addedToInterface\"]}}}";
    List<Report> reports = new ArrayList<>();
    runAnalysis(new CollectingReporter(reports), config, new String[] { "v1/methods/Added.java" }, new String[] { "v2/methods/Added.java" });
    List<Difference> diffs = reports.stream().flatMap( r -> r.getDifferences().stream()).filter( d -> "java.method.addedToInterface".equals(d.code)).filter( d -> d.description != null && d.description.endsWith("Use chain of the type in the old API: <null>\nUse chain of the" + " type in the new API: ")).collect(Collectors.toList());
    Assert.assertTrue(diffs.isEmpty());
}
Example 47
Project: jnlp-master  File: TestNLP.java View source code
public static void main(String[] args) throws Exception {
    NLP nlp = new NLP("这个东西真心很赞");
    System.out.println(nlp.words());
    System.out.println(nlp.tags());
    System.out.println(nlp.sentiments());
    System.out.println(nlp.pinyin());
    nlp = new NLP("「繁體字」「繁體中文」的叫法在臺灣亦很常見。");
    System.out.println(nlp.han());
    String text = "自然语言处理是计算机科学领域与人工智能领域中的一个重要方向。\r\n它研究能实现人与计算机之间用自然语言进行有效通信的各种理论和方法。\r\n自然语言处理是一门融语言学、计算机科学、数学于一体的科学。\r\n因此,这一领域的研究将涉及自然语言,即人们日常使用的语言,\r\n所以它与语言学的研究有着密切的联系,但又有重要的区别。\r\n自然语言处理并不是一般地研究自然语言,\r\n而在于研制能有效地实现自然语言通信的计算机系统,\r\n特别是其中的软件系统。因而它是计算机科学的一部分。";
    nlp = new NLP(text);
    System.out.println(nlp.keywords(5));
    System.out.println(nlp.summary(3));
    System.out.println(nlp.sentences());
    List<List<String>> test = new ArrayList<List<String>>();
    test.add(Arrays.asList("这篇", "文章"));
    test.add(Arrays.asList("那篇", "论文"));
    test.add(Arrays.asList("这个"));
    nlp = new NLP(test);
    System.out.println(nlp.tf());
    System.out.println(nlp.idf());
    System.out.println(nlp.sim(Arrays.asList("文章")));
}
Example 48
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 49
Project: aws-sdk-android-master  File: ListWithAutoConstructFlagTest.java View source code
@Test
public void testListWithAutoConstructFlag() {
    ListWithAutoConstructFlag<String> noArgs = new ListWithAutoConstructFlag<String>();
    ListWithAutoConstructFlag<String> collect = new ListWithAutoConstructFlag<String>(new ArrayList<String>());
    ListWithAutoConstructFlag<String> capacity = new ListWithAutoConstructFlag<String>(5);
    assertFalse(noArgs.isAutoConstruct());
    assertFalse(collect.isAutoConstruct());
    assertFalse(capacity.isAutoConstruct());
    noArgs.setAutoConstruct(true);
    collect.setAutoConstruct(true);
    capacity.setAutoConstruct(true);
    assertTrue(noArgs.isAutoConstruct());
    assertTrue(collect.isAutoConstruct());
    assertTrue(capacity.isAutoConstruct());
}
Example 50
Project: GlowstonePlusPlus-master  File: GlowChargeFadeMatcher.java View source code
@Override
public ItemStack getResult(ItemStack[] matrix) {
    ItemStack charge = null;
    List<Color> colors = new ArrayList<>();
    for (ItemStack item : matrix) {
        if (item == null)
            continue;
        switch(item.getType()) {
            case INK_SACK:
                Dye dye = (Dye) item.getData();
                colors.add(dye.getColor().getFireworkColor());
                break;
            case FIREWORK_CHARGE:
                charge = item;
                break;
            default:
                // Wrong item on matrix
                return null;
        }
    }
    // No charge, or no colors
    if (charge == null || colors.isEmpty())
        return null;
    FireworkEffectMeta meta = (FireworkEffectMeta) charge.getItemMeta();
    FireworkEffect old = meta.getEffect();
    FireworkEffect newEffect = FireworkEffect.builder().with(old.getType()).withColor(old.getColors()).flicker(old.hasFlicker()).trail(old.hasTrail()).withFade(colors).build();
    meta.setEffect(newEffect);
    ItemStack ret = charge.clone();
    ret.setItemMeta(meta);
    return ret;
}
Example 51
Project: hibernate-core-ogm-master  File: InterceptFieldClassFileTransformerTest.java View source code
/**
	 * Tests that class file enhancement works.
	 * 
	 * @throws Exception in case the test fails.
	 */
public void testEnhancement() throws Exception {
    List<String> entities = new ArrayList<String>();
    entities.add("org.hibernate.ejb.test.instrument.Simple");
    // sanity check that the class is unmodified and does not contain getFieldHandler()
    try {
        org.hibernate.ejb.test.instrument.Simple.class.getDeclaredMethod("getFieldHandler");
        fail();
    } catch (NoSuchMethodException nsme) {
    }
    // use custom class loader which enhances the class
    InstrumentedClassLoader cl = new InstrumentedClassLoader(Thread.currentThread().getContextClassLoader());
    cl.setEntities(entities);
    Class clazz = cl.loadClass(entities.get(0));
    // javassist is our default byte code enhancer. Enhancing will eg add the method getFieldHandler()
    // see org.hibernate.bytecode.internal.javassist.FieldTransformer
    Method method = clazz.getDeclaredMethod("getFieldHandler");
    assertNotNull(method);
}
Example 52
Project: koubei-mongo-master  File: MongoConnector.java View source code
/**
	 * 
	 * @param dsn
	 * @return
	 * @throws UnknownHostException
	 */
public static Mongo getMongo(MongoDsnVO dsn) throws UnknownHostException {
    MongoClient mongo = null;
    if (null != dsn) {
        // 主机列表
        List<String> servers = dsn.getServers();
        if (null != servers && 0 < servers.size()) {
            List<ServerAddress> seeds = new ArrayList<ServerAddress>();
            for (String server : servers) {
                seeds.add(new ServerAddress(server));
            }
            // 设定选项
            MongoClientOptions options = new MongoClientOptions.Builder().autoConnectRetry(dsn.getAutoConnectRetry()).connectionsPerHost(dsn.getConnectionsPerHost()).connectTimeout(dsn.getConnectTimeout()).maxWaitTime(dsn.getMaxWaitTime()).socketTimeout(dsn.getSocketTimeout()).threadsAllowedToBlockForConnectionMultiplier(dsn.getThreadsAllowedToBlockForConnectionMultiplier()).build();
            // 建立连接
            mongo = new MongoClient(seeds, options);
        }
    }
    return mongo;
}
Example 53
Project: extFM-Tooling-master  File: MtextOutlinePageActionProvider.java View source code
public java.util.List<org.eclipse.jface.action.IAction> getActions(org.feature.multi.perspective.mapping.viewmapping.resource.mtext.ui.MtextOutlinePageTreeViewer treeViewer) {
    // To add custom actions to the outline view, set the
    // 'overrideOutlinePageActionProvider' option to <code>false</code> and modify
    // this method.
    java.util.List<org.eclipse.jface.action.IAction> defaultActions = new java.util.ArrayList<org.eclipse.jface.action.IAction>();
    defaultActions.add(new org.feature.multi.perspective.mapping.viewmapping.resource.mtext.ui.MtextOutlinePageLinkWithEditorAction(treeViewer));
    defaultActions.add(new org.feature.multi.perspective.mapping.viewmapping.resource.mtext.ui.MtextOutlinePageCollapseAllAction(treeViewer));
    defaultActions.add(new org.feature.multi.perspective.mapping.viewmapping.resource.mtext.ui.MtextOutlinePageExpandAllAction(treeViewer));
    defaultActions.add(new org.feature.multi.perspective.mapping.viewmapping.resource.mtext.ui.MtextOutlinePageAutoExpandAction(treeViewer));
    defaultActions.add(new org.feature.multi.perspective.mapping.viewmapping.resource.mtext.ui.MtextOutlinePageLexicalSortingAction(treeViewer));
    defaultActions.add(new org.feature.multi.perspective.mapping.viewmapping.resource.mtext.ui.MtextOutlinePageTypeSortingAction(treeViewer));
    return defaultActions;
}
Example 54
Project: FallUML2013-master  File: ManagePolicy.java View source code
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //Renders manageProject.jsp
    System.out.println("enters manage ManagePolicy servlet");
    RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/JSP/managePolicy.jsp");
    //dispatcher.forward(request, response);
    //retrive all policy.
    ArrayList<Policy> allPolicy = null;
    try {
        allPolicy = PolicyDAO.getAllPolicys();
        request.setAttribute("policys", allPolicy);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    dispatcher.forward(request, response);
}
Example 55
Project: SimpleNews-master  File: ImageJsonUtils.java View source code
/**
     * 将获取到的json转换为图片列表对象
     * @param res
     * @return
     */
public static List<ImageBean> readJsonImageBeans(String res) {
    List<ImageBean> beans = new ArrayList<ImageBean>();
    try {
        JsonParser parser = new JsonParser();
        JsonArray jsonArray = parser.parse(res).getAsJsonArray();
        for (int i = 1; i < jsonArray.size(); i++) {
            JsonObject jo = jsonArray.get(i).getAsJsonObject();
            ImageBean news = JsonUtils.deserialize(jo, ImageBean.class);
            beans.add(news);
        }
    } catch (Exception e) {
        LogUtils.e(TAG, "readJsonImageBeans error", e);
    }
    return beans;
}
Example 56
Project: node-go-better-than-random-master  File: MoveUtil.java View source code
/** Fill a list of moves with pass moves.
        The resulting list will contain all moves of the original list
        in the same order, but ensure it starts with a move of color toMove
        and have no subsequent moves of the same color. */
public static ArrayList<Move> fillPasses(ArrayList<Move> moves, GoColor toMove) {
    ArrayList<Move> result = new ArrayList<Move>(moves.size() * 2);
    if (moves.isEmpty())
        return result;
    for (Move move : moves) {
        if (move.getColor() != toMove)
            result.add(Move.getPass(toMove));
        result.add(move);
        toMove = move.getColor().otherColor();
    }
    return result;
}
Example 57
Project: earthsci-master  File: FrameFactory.java View source code
/**
	 * Generates an image for frame-image.
	 * 
	 * @param backgroundColor
	 *            background color.
	 * @return An image data for frame.
	 */
public ImageData create(HSB backgroundColor) {
    ImageData source = SharedImages.getImageDescriptor(SharedImages.FRAME).getImageData();
    List<RGB> newRGBs = new ArrayList<RGB>();
    for (RGB each : source.palette.colors) {
        try {
            HSB copy = backgroundColor.getCopy();
            HSB hsb = new HSB(each);
            copy.brightness = hsb.brightness;
            copy = copy.mixWith(backgroundColor, 0.6f);
            newRGBs.add(copy.toRGB());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    source.palette.colors = newRGBs.toArray(new RGB[newRGBs.size()]);
    return source;
}
Example 58
Project: platform_tools_adt_idea-master  File: AndroidDesignerRefactoringContextProvider.java View source code
@NotNull
@Override
public XmlTag[] getComponentTags(@NotNull DataContext dataContext) {
    final EditableArea area = EditableArea.DATA_KEY.getData(dataContext);
    if (area == null) {
        return XmlTag.EMPTY;
    }
    final List<RadComponent> selection = area.getSelection();
    if (selection.size() == 0) {
        return XmlTag.EMPTY;
    }
    final List<XmlTag> tags = new ArrayList<XmlTag>(selection.size());
    for (RadComponent component : selection) {
        if (!(component instanceof RadViewComponent)) {
            return XmlTag.EMPTY;
        }
        final XmlTag tag = ((RadViewComponent) component).getTag();
        if (tag == null || tag.equals(EmptyXmlTag.INSTANCE)) {
            return XmlTag.EMPTY;
        }
        tags.add(tag);
    }
    return tags.toArray(new XmlTag[tags.size()]);
}
Example 59
Project: extension-aws-master  File: PageLink.java View source code
public List getChildren() {
    try {
        if (fieldChildren == null) {
            List children = getPageManager().getChildrenNames(getPath());
            fieldChildren = new ArrayList();
            //String dir = PathUtilities.extractDirectoryPath( getUrl() );
            for (Iterator iterator = children.iterator(); iterator.hasNext(); ) {
                String path = (String) iterator.next();
                PageLink child = new PageLink();
                child.setPath(path);
                String id = child.getPath();
                id = PathUtilities.makeId(id);
                child.setId(id);
                child.setPageManager(getPageManager());
                fieldChildren.add(child);
            }
        }
        return fieldChildren;
    } catch (OpenEditException ex) {
        throw new OpenEditRuntimeException(ex);
    }
}
Example 60
Project: osmdroid-master  File: BugsTestingActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //needed for unit tests
    MainActivity.updateStoragePrefreneces(this);
    setContentView(R.layout.activity_extra_samples);
    FragmentManager fm = this.getSupportFragmentManager();
    if (fm.findFragmentByTag(SAMPLES_FRAGMENT_TAG) == null) {
        List<BaseActivity> extras = new ArrayList<>();
        extras.add(new WeathForceActivity());
        FragmentSamples fragmentSamples = FragmentSamples.newInstance(BugFactory.getInstance(), extras);
        fm.beginTransaction().add(org.osmdroid.R.id.samples_container, fragmentSamples, SAMPLES_FRAGMENT_TAG).commit();
    }
}
Example 61
Project: jeboorker-master  File: SectionHrefSanityCheckBookProcessor.java View source code
private static List<SpineReference> checkSpineReferences(Spine spine) {
    List<SpineReference> result = new ArrayList<>(spine.size());
    Resource previousResource = null;
    for (SpineReference spineReference : spine.getSpineReferences()) {
        if (spineReference.getResource() == null || StringUtils.isBlank(spineReference.getResource().getHref())) {
            continue;
        }
        if (previousResource == null || spineReference.getResource() == null || (!(spineReference.getResource().getHref().equals(previousResource.getHref())))) {
            result.add(spineReference);
        }
        previousResource = spineReference.getResource();
    }
    return result;
}
Example 62
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 63
Project: windowtester-master  File: JListRecorder.java View source code
/** Create a click referencing the String value that was clicked. */
protected Step createClick(Component target, int x, int y, int mods, int count) {
    JList list = (JList) target;
    ComponentReference cr = getResolver().addComponent(target);
    String methodName = "actionSelectRow";
    ArrayList args = new ArrayList();
    args.add(cr.getID());
    args.add(getLocationArgument(list, x, y));
    if (list.locationToIndex(new Point(x, y)) == -1) {
        methodName = "actionClick";
    }
    if ((mods != 0 && mods != InputEvent.BUTTON1_MASK) || count > 1) {
        methodName = "actionClick";
        args.add(abbot.util.AWT.getMouseModifiers(mods));
        if (count > 1) {
            args.add(String.valueOf(count));
        }
    }
    return new Action(getResolver(), null, methodName, (String[]) args.toArray(new String[args.size()]), javax.swing.JList.class);
}
Example 64
Project: eclipselink.runtime-master  File: ContainerInstanceVariableAccessorTestCases.java View source code
@Override
protected Object getControlObject() {
    Employee emp = new Employee();
    emp.id = 10;
    emp.firstName = "Jane";
    emp.lastName = "Doe";
    emp.address = new Address();
    emp.address.street = "123 Fake Street";
    emp.address.city = "Ottawa";
    emp.address.state = "Ontario";
    emp.address.country = "Canada";
    emp.address.owningEmployee = emp;
    emp.phoneNumbers = new ArrayList<PhoneNumber>();
    PhoneNumber num1 = new PhoneNumber();
    num1.number = "123-4567";
    num1.owningEmployee = emp;
    emp.phoneNumbers.add(num1);
    PhoneNumber num2 = new PhoneNumber();
    num2.number = "234-5678";
    num2.owningEmployee = emp;
    emp.phoneNumbers.add(num2);
    return emp;
}
Example 65
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 66
Project: raylew_algorithm-master  File: 突击战.java View source code
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int m = scan.nextInt();
    ArrayList<Data> list = new ArrayList<Data>();
    for (int i = 0; i < m; i++) {
        int x = scan.nextInt();
        int y = scan.nextInt();
        Data d = new Data(x, y);
        list.add(d);
    }
    Collections.sort(list);
    int t1 = 0, t2 = 0;
    for (int i = 0; i < list.size(); i++) {
        Data d = list.get(i);
        if (i == 0) {
            t1 = d.x;
            t2 = d.y + t1;
            continue;
        }
        if (t1 + d.x + d.y < t2) {
            t1 += d.x;
        } else {
            t1 += d.x;
            t2 = d.y + t1;
        }
    }
    System.out.println(t2);
}
Example 67
Project: codemap-master  File: SelectionInfoAction.java View source code
private String makeText(ArrayList<ICompilationUnit> compilationUnits) {
    if (compilationUnits.isEmpty()) {
        return EMPTY;
    }
    if (compilationUnits.size() == 1) {
        ICompilationUnit unit = compilationUnits.get(0);
        return unit.getElementName();
    }
    return compilationUnits.size() + " Classes";
}
Example 68
Project: ilarkesto-master  File: FPTest.java View source code
public void testGroup() {
    Collection<String> elements = new ArrayList<String>();
    elements.add("abc");
    elements.add("123");
    elements.add("456");
    Function<String, String> textOrNumGroupFunction = new Function<String, String>() {

        public String eval(String e) {
            try {
                Integer.parseInt(e);
                return "num";
            } catch (NumberFormatException ex) {
                return "text";
            }
        }
    };
    Map<String, List<String>> result = FP.group(elements, textOrNumGroupFunction);
    List<String> nums = result.get("num");
    List<String> texts = result.get("text");
    List<String> others = result.get("other");
    assertNotNull(texts);
    assertNotNull(nums);
    assertNull(others);
    assertEquals(1, texts.size());
    assertEquals(2, nums.size());
    assertTrue(texts.contains("abc"));
    assertTrue(nums.contains("123"));
    assertFalse(nums.contains("abc"));
}
Example 69
Project: codereview.chromium-master  File: Diff.java View source code
public void parse(String s) {
    Scanner scanner = new Scanner(s);
    List<String> diffs = new ArrayList<String>();
    while (scanner.hasNext()) {
        String line = scanner.nextLine();
        if (line.startsWith(INDEX)) {
            String fileName = line.substring(INDEX.length());
            diffs = new ArrayList<String>();
            fileDiffs.put(fileName, diffs);
            //diff --git
            scanner.nextLine();
            //index
            scanner.nextLine();
            //--- a/
            scanner.nextLine();
            //+++ b/
            scanner.nextLine();
            continue;
        }
        diffs.add(line.replace(" ", " "));
    }
}
Example 70
Project: virgo.kernel-master  File: CompositeInstallArtifactCommandFormatter.java View source code
public List<String> formatExamine(ManageableCompositeArtifact artifact) {
    List<String> lines = new ArrayList<String>();
    lines.add(String.format("State:  %s", artifact.getState()));
    lines.add(String.format("Scoped: %s", artifact.isScoped()));
    lines.add(String.format("Atomic: %s", artifact.isAtomic()));
    lines.add("");
    lines.add("Children:");
    for (ObjectName child : artifact.getDependents()) {
        lines.add(String.format(CHILD_FORMAT, child.getKeyProperty("artifact-type"), child.getKeyProperty("name"), child.getKeyProperty("version")));
    }
    return lines;
}
Example 71
Project: Klyph-master  File: SearchEventRequest.java View source code
@Override
public List<GraphObject> handleResult(JSONArray result) {
    List<GraphObject> list = new ArrayList<GraphObject>();
    int n = result.length();
    for (int i = 0; i < n; i++) {
        Event event = new Event();
        JSONObject json = result.optJSONObject(i);
        event.setEid(json.optString("id"));
        event.setName(json.optString("name"));
        event.setStart_time(json.optString("start_time"));
        event.setLocation(json.optString("location"));
        JSONObject pic = json.optJSONObject("picture");
        JSONObject data = pic.optJSONObject("data");
        event.setPic(data.optString("url"));
        list.add(event);
    }
    setHasMoreData(false);
    return list;
}
Example 72
Project: android-bankdroid-master  File: CertificateReader.java View source code
public static Certificate[] getCertificates(Context context, int... rawResCerts) {
    List<Certificate> certificates = new ArrayList<>();
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        for (int resId : rawResCerts) {
            InputStream is = new BufferedInputStream(context.getResources().openRawResource(resId));
            try {
                X509Certificate cert = (X509Certificate) cf.generateCertificate(is);
                certificates.add(cert);
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    Timber.w(e, "Failed to close input stream");
                }
            }
        }
    } catch (CertificateException e) {
        Timber.w(e, "Generating certificate failed");
    }
    return certificates.toArray(new Certificate[certificates.size()]);
}
Example 73
Project: schemacrawler-master  File: LinterTableWithNullColumnsInIndex.java View source code
public void lint(final Table table) {
    if (table != null) {
        final Index[] nullableColumnsInUniqueIndex = findNullableColumnsInUniqueIndex(table.getIndices());
        if (nullableColumnsInUniqueIndex.length > 0) {
            addLint(table, new Lint("unique indices have nullable columns", nullableColumnsInUniqueIndex) {

                private static final long serialVersionUID = -1954217739621236510L;

                @Override
                public String getLintValueAsString() {
                    final List<String> indexNames = new ArrayList<String>();
                    for (final Index index : nullableColumnsInUniqueIndex) {
                        indexNames.add(index.getName());
                    }
                    return ObjectToString.toString(indexNames);
                }
            });
        }
    }
}
Example 74
Project: Archimulator-master  File: CSVHelper.java View source code
/**
     * To CSV.
     *
     * @param outputCSVFileName the output CSV file name
     * @param results the list of results
     * @param fields the list of fields
     * @param <ResultT> the result type
     */
public static <ResultT> void toCsv(String outputCSVFileName, List<ResultT> results, List<CSVField<ResultT>> fields) {
    File resultDirFile = new File(outputCSVFileName).getParentFile();
    if (!resultDirFile.exists()) {
        if (!resultDirFile.mkdirs()) {
            throw new RuntimeException();
        }
    }
    CSVFormat format = CSVFormat.RFC4180.withHeader().withDelimiter(',').withQuoteMode(QuoteMode.ALL).withQuote('"');
    try {
        FileWriter writer = new FileWriter(outputCSVFileName);
        CSVPrinter printer = new CSVPrinter(writer, format);
        printer.printRecord(fields);
        for (ResultT result : results) {
            List<String> record = new ArrayList<>();
            for (CSVField<ResultT> field : fields) {
                record.add(field.getFunc().apply(result));
            }
            printer.printRecord(record);
        }
        printer.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 75
Project: Light-Controller-master  File: zoneSetupWizard.java View source code
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_zonesetupwizard);
    final controller.ControllerPager cp = new controller.ControllerPager(getSupportFragmentManager(), null, this);
    List<String> zoneList = new ArrayList<>();
    Log.d("Zones", "Count: " + cp.getCount());
    for (int i = 0; i < cp.getCount(); i++) {
        zoneList.add(cp.getPageTitle(i).toString());
    }
    ArrayAdapter<String> zones = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, zoneList);
    ListView lv = (ListView) findViewById(R.id.zonelist);
    lv.setAdapter(zones);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            cp.setupZone(i);
        }
    });
}
Example 76
Project: openwayback-master  File: MonitoredFileSetTest.java View source code
public void testIsChanged() throws IOException, InterruptedException {
    File f1 = new File(System.getProperty("java.io.tmpdir"), "file-set-1.tmp");
    File f2 = new File(System.getProperty("java.io.tmpdir"), "file-set-2.tmp");
    writeFile(f1, "one");
    writeFile(f2, "two");
    ArrayList<String> l = new ArrayList<String>();
    l.add(f1.getAbsolutePath());
    l.add(f2.getAbsolutePath());
    MonitoredFileSet fs = new MonitoredFileSet(l);
    MonitoredFileSet.FileState s1 = fs.getFileState();
    MonitoredFileSet.FileState s2 = fs.getFileState();
    assertFalse(fs.isChanged(s1));
    assertFalse(fs.isChanged(s2));
    Thread.sleep(1001);
    writeFile(f2, "two2");
    MonitoredFileSet.FileState s3 = fs.getFileState();
    assertTrue(fs.isChanged(s2));
    assertTrue(s3.isChanged(s2));
    Thread.sleep(1001);
    assertTrue(fs.isChanged(s2));
    assertFalse(fs.isChanged(s3));
}
Example 77
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 78
Project: korsakow-editor-master  File: MoveForwardsAction.java View source code
@Override
public void performAction() {
    WidgetCanvasModel model = interfBuilder.getCanvas().getModel();
    final List<WidgetModel> widgets = model.getWidgets();
    List<WidgetModel> selected = new ArrayList<WidgetModel>(model.getSelectedWidgets());
    Collections.sort(selected, new DepthSort(widgets));
    for (int i = selected.size() - 1; i >= 0; --i) {
        WidgetModel widget = selected.get(i);
        int index = model.indexOfWidget(widget);
        if (index + 2 > widgets.size())
            continue;
        if (index + 1 < widgets.size() && selected.contains(widgets.get(index + 1)))
            // preserve relative ordering
            continue;
        model.addWidget(index + 2, widget);
    }
}
Example 79
Project: usercenter-master  File: ParallelPoolCloser.java View source code
void closeConnections() {
    final int numConnections = connections.size();
    final ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(numConnections);
    final ThreadPoolExecutor executor = new ThreadPoolExecutor(numThreads, numThreads, 0L, TimeUnit.MILLISECONDS, queue);
    final ArrayList<Future<?>> results = new ArrayList<Future<?>>(numConnections);
    for (final LDAPConnection conn : connections) {
        results.add(executor.submit(new ParallelPoolCloserTask(conn, unbind)));
    }
    for (final Future<?> f : results) {
        try {
            f.get();
        } catch (final Exception e) {
            Debug.debugException(e);
        }
    }
    executor.shutdown();
}
Example 80
Project: parkandrideAPI-master  File: SameAsLatestPredictor.java View source code
@Override
public List<Prediction> predict(PredictorState state, UtilizationHistory history, int maxCapacity) {
    List<Prediction> predictions = new ArrayList<>();
    try (CloseableIterator<Utilization> utilizations = history.getUpdatesSince(state.latestUtilization)) {
        stream(spliteratorUnknownSize(utilizations, NONNULL | IMMUTABLE), false).reduce(( older,  newer) -> newer).ifPresent( lastUpdate -> {
            state.latestUtilization = lastUpdate.timestamp;
            predictions.add(new Prediction(lastUpdate.timestamp, lastUpdate.spacesAvailable));
            predictions.add(new Prediction(lastUpdate.timestamp.plusDays(1), lastUpdate.spacesAvailable));
        });
    }
    return predictions;
}
Example 81
Project: polly-master  File: ScoreBoardParser.java View source code
public static Collection<ScoreBoardEntry> parse(String paste, Date date) throws ParseException {
    if (paste == null) {
        throw new ParseException();
    }
    //$NON-NLS-1$
    String[] lines = paste.split("[\n\r]+");
    ArrayIterator<String> it = ArrayIterator.get(lines);
    while (it.peekNext().equals("")) {
        //$NON-NLS-1$
        it.next();
    }
    if (it.peekNext().equals("Umgebungsliste")) {
        //$NON-NLS-1$
        it.next();
    }
    if (it.peekNext().startsWith("Rang")) {
        //$NON-NLS-1$
        it.next();
    }
    Collection<ScoreBoardEntry> result = new ArrayList<ScoreBoardEntry>();
    while (it.hasNext()) {
        String line = it.next();
        //$NON-NLS-1$
        String[] parts = line.split("\\s+");
        if (parts.length != 3) {
            continue;
        }
        int rank = Integer.parseInt(parts[0]);
        String venad = parts[1];
        //$NON-NLS-1$
        String clan = "";
        //$NON-NLS-1$
        int i = venad.indexOf("[");
        if (i != -1) {
            clan = venad.substring(i + 1, venad.length() - 1);
            venad = venad.substring(0, venad.length() - clan.length() - 2);
        }
        int points = Integer.parseInt(parts[2]);
        result.add(new ScoreBoardEntry(venad, clan, rank, points, date));
    }
    return result;
}
Example 82
Project: powermock-master  File: ClassNameReader.java View source code
public static String[] getClassInfo(ClassReader r) {
    final List array = new ArrayList();
    try {
        r.accept(new ClassAdapter(null) {

            public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
                array.add(name.replace('/', '.'));
                if (superName != null) {
                    array.add(superName.replace('/', '.'));
                }
                for (int i = 0; i < interfaces.length; i++) {
                    array.add(interfaces[i].replace('/', '.'));
                }
                throw EARLY_EXIT;
            }
        }, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
    } catch (EarlyExitException e) {
    }
    return (String[]) array.toArray(new String[] {});
}
Example 83
Project: ldbc_snb_datagen-master  File: CumulativeBasedDegreeDistribution.java View source code
private int binarySearch(ArrayList<CumulativeEntry> cumulative, double prob) {
    int upperBound = cumulative.size() - 1;
    int lowerBound = 0;
    int midPoint = (upperBound + lowerBound) / 2;
    while (upperBound > (lowerBound + 1)) {
        if (cumulative.get(midPoint).prob_ > prob) {
            upperBound = midPoint;
        } else {
            lowerBound = midPoint;
        }
        midPoint = (upperBound + lowerBound) / 2;
    }
    return midPoint;
}
Example 84
Project: sitebricks-master  File: StringToPrimitiveConverters.java View source code
public static List<Converter<?, ?>> converters() {
    List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();
    converters.add(new ConverterAdaptor<String, Integer>() {

        public Integer to(String source) {
            return Integer.valueOf(source);
        }
    });
    converters.add(new ConverterAdaptor<String, Long>() {

        public Long to(String source) {
            return Long.valueOf(source);
        }
    });
    converters.add(new ConverterAdaptor<String, Float>() {

        public Float to(String source) {
            return Float.valueOf(source);
        }
    });
    converters.add(new ConverterAdaptor<String, Double>() {

        public Double to(String source) {
            return Double.valueOf(source);
        }
    });
    converters.add(new ConverterAdaptor<String, Byte>() {

        public Byte to(String source) {
            return Byte.valueOf(source);
        }
    });
    converters.add(new ConverterAdaptor<String, Boolean>() {

        public Boolean to(String source) {
            return Boolean.valueOf(source);
        }
    });
    converters.add(new ConverterAdaptor<String, Character>() {

        public Character to(String source) {
            return source.charAt(0);
        }
    });
    return converters;
}
Example 85
Project: Tank-master  File: CustomInputStream.java View source code
public static File getNewFile(File file) throws IOException {
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    List<String> contents = new ArrayList<String>();
    String s;
    int i = 0;
    while ((s = br.readLine()) != null) {
        contents.add(s);
        if (s.endsWith(">")) {
            if (i == 0) {
                contents.add(startTag);
            }
            i++;
        }
    }
    contents.add(endTag);
    br.close();
    fr.close();
    File tmpFile = File.createTempFile("temporary", ".xml");
    FileWriter fw = new FileWriter(tmpFile);
    BufferedWriter bw = new BufferedWriter(fw);
    for (String string : contents) {
        bw.write(string);
        System.out.println(string);
    }
    bw.close();
    fw.close();
    return tmpFile;
}
Example 86
Project: XposedGELSettings-master  File: OnPackagesUpdatedHook.java View source code
// http://androidxref.com/4.4.2_r1/xref/packages/apps/Launcher3/src/com/android/launcher3/AppsCustomizePagedView.java#432
// public void onPackagesUpdated(ArrayList<Object> widgetsAndShortcuts)
@SuppressWarnings("unchecked")
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
    if (DEBUG)
        log(param, "Hide Widgets");
    ArrayList<Object> widgets = (ArrayList<Object>) param.args[0];
    Iterator it = widgets.iterator();
    while (it.hasNext()) {
        Object widget = it.next();
        String cmp;
        if (widget instanceof AppWidgetProviderInfo) {
            cmp = ((AppWidgetProviderInfo) widget).provider.flattenToString();
        } else if (widget instanceof ResolveInfo) {
            ResolveInfo item = (ResolveInfo) widget;
            cmp = new ComponentName(item.activityInfo.packageName, item.activityInfo.loadLabel(Common.LAUNCHER_CONTEXT.getPackageManager()).toString()).flattenToString();
        } else {
            continue;
        }
        if (PreferencesHelper.hiddenWidgets.contains(cmp)) {
            it.remove();
        }
    }
    param.args[0] = widgets;
}
Example 87
Project: Desktop-master  File: RibbonTaskContributorFactory.java View source code
public ARibbonContributor getContributor(final Properties attributes) {
    return new ARibbonContributor() {

        private List<ComparableContributorHull<AbstractRibbonBand<?>>> hulls = new ArrayList<ARibbonContributor.ComparableContributorHull<AbstractRibbonBand<?>>>();

        public String getKey() {
            return attributes.getProperty("name");
        }

        public void contribute(RibbonBuildContext context, ARibbonContributor parent) {
            hulls.clear();
            context.processChildren(context.getCurrentPath(), this);
            if (!hulls.isEmpty()) {
                Collections.sort(hulls, comparator);
                AbstractRibbonBand<?>[] bands = new AbstractRibbonBand<?>[hulls.size()];
                int count = 0;
                for (ComparableContributorHull<AbstractRibbonBand<?>> hull : hulls) {
                    bands[count++] = hull.getObject();
                }
                RibbonTask task = new RibbonTask(TextUtils.removeTranslateComment(TextUtils.getText("ribbon." + getKey())), bands);
                if (parent != null) {
                    parent.addChild(task, new ChildProperties(parseOrderSettings(attributes.getProperty("orderPriority", ""))));
                }
            }
        }

        public void addChild(Object child, ChildProperties properties) {
            if (child instanceof AbstractRibbonBand) {
                hulls.add(new ComparableContributorHull<AbstractRibbonBand<?>>((AbstractRibbonBand<?>) child, properties.getOrderPriority()));
            }
        }
    };
}
Example 88
Project: many-ql-master  File: CombinedParsingResult.java View source code
public ValidationResult validate() {
    ValidationResult qlValidationResult = questionnaireParsingResult.validate();
    Questionnaire questionnaire = questionnaireParsingResult.getQuestionnaire();
    ValidationResult qlsValidationResult = stylesheetParsingResult.validate(questionnaire);
    List<ValidationMessage> validationMessages = new ArrayList<>();
    validationMessages.addAll(qlValidationResult.getValidationMessages());
    validationMessages.addAll(qlsValidationResult.getValidationMessages());
    return new ValidationResult(validationMessages);
}
Example 89
Project: openmuc-master  File: CsvDriverReadHHMMSSTest.java View source code
@Test
public void testRead() {
    List<ChannelRecordContainer> containers = new ArrayList<ChannelRecordContainer>();
    containers.add(new CsvChannelRecordContainer("hhmmss"));
    containers.add(new CsvChannelRecordContainer("grid_power"));
    try {
        connection.read(containers, null, null);
        for (ChannelRecordContainer container : containers) {
            System.out.println("##### " + container.getChannelAddress() + " " + container.getRecord().getValue());
        }
    } catch (UnsupportedOperationExceptionConnectionException |  e) {
        e.printStackTrace();
    }
}
Example 90
Project: teleportr-master  File: MfgPlugIn.java View source code
@Override
public ArrayList<Ride> find(Place o, Place d, Date time) {
    ArrayList<Ride> rides = new ArrayList<Ride>();
    // mfg
    Ride r = new Ride();
    r.orig = o;
    r.dest = d;
    r.dep = new Date(System.currentTimeMillis() + 7 * 60000);
    r.arr = new Date(System.currentTimeMillis() + (7 + 22) * 60000);
    r.mode = Ride.MODE_MFG;
    r.price = 150;
    r.fun = 3;
    r.eco = 5;
    r.fast = 3;
    r.social = 4;
    r.green = 3;
    rides.add(r);
    // taxi teiler
    r = new Ride();
    r.orig = o;
    r.dest = d;
    r.dep = new Date(System.currentTimeMillis() + 8 * 60000);
    r.arr = new Date(System.currentTimeMillis() + (8 + 22) * 60000);
    r.mode = Ride.MODE_MFG;
    r.price = 320;
    r.fun = 3;
    r.eco = 4;
    r.fast = 3;
    r.social = 5;
    r.green = 3;
    rides.add(r);
    return rides;
}
Example 91
Project: xwiki-application-mailarchive-master  File: TimeLineEventTest.java View source code
@Test
public void testConstructorClone() throws CloneNotSupportedException {
    TimeLineEvent event = new TimeLineEvent();
    event.action = "action";
    event.author = "author";
    event.authorAvatar = "authorAvatar";
    event.beginDate = new Date();
    event.content = "content";
    event.endDate = new Date();
    event.extract = "extract";
    event.icons = new ArrayList<String>();
    event.icons.add("icon1");
    event.lists = new ArrayList<String>();
    event.lists.add("list1");
    event.lists.add("list2");
    event.messages = new TreeMap<Long, TopicEventBubble>();
    event.messages.put(10L, new TopicEventBubble());
    TimeLineEvent clone = new TimeLineEvent(event);
    assertEquals(event, clone);
}
Example 92
Project: Katari-master  File: ActivitySearchAdapterExample.java View source code
public SearchResultElement convert(final Object o, final float score) {
    Activity activity = (Activity) o;
    ArrayList<Action> actions;
    actions = new ArrayList<Action>();
    actions.add(new Action("Edit", null, "userEdit.do?id=" + activity.getId()));
    actions.add(new Action("Delete", null, "userDelete.do?id=" + activity.getId()));
    StringBuilder description = new StringBuilder();
    description.append("Activity - name: " + activity.getName());
    return new SearchResultElement("Activity", activity.getName(), description.toString(), "activity.do?id=" + activity.getId(), actions, score);
}
Example 93
Project: framework-master  File: TableQueryWithNonUniqueFirstPrimaryKeyTest.java View source code
@Test
public void testComboBoxSuggestionsListedCorrectly() throws Exception {
    openTestURL();
    $(ComboBoxElement.class).first().findElement(By.vaadin("#textbox")).sendKeys("rus", Keys.ENTER);
    List<String> result = new ArrayList<>();
    // pick list items that are shown in suggestion popup
    List<WebElement> elems = findElements(By.cssSelector("td[role=\"listitem\"]"));
    Assert.assertEquals("not enough suggestions shown", DATA.length, elems.size());
    for (WebElement elem : elems) {
        result.add(elem.getText());
    }
    Assert.assertArrayEquals("popup items not what they should be", DATA, result.toArray());
}
Example 94
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 95
Project: ecms-develop-master  File: TestCreatePortalArtifactsService.java View source code
public void testAddIgnorePortalPlugin() throws Exception {
    IgnorePortalPlugin ignorePortalPlugin = Mockito.mock(IgnorePortalPlugin.class);
    CreatePortalArtifactsServiceImpl artifactService = (CreatePortalArtifactsServiceImpl) getService(CreatePortalArtifactsService.class);
    String[] ignorePortals = { "acme", "classic", "wai" };
    ArrayList<String> ignorePortalsList = new ArrayList<String>();
    Collections.addAll(ignorePortalsList, ignorePortals);
    Mockito.when(ignorePortalPlugin.getIgnorePortals()).thenReturn(ignorePortalsList);
    artifactService.addIgnorePortalPlugin(ignorePortalPlugin);
}
Example 96
Project: GATECH-master  File: CSVDataSetReader.java View source code
@Override
public DataSet read() throws Exception {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    List<Instance> data = new ArrayList<Instance>();
    Pattern pattern = Pattern.compile("[ ,]+");
    while ((line = br.readLine()) != null) {
        String[] split = pattern.split(line.trim());
        double[] input = new double[split.length];
        for (int i = 0; i < input.length; i++) {
            input[i] = Double.parseDouble(split[i]);
        }
        Instance instance = new Instance(input);
        data.add(instance);
    }
    br.close();
    Instance[] instances = (Instance[]) data.toArray(new Instance[0]);
    DataSet set = new DataSet(instances);
    set.setDescription(new DataSetDescription(set));
    return set;
}
Example 97
Project: hacktoolkit-android_lib-master  File: FacebookHelper.java View source code
@Override
public void onCompleted(List<GraphUser> users, Response response) {
    if (users != null) {
        List<String> friendsList = new ArrayList<String>();
        for (GraphUser user : users) {
            friendsList.add(user.getId());
        }
        // Construct a ParseUser query that will find friends whose
        // Facebook IDs are contained in the current user's friend list.
        ParseQuery<ParseUser> friendQuery = ParseQuery.getQuery("ParseUser");
        friendQuery.whereContainedIn("fbId", friendsList);
        // the current user
        try {
            List<ParseUser> friendUsers = friendQuery.find();
            callback.execute(friendUsers);
        } catch (ParseException e) {
        }
    }
}
Example 98
Project: dk-master  File: ColorLifeService.java View source code
public List<String> importInfo(List<Map<String, String>> paramList) throws SQLException {
    Connection conn = null;
    List<String> errorList = new ArrayList<String>();
    Long result = -1L;
    Map<String, String> paramMap;
    try {
        conn = MySQL.getConnection();
        for (int i = 0; i < paramList.size(); i++) {
            paramMap = paramList.get(i);
            Long id = colorLifeDao.addColorLife(conn, paramMap);
            if (id <= 0) {
                result = -1L;
                errorList.add("第" + (i + 2) + "行插入失败!");
            }
            result = 1L;
        }
        if (result > 0) {
            conn.commit();
        }
    } catch (SQLException e) {
        errorList.add("导入失败!");
        conn.rollback();
        e.printStackTrace();
    } finally {
        if (conn != null)
            conn.close();
    }
    return errorList;
}
Example 99
Project: CodingSpectator-master  File: T26.java View source code
@Override
protected void doExecuteRefactoring() {
    final String destinationForImports = "DestinationFile";
    bot.createANewJavaClass(getProjectName(), destinationForImports);
    bot.selectFromPackageExplorer(getProjectName(), "src", CodingSpectatorBot.PACKAGE_NAME, getTestFileFullName());
    bot.getBot().menu("Navigate").menu("Open").click();
    final String selection = "import java.util.ArrayList;\n" + "import java.util.Queue;";
    bot.selectElementToRefactor(getTestFileFullName(), 5, 0, selection.length());
    bot.invokeRefactoringFromMenu("Move...");
    bot.activateShellWithName("Textual Move");
    bot.getCurrentTree().expandNode(getProjectName(), "src", CodingSpectatorBot.PACKAGE_NAME, getTestFileFullName());
    bot.getCurrentTree().pressShortcut(org.eclipse.jface.bindings.keys.KeyStroke.getInstance('D'));
    bot.clickButtons(IDialogConstants.OK_LABEL);
}
Example 100
Project: download-manager-master  File: DownloadNotifierTest.java View source code
@Test
public void whenRemovingStaleNotificationsThenItDoesNotCrash() {
    Collection<DownloadBatch> batches = new ArrayList<>();
    DownloadBatch batchQueuedForWifi = getQueuedForWifiDownloadBatch();
    DownloadBatch batchRunning = getRunningDownloadBatch();
    batches.add(batchQueuedForWifi);
    batches.add(batchRunning);
    Collection<DownloadBatch> updatedBatches = new ArrayList<>();
    DownloadBatch batchQueuedForWifiUpdated = getQueuedForWifiDownloadBatch();
    updatedBatches.add(batchQueuedForWifiUpdated);
    DownloadNotifier downloadNotifier = new SynchronisedDownloadNotifier(mockContext, mockNotificationDisplayer);
    downloadNotifier.updateWith(batches);
    downloadNotifier.updateWith(updatedBatches);
}
Example 101
Project: stickypunch-master  File: WebsiteDeserializer.java View source code
@Override
public Website deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectCodec oc = jp.getCodec();
    JsonNode nodes = oc.readTree(jp);
    String websitePushID = nodes.get("websitePushID").getTextValue();
    String websiteName = nodes.get("websiteName").getTextValue();
    List<String> allowedDomains = new ArrayList<String>();
    for (JsonNode node : nodes.get("allowedDomains")) {
        allowedDomains.add(node.getTextValue());
    }
    String urlFormatString = nodes.get("urlFormatString").getTextValue();
    String authenticationToken = nodes.get("authenticationToken").getTextValue();
    String webServiceUrl = nodes.get("webServiceURL").getTextValue();
    return new WebsiteBuilder().setWebsiteName(websiteName).setWebsitePushId(websitePushID).setAllowedDomains(allowedDomains).setUrlFormatString(urlFormatString).setAuthenticationToken(authenticationToken).setWebServiceUrl(webServiceUrl).build();
}