javatips.net counter

Java Examples for java.util.LinkedList

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

Example 1
Project: j2objc-master  File: LinkedListTest.java View source code
/**
	 * @tests java.util.LinkedList#add(int, java.lang.Object)
	 */
public void test_addILjava_lang_Object() {
    // Test for method void java.util.LinkedList.add(int, java.lang.Object)
    Object o;
    ll.add(50, o = "Test");
    assertTrue("Failed to add Object>: " + ll.get(50).toString(), ll.get(50) == o);
    assertTrue("Failed to fix up list after insert", ll.get(51) == objArray[50] && (ll.get(52) == objArray[51]));
    ll.add(50, null);
    assertNull("Did not add null correctly", ll.get(50));
    try {
        ll.add(-1, "Test");
        fail("Should throw IndexOutOfBoundsException");
    } catch (IndexOutOfBoundsException e) {
    }
    try {
        ll.add(-1, null);
        fail("Should throw IndexOutOfBoundsException");
    } catch (IndexOutOfBoundsException e) {
    }
    try {
        ll.add(ll.size() + 1, "Test");
        fail("Should throw IndexOutOfBoundsException");
    } catch (IndexOutOfBoundsException e) {
    }
    try {
        ll.add(ll.size() + 1, null);
        fail("Should throw IndexOutOfBoundsException");
    } catch (IndexOutOfBoundsException e) {
    }
}
Example 2
Project: sosies-generator-master  File: CompareStackTrace.java View source code
public List<String> findDiff() {
    List<String> diffs = new LinkedList();
    originalStackTrace.reset();
    sosieStackTrace.reset();
    int oVar = 0, sVar = 0, call = 0;
    while (originalStackTrace.hasNext() && sosieStackTrace.hasNext()) {
        if (originalStackTrace.nextIsVar() || sosieStackTrace.nextIsVar()) {
            if (originalStackTrace.nextIsVar()) {
                //                    nextVar(originalStackTrace, sosieStackTrace.getStartLogging());
                originalStackTrace.next();
                oVar++;
            }
            if (sosieStackTrace.nextIsVar()) {
                //                    nextVar(sosieStackTrace, sosieStackTrace.getStartLogging());
                sosieStackTrace.next();
                sVar++;
            }
        } else {
            call++;
            sosieStackTrace.next();
            originalStackTrace.next();
        }
        StackTraceCall top1 = originalStackTrace.getTop();
        StackTraceCall top2 = sosieStackTrace.getTop();
        boolean sameTop = top1.equals(top2);
        if (sameTop) {
            testReport.addSameMethodCall(top1);
            if (originalStackTrace.getVariablesValueChange() || sosieStackTrace.getVariablesValueChange()) {
                Set<String> vd = varDiff(originalStackTrace, sosieStackTrace);
                if (!vd.isEmpty()) {
                    diffs.addAll(vd);
                }
            }
        } else {
            testReport.addDiffMethodCall(top1);
            testReport.addDiffMethodCall(top2);
            //                Log.info("stack trace diff: st1 size: {}, st2 size: {},\nst1 top: {}, st2 top: {}",deep1,deep2,top1,top2);
            findNewSyncro(20, 1, originalStackTrace, sosieStackTrace);
        }
    }
    return diffs;
}
Example 3
Project: VaadinUtils-master  File: JpaDslBuilderGroup.java View source code
private List<E> makeQuery(final JpaDslBuilderGroupItem<E> builder) {
    final JpaDslBuilder<E> q = new JpaDslBuilder<E>(entityClass);
    final List<Condition<E>> conditions = new LinkedList<>();
    if (common != null) {
        common.conditionsWillBeAdded(q, conditions);
    }
    if (builder != null) {
        builder.conditionsWillBeAdded(q, conditions);
    }
    if (distinct) {
        q.distinct();
    }
    q.where(conditions);
    for (JpaDslOrder order : orders) {
        q.orderBy(order.getField(), order.getAscending());
    }
    return q.getResultList();
}
Example 4
Project: solmix-master  File: SpringContainerFactoryTest.java View source code
@Test
public void test() {
    SpringContainerFactory ssc = new SpringContainerFactory();
    Container sc = ssc.createContainer();
    ConfiguredBeanProvider provider = sc.getExtension(ConfiguredBeanProvider.class);
    List<?> l = provider.getBeanOfType("java.util.LinkedList", List.class);
    Assert.assertNotNull(l);
    ExtensionManager em = sc.getExtension(ExtensionManager.class);
    Assert.assertNotNull(em);
    Assert.assertNotNull(sc);
    Assert.assertNotNull("adaptermanager must be not ull", sc.getExtension(org.solmix.runtime.adapter.AdapterManager.class));
}
Example 5
Project: OrganicBuilder-master  File: AtomTest.java View source code
/**
     * Test of breakAllBonds() and getAllConnectedAtoms(). *
     */
@Test
public void testGeneralMethods() {
    final Atom a1 = Atoms.createAtom(BasicType.A, 1);
    final Atom a2 = Atoms.createAtom(BasicType.A, 2);
    final Atom a3 = Atoms.createAtom(BasicType.A, 3);
    ;
    final Atom a4 = Atoms.createAtom(BasicType.A, 4);
    final Atom a5 = Atoms.createAtom(BasicType.A, 3);
    final Atom a6 = Atoms.createAtom(BasicType.A, 4);
    a1.bondWith(a2);
    a1.bondWith(a3);
    a1.bondWith(a6);
    a3.bondWith(a4);
    a3.bondWith(a5);
    a5.bondWith(a6);
    final LinkedList<Atom> l = new LinkedList<Atom>();
    a1.getAllConnectedAtoms(l);
    assertTrue(l.contains(a1));
    assertTrue(l.contains(a2));
    assertTrue(l.contains(a3));
    assertTrue(l.contains(a4));
    assertTrue(l.contains(a5));
    assertTrue(l.contains(a6));
    a1.breakAllBonds();
    l.clear();
    a1.getAllConnectedAtoms(l);
    assertTrue(l.contains(a1));
    l.remove(a1);
    assertTrue(l.isEmpty());
}
Example 6
Project: ilarkesto-master  File: LongestCommonSubsequenceList.java View source code
public static List<String> execute(List<String> a, List<String> b) {
    int n = a.size();
    int m = b.size();
    int S[][] = new int[n + 1][m + 1];
    int R[][] = new int[n + 1][m + 1];
    int ii, jj;
    // It is important to use <=, not <. The next two for-loops are initialization
    for (ii = 0; ii <= n; ++ii) {
        S[ii][0] = 0;
        R[ii][0] = UP;
    }
    for (jj = 0; jj <= m; ++jj) {
        S[0][jj] = 0;
        R[0][jj] = LEFT;
    }
    // backtracking arrays.
    for (ii = 1; ii <= n; ++ii) {
        for (jj = 1; jj <= m; ++jj) {
            if (a.get(ii - 1).equals(b.get(jj - 1))) {
                S[ii][jj] = S[ii - 1][jj - 1] + 1;
                R[ii][jj] = UP_AND_LEFT;
            } else {
                S[ii][jj] = S[ii - 1][jj - 1] + 0;
                R[ii][jj] = NEITHER;
            }
            if (S[ii - 1][jj] >= S[ii][jj]) {
                S[ii][jj] = S[ii - 1][jj];
                R[ii][jj] = UP;
            }
            if (S[ii][jj - 1] >= S[ii][jj]) {
                S[ii][jj] = S[ii][jj - 1];
                R[ii][jj] = LEFT;
            }
        }
    }
    // The length of the longest substring is S[n][m]
    ii = n;
    jj = m;
    int pos = S[ii][jj] - 1;
    String[] lcs = new String[pos + 1];
    // Trace the backtracking matrix.
    while (ii > 0 || jj > 0) {
        if (R[ii][jj] == UP_AND_LEFT) {
            ii--;
            jj--;
            lcs[pos--] = a.get(ii);
        } else if (R[ii][jj] == UP) {
            ii--;
        } else if (R[ii][jj] == LEFT) {
            jj--;
        }
    }
    return new LinkedList<String>(Arrays.asList(lcs));
}
Example 7
Project: Katari-master  File: ListApplicationsCommandTest.java View source code
@Test
public void testExecute() throws Exception {
    List<Application> applications = new LinkedList<Application>();
    // We add 3 applications: 2 supports the default view, the other does not.
    Application application1 = new Application(gadgetXmlUrl1);
    applications.add(application1);
    Application application2 = new Application(gadgetXmlUrl2);
    applications.add(application2);
    Application application3 = new Application(gadgetXmlUrlProfile);
    applications.add(application3);
    // Add 1 application to the gadget group that supports the default view.
    CoreUser user = new SampleUser("me");
    CustomizableGadgetGroup group;
    group = new CustomizableGadgetGroup(user, "gadget group", "default", 2);
    group.add(new GadgetInstance(application1, 0, 0));
    ApplicationRepository applicationRepository;
    applicationRepository = createMock(ApplicationRepository.class);
    expect(applicationRepository.findAll()).andReturn(applications);
    replay(applicationRepository);
    GadgetGroupRepository groupRepository;
    groupRepository = createMock(GadgetGroupRepository.class);
    expect(groupRepository.findGadgetGroup(1, "gadget group")).andReturn(group);
    replay(groupRepository);
    ContextUserService userService = createMock(ContextUserService.class);
    expect(userService.getCurrentUserId()).andReturn(1L);
    replay(userService);
    ListApplicationsCommand command;
    command = new ListApplicationsCommand(applicationRepository, groupRepository, userService);
    command.setGadgetGroupName("gadget group");
    // This should return just one application. Of the original 3, one is
    // already included and the other does not support the gadget container
    // view.
    List<Application> result = command.execute();
    assertThat(result.size(), is(1));
    assertThat(result.get(0).getTitle(), is("Test title 2"));
    verify(applicationRepository);
    verify(groupRepository);
}
Example 8
Project: clinic-softacad-master  File: SingleLineSqlCommandExtractor.java View source code
@Override
public String[] extractCommands(Reader reader) {
    BufferedReader bufferedReader = new BufferedReader(reader);
    List<String> statementList = new LinkedList<String>();
    try {
        for (String sql = bufferedReader.readLine(); sql != null; sql = bufferedReader.readLine()) {
            String trimmedSql = sql.trim();
            if (StringHelper.isEmpty(trimmedSql) || isComment(trimmedSql)) {
                continue;
            }
            if (trimmedSql.endsWith(";")) {
                trimmedSql = trimmedSql.substring(0, trimmedSql.length() - 1);
            }
            statementList.add(trimmedSql);
        }
        return statementList.toArray(new String[statementList.size()]);
    } catch (IOException e) {
        throw new ImportScriptException("Error during import script parsing.", e);
    }
}
Example 9
Project: katharsis-core-master  File: DirectRepositoryEntryBuilder.java View source code
@Override
public List<ResponseRelationshipEntry<?, ?>> buildRelationshipRepositories(ResourceLookup lookup, Class<?> resourceClass) {
    Set<Class<?>> relationshipRepositoryClasses = lookup.getResourceRepositoryClasses();
    Set<Class<?>> relationshipRepositories = findRelationshipRepositories(resourceClass, relationshipRepositoryClasses);
    List<ResponseRelationshipEntry<?, ?>> relationshipEntries = new LinkedList<>();
    for (Class<?> relationshipRepositoryClass : relationshipRepositories) {
        RelationshipRepository relationshipRepository = (RelationshipRepository) jsonServiceLocator.getInstance(relationshipRepositoryClass);
        if (relationshipRepository == null) {
            throw new RepositoryInstanceNotFoundException(relationshipRepositoryClass.getCanonicalName());
        }
        LOGGER.debug("Assigned {} RelationshipRepository  to {} resource class", relationshipRepositoryClass.getCanonicalName(), resourceClass.getCanonicalName());
        @SuppressWarnings("unchecked") DirectResponseRelationshipEntry<Object, Object> relationshipEntry = new DirectResponseRelationshipEntry<>(new RepositoryInstanceBuilder<>(jsonServiceLocator, (Class<RelationshipRepository>) relationshipRepositoryClass));
        relationshipEntries.add(relationshipEntry);
    }
    return relationshipEntries;
}
Example 10
Project: MUtils-master  File: ExampleUnitTest.java View source code
@Test
public void testListSizeComparator() {
    List<List<Integer>> list = new ArrayList<List<Integer>>();
    for (int i = 0; i < 5; i++) {
        int size = (int) (Math.random() * 10);
        List<Integer> itemList = new LinkedList<Integer>();
        for (int j = size; j >= 0; j--) {
            itemList.add(0);
        }
        list.add(itemList);
    }
    for (int i = 0; i < list.size(); i++) {
        System.out.print(list.get(i).size() + " ");
    }
    System.out.println();
    List<List<Integer>> sortedList = SortUtil.sortByListSize(list);
    for (int i = 0; i < sortedList.size(); i++) {
        System.out.print(sortedList.get(i).size() + " ");
    }
    System.out.println();
}
Example 11
Project: jade_agents-master  File: LinkedList.java View source code
/**
     * @see jade.util.leap.Collection interface
     */
public Iterator iterator() {
    return new Iterator() {

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

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

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

        /**
             * Method declaration
             * 
             * @see
             */
        public void remove() {
            it.remove();
        }
    };
}
Example 12
Project: eclipselink.runtime-master  File: CollectionReferenceReuseTestCases.java View source code
public Object getControlObject() {
    Employee emp = new Employee();
    emp.id = 3208;
    emp.name = "Dave Matthews";
    Address home = new Address();
    home.id = 1198;
    home.info = "727 Main Street, Anytown NY, 78228";
    home.type = "home";
    Address work = new Address();
    work.id = 1453;
    work.info = "30 Capital Ave Suite 100, Big Town NY, 78441";
    work.type = "work";
    Address other = new Address();
    other.id = 1676;
    other.info = "Site 17 RR#4, Boonies NY, 78112";
    other.type = "other";
    List<Address> addresses = new LinkedList<Address>();
    addresses.add(home);
    addresses.add(work);
    addresses.add(other);
    emp.addresses = addresses;
    Root root = new Root();
    root.employee = emp;
    root.addresses = addresses;
    return root;
}
Example 13
Project: WaveInCloud-master  File: FastQueueGwtTest.java View source code
public void testQueue() throws Exception {
    final int TEST_ITERS = 500;
    int nextInt = 0;
    Random random = new Random(1);
    Queue<Integer> queue = new FastQueue<Integer>();
    Queue<Integer> reference = new LinkedList<Integer>();
    for (int i = 0; i < TEST_ITERS; i++) {
        if (random.nextBoolean()) {
            // enqueue test
            Integer value = random.nextDouble() < 0.9 ? nextInt++ : null;
            queue.offer(value);
            reference.offer(value);
            assertEquals(reference.size(), queue.size());
        } else {
            // dequeue test
            Integer actual = queue.poll();
            Integer expected = reference.poll();
            assertEquals(expected, actual);
            assertEquals(reference.size(), queue.size());
        }
    }
    // try the rest
    while (!reference.isEmpty()) {
        Integer actual = queue.poll();
        Integer expected = reference.poll();
        assertEquals(expected, actual);
        assertEquals(reference.size(), queue.size());
    }
}
Example 14
Project: nicehair-master  File: ZoneAllParser.java View source code
@Override
public JsonResult parse(String json) throws JSONException {
    // TODO Auto-generated method stub
    ZoneResult result = new ZoneResult();
    LinkedList<ZoneAllItem> mListInfo = new LinkedList<ZoneAllItem>();
    if (!TextUtils.isEmpty(json)) {
        result.setSuccess(true);
        JSONObject newsObject = new JSONObject(json);
        JSONObject jsonObject = newsObject.getJSONObject("data");
        JSONArray blogsJson = jsonObject.getJSONArray("blogs");
        for (int i = 0; i < blogsJson.length(); i++) {
            JSONObject jsonObj = blogsJson.getJSONObject(i);
            ZoneAllItem info = new ZoneAllItem();
            info.setTitle(jsonObj.optString("albnm"));
            info.setName(jsonObj.optString("unm"));
            info.setHeadUrl(jsonObj.optString("ava"));
            info.setUid(jsonObj.optInt("uid"));
            info.setContent(jsonObj.optString("msg"));
            info.setLevel(10);
            info.setTime((i + 1) + "分钟前");
            info.setPariseNum(jsonObj.optInt("favc"));
            info.setChatNum(3 + i);
            info.setId(jsonObj.optInt("id"));
            String[] picArray = new String[3];
            List<Comment> listCom = new ArrayList<Comment>();
            for (int j = 0; j < 3; j++) {
                Comment com = new Comment();
                i++;
                if (i < blogsJson.length()) {
                    jsonObj = blogsJson.getJSONObject(i);
                    String url = jsonObj.optString("isrc");
                    picArray[j] = url;
                    com.setContent(jsonObj.optString("msg"));
                    com.setHeadUrl(jsonObj.optString("ava"));
                    com.setName(jsonObj.optString("unm"));
                    com.setToUId(jsonObj.optInt("uid"));
                    com.setId(jsonObj.optInt("id"));
                    com.setTime((i + 1) + "分钟前");
                    listCom.add(com);
                }
            }
            info.setPicArray(picArray);
            info.setListComment(listCom);
            mListInfo.add(info);
        }
    }
    result.setListInfo(mListInfo);
    return result;
}
Example 15
Project: GeoGig-master  File: RebuildGraphOp.java View source code
/**
     * Executes the [email protected] RebuildGraphOp} operation.
     * 
     * @return a list of [email protected] ObjectId}s that were found to be missing or incomplete
     */
@Override
protected ImmutableList<ObjectId> _call() {
    Repository repository = repository();
    Preconditions.checkState(!repository.isSparse(), "Cannot rebuild the graph of a sparse repository.");
    List<ObjectId> updated = new LinkedList<ObjectId>();
    ImmutableList<Ref> branches = command(BranchListOp.class).setLocal(true).setRemotes(true).call();
    GraphDatabase graphDb = repository.graphDatabase();
    for (Ref ref : branches) {
        Iterator<RevCommit> commits = command(LogOp.class).setUntil(ref.getObjectId()).call();
        while (commits.hasNext()) {
            RevCommit next = commits.next();
            if (graphDb.put(next.getId(), next.getParentIds())) {
                updated.add(next.getId());
            }
        }
    }
    return ImmutableList.copyOf(updated);
}
Example 16
Project: octarine-master  File: RecordRowMapper.java View source code
@Override
default Record map(ResultSet resultSet) {
    List<Value> columnValues = new LinkedList<>();
    configure(new ColumnMappings() {

        private int index = 1;

        @Override
        public <T> ColumnMappings add(Key<? super T> key, String columnName, ColumnMapper<? extends T> columnMapper) {
            Optional<T> maybeColumnValue = Optional.ofNullable(columnMapper.apply(resultSet, index));
            index += 1;
            maybeColumnValue.ifPresent( columnValue -> columnValues.add(key.of(columnValue)));
            return this;
        }
    });
    return Record.of(columnValues);
}
Example 17
Project: teiid-designer-master  File: TestFakeMappableObject.java View source code
// =========================================================================
//                      H E L P E R   M E T H O D S
// =========================================================================
public void helpTestCreateFakeMappableTree(final String namePrefix, final int startingType, final int endingType, final int numTypeInc, final int depth) {
    final List roots = new LinkedList();
    FakeMappableObject.createFakeMappableTree(roots, namePrefix, startingType, endingType, numTypeInc, depth);
    //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$ //$NON-NLS-5$
    System.out.println("Tree with namePrefix=" + namePrefix + "; startingType=" + startingType + "; endingType=" + endingType + "; numTypeInc=" + numTypeInc + "; depth=" + depth);
    final Iterator iter = roots.iterator();
    while (iter.hasNext()) {
        final FakeMappableObject obj = (FakeMappableObject) iter.next();
        //$NON-NLS-1$
        obj.print(System.out, " ");
    }
}
Example 18
Project: java-promises-master  File: ExecuteInOrderTestCase.java View source code
@Test
public void testReturnedPromiseMustBeRejectWithSameReasonWhenOnFulfilledThrowsAnException() {
    LinkedList<String> done = new LinkedList<String>();
    LinkedList<Exception> failed = new LinkedList<Exception>();
    Deferred<Integer> deferred = new Deferred<Integer>();
    Exception e = new Exception();
    deferred.promise.then(Callbacks.<Integer>throwHandler(e), Callbacks.<Exception>throwHandler()).then(Callbacks.<Void, String>addToHandler(done, "abc"), Callbacks.addToHandler(failed));
    deferred.resolve(3);
    assertEquals(Arrays.<String>asList(), done);
    assertEquals(Arrays.asList(e), failed);
}
Example 19
Project: breakout-master  File: TaskServiceBatcher.java View source code
@Override
protected void handleLater(LinkedList<M> batch) {
    synchronized (latestLock) {
        latestTask = createTask(batch);
        latestTask.batch = batch;
        latestTask.changeSupport().addPropertyChangeListener(this);
        taskService.submit(latestTask);
    }
}
Example 20
Project: dataverse-master  File: AddRoleAssigneesToExplicitGroupCommand.java View source code
@Override
public ExplicitGroup execute(CommandContext ctxt) throws CommandException {
    List<String> nonexistentRAs = new LinkedList<>();
    for (String rai : roleAssigneeIdentifiers) {
        RoleAssignee ra = null;
        try {
            ra = ctxt.roleAssignees().getRoleAssignee(rai);
        } catch (EJBException iae) {
            if (iae.getCausedByException() instanceof IllegalArgumentException) {
                throw new IllegalCommandException("Bad role assignee name:" + rai, this);
            }
        }
        if (ra == null) {
            nonexistentRAs.add(rai);
        } else {
            try {
                explicitGroup.add(ra);
            } catch (GroupException ex) {
                Logger.getLogger(AddRoleAssigneesToExplicitGroupCommand.class.getName()).log(Level.WARNING, "Error adding role assignee " + rai + " to group" + " " + explicitGroup.getIdentifier(), ex);
                throw new IllegalCommandException("Error adding " + rai + " to group " + explicitGroup.getIdentifier() + ": " + ex.getMessage(), this);
            }
        }
    }
    if (nonexistentRAs.isEmpty()) {
        return ctxt.explicitGroups().persist(explicitGroup);
    } else {
        StringBuilder sb = new StringBuilder();
        for (String s : nonexistentRAs) {
            sb.append(s).append(", ");
        }
        sb.setLength(sb.length() - 2);
        throw new IllegalCommandException("The following role assignees were not found: " + sb.toString(), this);
    }
}
Example 21
Project: erlide-master  File: CommandData.java View source code
// non-interactive
public void addUserInput(final List<String> input) {
    final List<OtpErlangObject> argsTmp = new LinkedList<>();
    final OtpErlangObject[] userInput = new OtpErlangObject[input.size()];
    int i = 0;
    for (final String text : input) {
        userInput[i] = new OtpErlangString(text);
        i++;
    }
    for (final OtpErlangObject arg : args) {
        if (arg instanceof OtpErlangTuple && ((OtpErlangTuple) arg).elementAt(0).equals(new OtpErlangAtom("prompt"))) {
            argsTmp.add(new OtpErlangList(userInput));
        // TODO make it so that it adds input only once, check repeat
        // interactive
        } else {
            argsTmp.add(arg);
        }
    }
    args = argsTmp.toArray(new OtpErlangObject[0]);
}
Example 22
Project: bixie-master  File: CallUnwinding.java View source code
public void unwindCalls(CfgProcedure p) {
    Log.debug("eliminateCalls for: " + p.getProcedureName());
    BasicBlock root = p.getRootNode();
    LinkedList<BasicBlock> todo = new LinkedList<BasicBlock>();
    LinkedList<BasicBlock> done = new LinkedList<BasicBlock>();
    todo.add(root);
    while (!todo.isEmpty()) {
        BasicBlock current = todo.pop();
        done.add(current);
        /*
			 * For each BasicBlock, iterate over the statements. If a statement
			 * is a call, collect all variables in the modifies clause and in
			 * the LHS of the call statement and replace the call by a Havoc for
			 * all these variables.
			 */
        LinkedList<CfgStatement> statements = current.getStatements();
        //shallow copy for iteration ... needed because we're modifying "statements"
        LinkedList<CfgStatement> iterlist = new LinkedList<CfgStatement>(statements);
        for (CfgStatement stmt : iterlist) {
            if (stmt instanceof CfgCallStatement) {
                CfgCallStatement call = (CfgCallStatement) stmt;
                int offset = 0;
                LinkedList<CfgStatement> callcontract = new LinkedList<CfgStatement>();
                //insert the assert statements that are enforced by the "requires" clauses
                //of the callee.
                HashMap<CfgVariable, CfgExpression> substitutes = new HashMap<CfgVariable, CfgExpression>();
                for (int j = offset; j < call.getCallee().getInParams().length; j++) {
                    substitutes.put(call.getCallee().getInParams()[j], call.getArguments()[j]);
                }
                for (CfgExpression xp : call.getCallee().getRequires()) {
                    callcontract.add(new CfgAssertStatement(call.getLocation(), xp.substitute(substitutes)));
                }
                //create the havoc statement for the modifies clause.
                HashSet<CfgVariable> modifies = new HashSet<CfgVariable>();
                modifies.addAll(call.getCallee().getModifies());
                for (CfgIdentifierExpression lhs : call.getLeftHandSide()) {
                    modifies.add(lhs.getVariable());
                }
                CfgHavocStatement havoc = new CfgHavocStatement(call.getLocation(), modifies.toArray(new CfgVariable[modifies.size()]));
                // Log.error(" call: "+ call.toString());
                // Log.error(" becomes: "+ havoc.toString());
                havoc.setReplacedStatement(call);
                callcontract.add(havoc);
                //insert the assume statements that are guaranteed by the "ensures" clauses
                //of the callee.
                substitutes = new HashMap<CfgVariable, CfgExpression>();
                for (int j = offset; j < call.getCallee().getOutParams().length; j++) {
                    substitutes.put(call.getCallee().getOutParams()[j], call.getLeftHandSide()[j]);
                }
                for (CfgExpression xp : call.getCallee().getEnsures()) {
                    if (statements.indexOf(stmt) < statements.size() - 1) {
                        statements.add(new CfgAssumeStatement(call.getLocation(), xp.substitute(substitutes)));
                    } else {
                        callcontract.add(new CfgAssumeStatement(call.getLocation(), xp.substitute(substitutes)));
                    }
                }
                //now merge callcontract back into statements at and replace the original call stmt.					
                statements.addAll(statements.indexOf(stmt), callcontract);
                //and now remove the old call statement.
                statements.remove(stmt);
            } else {
            //TODO
            }
        }
        current.setStatements(statements);
        for (BasicBlock next : current.getSuccessors()) {
            if (!todo.contains(next) && !done.contains(next)) {
                todo.add(next);
            }
        }
    }
}
Example 23
Project: wso2-synapse-master  File: EndDelimitedProtocolTest.java View source code
public void test() throws IOException {
    byte delimiter = 0;
    Random random = new Random();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    List<byte[]> messages = new LinkedList<byte[]>();
    for (int i = 0; i < 20; i++) {
        int size = 64 + random.nextInt(2048);
        byte[] data = new byte[size];
        for (int j = 0; j < size; j++) {
            data[j] = (byte) (32 + random.nextInt(96));
        }
        out.write(data);
        out.write(delimiter);
        messages.add(data);
    }
    EndDelimitedProtocol protocol = new EndDelimitedProtocol();
    protocol.setDelimiter(delimiter);
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    ProtocolDecoder decoder = protocol.createProtocolDecoder();
    byte[] readBuffer = new byte[1024];
    while (true) {
        int remaining = messages.size();
        while (decoder.inputRequired()) {
            int c = in.read(readBuffer);
            if (c == -1) {
                assertTrue("Expected " + remaining + " more messages", remaining == 0);
                return;
            }
            decoder.decode(readBuffer, 0, c);
        }
        assertTrue("Didn't expecte any more messages", remaining != 0);
        byte[] actual = decoder.getNext();
        byte[] expected = messages.remove(0);
        assertEquals(new String(expected, "us-ascii"), new String(actual, "us-ascii"));
    }
}
Example 24
Project: streamex-master  File: InternalsTest.java View source code
@Test
public void testArrayCollection() {
    Collection<Object> collection = new ArrayCollection(new Object[] { "1", "2" });
    List<Object> list = new LinkedList<>(collection);
    assertEquals("1", list.get(0));
    assertEquals("2", list.get(1));
    List<Object> list2 = new ArrayList<>(collection);
    assertEquals("1", list.get(0));
    assertEquals("2", list.get(1));
    assertEquals(list2, list);
    Set<Object> set = new HashSet<>(collection);
    assertTrue(set.contains("1"));
    assertTrue(set.contains("2"));
    assertEquals(2, set.size());
}
Example 25
Project: cloudtm-data-platform-master  File: LockPerEntryTest.java View source code
@Test(enabled = false)
public void testLocksConcurrency() throws Exception {
    cache = cacheManager.getCache();
    final int NUM_THREADS = 10;
    final CountDownLatch l = new CountDownLatch(1);
    final int numLoops = 1000;
    final List<Exception> exceptions = new LinkedList<Exception>();
    Thread[] t = new Thread[NUM_THREADS];
    for (int i = 0; i < NUM_THREADS; i++) t[i] = new Thread() {

        public void run() {
            try {
                l.await();
            } catch (Exception e) {
            }
            for (int i = 0; i < numLoops; i++) {
                try {
                    switch(i % 2) {
                        case 0:
                            cache.put("Key" + i, "v");
                            break;
                        case 1:
                            cache.remove("Key" + i);
                            break;
                    }
                } catch (Exception e) {
                    exceptions.add(e);
                }
            }
        }
    };
    for (Thread th : t) th.start();
    l.countDown();
    for (Thread th : t) th.join();
    if (!exceptions.isEmpty())
        throw exceptions.get(0);
    assertNoLocks();
}
Example 26
Project: cdo-master  File: CDOExplorerUtil.java View source code
public static CDOCheckout walkUp(Object object, LinkedList<Object> path) {
    while (object != null) {
        if (path != null) {
            path.addFirst(object);
        }
        if (object instanceof CDOCheckout) {
            return (CDOCheckout) object;
        }
        if (object instanceof EObject) {
            EObject eObject = (EObject) object;
            Adapter adapter = EcoreUtil.getAdapter(eObject.eAdapters(), CDOCheckout.class);
            if (adapter != null) {
                return (CDOCheckout) adapter;
            }
        }
        object = getParent(object);
    }
    return null;
}
Example 27
Project: google-web-toolkit-svnmirror-master  File: ReflectionUtils.java View source code
public static <A extends Annotation> A getAnnotation(Class<?> clazz, Class<A> annotClass, boolean forceInherit) {
    boolean inherited = forceInherit || annotClass.isAnnotationPresent(Inherited.class);
    LinkedList<Class<?>> workQueue = new LinkedList<Class<?>>();
    workQueue.add(clazz);
    while (!workQueue.isEmpty()) {
        clazz = workQueue.removeFirst();
        A result = clazz.getAnnotation(annotClass);
        if (result != null || !inherited) {
            return result;
        }
        Class<?> superClass = clazz.getSuperclass();
        if (superClass != null) {
            workQueue.addLast(superClass);
        }
        workQueue.addAll(Arrays.asList((Class<?>[]) clazz.getInterfaces()));
    }
    return null;
}
Example 28
Project: keycloak-master  File: ValidatePassword.java View source code
@Override
public void authenticate(AuthenticationFlowContext context) {
    MultivaluedMap<String, String> inputData = context.getHttpRequest().getDecodedFormParameters();
    List<UserCredentialModel> credentials = new LinkedList<>();
    String password = inputData.getFirst(CredentialRepresentation.PASSWORD);
    boolean valid = context.getSession().userCredentialManager().isValid(context.getRealm(), context.getUser(), UserCredentialModel.password(password));
    if (!valid) {
        context.getEvent().user(context.getUser());
        context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);
        Response challengeResponse = errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "invalid_grant", "Invalid user credentials");
        context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
        return;
    }
    context.success();
}
Example 29
Project: dashbuilder-master  File: AbstractDataSetDefValidator.java View source code
protected Class[] getValidationGroups(final boolean isCacheEnabled, final boolean isPushEnabled, final boolean isRefreshEnabled, final Class... groups) {
    List<Class> classes = new LinkedList<Class>();
    classes.add(DataSetDefBasicAttributesGroup.class);
    classes.add(DataSetDefProviderTypeGroup.class);
    if (isCacheEnabled) {
        classes.add(DataSetDefCacheRowsValidation.class);
    }
    if (isPushEnabled) {
        classes.add(DataSetDefPushSizeValidation.class);
    }
    if (isRefreshEnabled) {
        classes.add(DataSetDefRefreshIntervalValidation.class);
    }
    if (groups != null) {
        for (final Class group : groups) {
            classes.add(group);
        }
    }
    return classes.toArray(new Class[classes.size()]);
}
Example 30
Project: org.eclipse.ecr-master  File: Insert.java View source code
/**
     * Gets the statement to insert a row, or copy it if [email protected] #setValues} has
     * been called.
     * <p>
     * Example: [email protected] INSERT INTO foo (a, b, c) SELECT ?, b, c FROM foo WHERE
     * id = ?}
     *
     * @return the SQL insert or copy statement
     */
public String getStatement() {
    StringBuilder buf = new StringBuilder(128);
    buf.append("INSERT INTO ");
    buf.append(table.getQuotedName());
    buf.append(' ');
    List<String> columnNames = new LinkedList<String>();
    List<String> values = new LinkedList<String>();
    for (Column column : columns) {
        columnNames.add(column.getQuotedName());
        values.add(column.getFreeVariableSetter());
    }
    if (columnNames.isEmpty()) {
        buf.append(dialect.getNoColumnsInsertString());
    } else {
        buf.append('(');
        buf.append(StringUtils.join(columnNames, ", "));
        buf.append(") ");
        if (insertValues == null) {
            buf.append("VALUES (");
            buf.append(StringUtils.join(values, ", "));
            buf.append(')');
        } else {
            buf.append(insertValues);
        }
    }
    return buf.toString();
}
Example 31
Project: GlowstonePlusPlus-master  File: GlowCreature.java View source code
@Override
public List<Message> createSpawnMessage() {
    List<Message> result = new LinkedList<>();
    // spawn mob
    int x = Position.getIntX(location);
    int y = Position.getIntY(location);
    int z = Position.getIntZ(location);
    int yaw = Position.getIntYaw(location);
    int pitch = Position.getIntPitch(location);
    result.add(new SpawnMobMessage(id, type.getTypeId(), x, y, z, yaw, pitch, pitch, 0, 0, 0, metadata.getEntryList()));
    // head facing
    result.add(new EntityHeadRotationMessage(id, yaw));
    //result.add(createEquipmentMessage());
    return result;
}
Example 32
Project: cdt-tests-runner-master  File: MIRegistersTest_7_2.java View source code
// GDB's list of registers is different with GDB 7.2
@Override
protected List<String> get_X86_REGS() {
    List<String> list = new LinkedList<String>(Arrays.asList("eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "eip", "eflags", "cs", "ss", "ds", "es", "fs", "gs", "st0", "st1", "st2", "st3", "st4", "st5", "st6", "st7", "fctrl", "fstat", "ftag", "fiseg", "fioff", "foseg", "fooff", "fop", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", /*"","","","","","","","",*/
    "mxcsr", "orig_eax", "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh", "ax", "cx", /*"",*/
    "dx", "bx", "bp", "si", "di", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7"));
    // On Windows, gdb doesn't report "orig_eax" as a register. Apparently it does on Linux
    if (Platform.getOS().equals(Platform.OS_WIN32)) {
        list.remove("orig_eax");
    }
    return list;
}
Example 33
Project: dcache-master  File: SourceBackedPredicateMap.java View source code
/**
     * Get values from the map belonging to a specific key
     * @param key Key to be used to find corresponding values
     * @return Collection of matching values
     */
public synchronized List<TValue> getValuesForPredicatesMatching(TKey key) {
    if (_source.hasChanged()) {
        try {
            _log.info("Source changed. Recreating map.");
            createMapFromData(_source.getContent());
        } catch (IOException e) {
            _log.error("Error creating map.", e);
            return Collections.emptyList();
        }
    }
    List<TValue> result = new LinkedList<>();
    for (Entry<MapPredicate<TKey>, TValue> predicateEntry : _predicateValueMap.entrySet()) {
        if (predicateEntry.getKey().matches(key)) {
            result.add(predicateEntry.getValue());
        }
    }
    return result;
}
Example 34
Project: xchain-master  File: TestValidate3.java View source code
public boolean execute(JXPathContext context) throws Exception {
    Session session = HibernateLifecycle.getCurrentSession(getName(context));
    Map contextHolder = new HashMap();
    List beans = new LinkedList();
    Person bean1 = new Person();
    beans.add(bean1);
    Person bean2 = new Person();
    beans.add(bean2);
    Person bean3 = new Person();
    bean3.setId(new Integer(1234));
    bean3.setName("Test Person");
    beans.add(bean3);
    contextHolder.put("beans", beans);
    context.getVariables().declareVariable("test-validate-beans", contextHolder);
    // execute the chain 
    return super.execute(context);
}
Example 35
Project: eis-master  File: PerceptHandlerTest.java View source code
/**
	 * Check that all percepts have been received
	 * 
	 * @param percepts
	 */
private void assertAllPerceptsReceived(LinkedList<Percept> percepts) {
    assertTrue(percepts.contains(entity.getAlways()));
    assertTrue(percepts.contains(entity.getOnce()));
    assertTrue(percepts.contains(entity.getOnChange()));
    assertFalse(percepts.contains(entity.getOnChanged()));
    assertTrue(percepts.containsAll(entity.getOnChangeNegation()));
    assertFalse(percepts.containsAll(entity.getOnChangedNegation()));
    assertTrue(percepts.containsAll(entity.getMultipleAlways()));
    assertTrue(percepts.containsAll(entity.getMultipleOnChange()));
    assertTrue(percepts.contains(entity.getMultiArgs()));
    assertTrue(percepts.containsAll(entity.getMultipleMultiArgs()));
}
Example 36
Project: android-essentials-toolbox-master  File: SanityChecks.java View source code
@Test
public void testUnassignedProtectionLevelPermissionsAreNotAssigned() {
    Collection<ProtectionLevel> protectionLevels = new LinkedList<ProtectionLevel>();
    protectionLevels.addAll(ProtectionLevel.getAllProtectionLevels());
    protectionLevels.remove(ProtectionLevel.UNASSIGNED);
    for (ProtectionLevel pl : protectionLevels) {
        for (Permission permission : pl.getPermissions()) {
            if (ProtectionLevel.UNASSIGNED.getPermissions().contains(permission)) {
                System.err.println(permission.getQualifiedName() + " is assigned to " + pl.getName() + " but is also in the unassigned protection level!");
            }
            assertTrue(!ProtectionLevel.UNASSIGNED.getPermissions().contains(permission));
        }
    }
}
Example 37
Project: schach-master  File: Fingerprint.java View source code
/*
     * Gibt einen eindeutigen Fingerprint des aktuellen Spielfeldes
     * (Schachfiguren auf Brett) zurueck, um eine Situation zu identifizieren
     * 
     * @param map HashMap<Integer,Byte> mit Situation von der Fingerprint
     * erstellt werden soll
     * 
     * @return String Fingerprint als String als Format
     * "pos1,figwert1--pos2,figwert2--..."
     */
@SuppressWarnings("unchecked")
public static String getFingerprint(HashMap<Integer, Byte> map) {
    HashMap<Integer, Byte> cloneMap = (HashMap<Integer, Byte>) map.clone();
    String fingerprint = "";
    Iterator<Entry<Integer, Byte>> it = cloneMap.entrySet().iterator();
    /*
         * Da die HashMap die Eintraege unterschiedlich ausliest, ist hier die Moeglichkeit,
         * FigureValue mit position zu verknuepfen um sie dann sortieren zu koennen.
         */
    class Identifier implements Comparable {

        byte figureValue;

        int position;

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

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

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

        public int compareTo(Object id) {
            int position;
            if (id instanceof Identifier) {
                position = ((Identifier) id).getPosition();
                return (position - this.position);
            } else {
                return 0;
            }
        }
    }
    List<Identifier> id = new LinkedList<Identifier>();
    while (it.hasNext()) {
        Map.Entry<Integer, Byte> pair = (Map.Entry<Integer, Byte>) it.next();
        byte figureValue = pair.getValue();
        int position = pair.getKey().intValue();
        id.add(new Identifier(figureValue, position));
        it.remove();
    }
    //fuer einen eindeutigen Fingerprint, muss Liste sortiert werden.
    Collections.sort(id);
    while (id.size() > 0) {
        fingerprint += id.get(0).getPosition() + "," + id.get(0).getFigureValue() + "--";
        id.remove(0);
    }
    fingerprint = fingerprint.substring(0, fingerprint.length() - 2);
    return fingerprint;
}
Example 38
Project: picard-tools-master  File: AddCommentsToBamTest.java View source code
@Test
public void testAddCommentsToBam() throws Exception {
    final File outputFile = File.createTempFile("addCommentsToBamTest.", BamFileIoUtils.BAM_FILE_EXTENSION);
    runIt(INPUT_FILE, outputFile, commentList);
    final SAMFileHeader newHeader = new SAMFileReader(outputFile).getFileHeader();
    // The original comments are massaged when they're added to the header. Perform the same massaging here,
    // and then compare the lists
    final List<String> massagedComments = new LinkedList<String>();
    for (final String comment : commentList) {
        massagedComments.add(SAMTextHeaderCodec.COMMENT_PREFIX + comment);
    }
    Assert.assertEquals(newHeader.getComments(), massagedComments);
}
Example 39
Project: tmdm-studio-se-master  File: DeleteAction.java View source code
private List<IRepositoryNode> getRemainNodes() {
    ISelection selection = getSelectionProvider().getSelection();
    List<IRepositoryNode> nodes = new LinkedList<IRepositoryNode>();
    if (!selection.isEmpty()) {
        for (Iterator il = ((IStructuredSelection) selection).iterator(); il.hasNext(); ) {
            IRepositoryNode node = (IRepositoryNode) il.next();
            nodes.add(node);
        }
        final DeleteActionCache deleteActionCache = DeleteActionCache.getInstance();
        deleteActionCache.setGetAlways(false);
        deleteActionCache.setDocRefresh(false);
        deleteActionCache.createRecords();
        final List<ItemReferenceBean> unDeleteItems = RepositoryNodeDeleteManager.getInstance().getUnDeleteItems(nodes, deleteActionCache);
    }
    return nodes;
}
Example 40
Project: cdt-master  File: ResourceExclusion.java View source code
@Override
public synchronized boolean testExclusion(IResource resource) {
    // Populate the resources to be excluded by this exclusion.
    List<IResource> excludedResources = new LinkedList<IResource>();
    List<ExclusionInstance> exclusionInstances = getExclusionInstances();
    for (ExclusionInstance instance : exclusionInstances) {
        excludedResources.add(instance.getResource());
    }
    if (excludedResources.contains(resource)) {
        return true;
    }
    // Check to see if the given resource is part of this exclusion.
    for (IResource excludedResource : excludedResources) {
        // TODO: need to update this for Phase 2 implementation
        if (excludedResource instanceof IContainer) {
            IContainer container = (IContainer) excludedResource;
            if (container.getFullPath().isPrefixOf(resource.getFullPath())) {
                return true;
            }
        }
    }
    return false;
}
Example 41
Project: aws-toolkit-eclipse-master  File: DeploymentsTableViewTreePathContentCache.java View source code
private Object[] loadChildren(TreePath parent) {
    if (parent.getSegmentCount() == 0) {
        // root
        List<DeploymentInfo> deployments = ServiceAPIUtils.getAllDeployments(editorInput.getCodeDeployClient(), editorInput.getApplicationName(), editorInput.getDeploymentGroupName());
        // Sort by creation data
        Collections.sort(deployments, new Comparator<DeploymentInfo>() {

            public int compare(DeploymentInfo a, DeploymentInfo b) {
                int a_to_b = a.getCreateTime().compareTo(b.getCreateTime());
                // In descending order
                return -a_to_b;
            }
        });
        return deployments.toArray(new DeploymentInfo[deployments.size()]);
    } else {
        Object lastSegment = parent.getLastSegment();
        if (lastSegment instanceof DeploymentInfo) {
            DeploymentInfo deployment = (DeploymentInfo) lastSegment;
            List<InstanceSummary> instances = ServiceAPIUtils.getAllDeploymentInstances(editorInput.getCodeDeployClient(), deployment.getDeploymentId());
            return instances.toArray(new InstanceSummary[instances.size()]);
        } else if (lastSegment instanceof InstanceSummary) {
            InstanceSummary deploymentInstance = (InstanceSummary) lastSegment;
            List<LifecycleEvent> events = deploymentInstance.getLifecycleEvents();
            if (events == null) {
                events = new LinkedList<LifecycleEvent>();
            }
            return events.toArray(new LifecycleEvent[events.size()]);
        }
    }
    return new Object[0];
}
Example 42
Project: android-bankdroid-master  File: LegacyProviderConfiguration.java View source code
private List<Field> createConfiguration() {
    List<Field> configuration = new LinkedList<>();
    configuration.add(new FieldBuilder(USERNAME).label(mLegacyBank.getContext().getString(mLegacyBank.getInputTitleUsername())).placeholder(mLegacyBank.getInputHintUsername()).hidden(mLegacyBank.isInputUsernameHidden()).required(true).fieldType(FieldTypeMapper.toFieldType(mLegacyBank.getInputTypeUsername())).build());
    configuration.add(new FieldBuilder(PASSWORD).label(mLegacyBank.getContext().getString(mLegacyBank.getInputTitlePassword())).hidden(mLegacyBank.isInputPasswordHidden()).secret(true).required(!mLegacyBank.isInputPasswordHidden()).fieldType(FieldTypeMapper.toFieldType(mLegacyBank.getInputTypePassword())).build());
    configuration.add(new FieldBuilder(EXTRAS).label(mLegacyBank.getContext().getString(mLegacyBank.getInputTitleExtras())).hidden(mLegacyBank.isInputExtrasHidden()).fieldType(FieldTypeMapper.toFieldType(mLegacyBank.getInputTypeExtras())).build());
    return configuration;
}
Example 43
Project: galen-master  File: SpecOnProcessor.java View source code
@Override
public Spec process(StringCharReader reader, String contextPath) {
    List<String> allEdges = new LinkedList<>();
    boolean edgesAreNotRead = true;
    while (edgesAreNotRead && reader.hasMore()) {
        String word = reader.readWord();
        if (word.equals("edge")) {
            edgesAreNotRead = false;
        } else {
            allEdges.add(word);
        }
    }
    if (edgesAreNotRead) {
        throw new SyntaxException("Missing \"edge\"");
    }
    if (allEdges.size() > 2) {
        throw new SyntaxException("Too many sides. Should use only 2");
    }
    Side sideHorizontal = Side.TOP;
    Side sideVertical = Side.LEFT;
    boolean isFirstHorizontal = false;
    if (allEdges.size() > 0) {
        Side side = Side.fromString(allEdges.get(0));
        if (side == Side.TOP || side == Side.BOTTOM) {
            isFirstHorizontal = true;
            sideHorizontal = side;
        } else
            sideVertical = side;
    }
    if (allEdges.size() > 1) {
        Side side = Side.fromString(allEdges.get(1));
        if (side == Side.TOP || side == Side.BOTTOM) {
            if (isFirstHorizontal) {
                throw new SyntaxException("Cannot use theses sides: " + allEdges.get(0) + " " + allEdges.get(1));
            }
            sideHorizontal = side;
        } else {
            if (!isFirstHorizontal) {
                throw new SyntaxException("Cannot use theses sides: " + allEdges.get(0) + " " + allEdges.get(1));
            }
            sideVertical = side;
        }
    }
    String objectName = reader.readWord();
    if (objectName.isEmpty()) {
        throw new SyntaxException("Missing object name");
    }
    List<Location> locations = Expectations.locations().read(reader);
    return new SpecOn(objectName, sideHorizontal, sideVertical, locations);
}
Example 44
Project: heron-master  File: ShuffleGroupingTest.java View source code
/**
   * Method: test round robin nature of shuffle grouping
   */
@Test
public void testRoundRobin() throws Exception {
    List<Integer> taskIds = new LinkedList<>();
    taskIds.add(0);
    taskIds.add(2);
    taskIds.add(4);
    taskIds.add(8);
    ShuffleGrouping g = new ShuffleGrouping(taskIds);
    HeronTuples.HeronDataTuple dummy = HeronTuples.HeronDataTuple.getDefaultInstance();
    List<Integer> dest = g.getListToSend(dummy);
    Assert.assertEquals(dest.size(), 1);
    int first = dest.get(0);
    int index = -1;
    for (int i = 0; i < taskIds.size(); ++i) {
        if (taskIds.get(i) == first) {
            index = i;
            break;
        }
    }
    dest.clear();
    for (int i = 0; i < 100; ++i) {
        dest = g.getListToSend(dummy);
        Assert.assertEquals(dest.size(), 1);
        int d = dest.get(0);
        index = (index + 1) % taskIds.size();
        Assert.assertEquals((Integer) d, taskIds.get(index));
        dest.clear();
    }
}
Example 45
Project: SideScrollerGDW2012-Max-master  File: WindowsIpaddressen.java View source code
private LinkedList<InetAddress> getSubnet() throws IOException {
    Process process = Runtime.getRuntime().exec("ipconfig");
    Scanner scanner = new Scanner(process.getInputStream());
    LinkedList<InetAddress> result = new LinkedList<InetAddress>();
    String line;
    //get Programmoutput
    while (scanner.hasNextLine()) {
        if ((line = scanner.nextLine()).contains("IPv4")) {
            String partResult = new String();
            //found input
            String ipAddress = line.split(":")[1];
            line = scanner.nextLine();
            String subnetMask = line.split(":")[1];
            ipAddress = ipAddress.trim();
            subnetMask = subnetMask.trim();
            //split into parts	
            String[] ipAddressParts = ipAddress.split("\\.");
            String[] subnetMaskParts = subnetMask.split("\\.");
            //parse...
            for (int i = 0; i < 4; ++i) {
                if (subnetMaskParts[i].equals("255")) //copy complete
                {
                    partResult += ipAddressParts[i] + ".";
                } else if (subnetMaskParts[i].equals("0")) //empty part
                {
                    partResult += "255.";
                } else //calc...
                {
                    short ipValue = Short.parseShort(ipAddressParts[i]);
                    short subValue = Short.parseShort(subnetMaskParts[i]);
                    subValue *= -1;
                    ipValue &= subValue;
                    partResult += Short.toString(ipValue) + ".";
                }
            }
            //debug
            String sringResult = partResult.substring(0, partResult.length() - 1);
            result.add(InetAddress.getByName(sringResult));
        }
    }
    return result;
}
Example 46
Project: powermock-master  File: PowerMockExpectedExceptionsExtractorImpl.java View source code
public String[] getPackagesToIgnore(AnnotatedElement element) {
    List<String> ignoredPackages = new LinkedList<String>();
    if (element instanceof Class<?>) {
        Class<?> klazz = (Class<?>) element;
        for (Method method : klazz.getMethods()) {
            Test annotation = method.getAnnotation(Test.class);
            if (annotation != null) {
                Class<?>[] ignores = annotation.expectedExceptions();
                if (ignores != null) {
                    for (Class<?> ignorePackage : ignores) {
                        ignoredPackages.add(ignorePackage.getName());
                    }
                }
            }
        }
        Class<?> superclass = klazz.getSuperclass();
        if (superclass != null && !superclass.equals(Object.class)) {
            String[] packagesToIgnore = getPackagesToIgnore(superclass);
            ignoredPackages.addAll(Arrays.asList(packagesToIgnore));
        }
    }
    return ignoredPackages.toArray(new String[ignoredPackages.size()]);
}
Example 47
Project: REST-OCD-Services-master  File: CostFunction.java View source code
public double value(LinkedList<Cluster> clust, int numbNode) {
    double res = 0;
    double tempRes = 0;
    Similarities sim = new Similarities();
    for (Iterator<Cluster> it = clust.iterator(); it.hasNext(); ) {
        Cluster curr = it.next();
        ArrayRealVector cent = curr.getCentroid();
        for (Iterator<Point> iter = curr.getPoints().iterator(); iter.hasNext(); ) {
            Point p = iter.next();
            tempRes = 1 - sim.cosineSim(cent, p.getCoordinates());
            res = res + tempRes;
        }
    }
    res = res / numbNode;
    return res;
}
Example 48
Project: many-ql-master  File: AddEventualEmptyTransformationToProductions.java View source code
@Override
public void inAProd(AProd node) {
    currentProd = (String) ids.names.get(node);
    /* IfStmt there is no transformation specified for the production
     * and there is no AST production which has the same name as the current
     * CST production, this production is transformed into an empty
     */
    if (node.getArrow() == null && ast_ids.ast_prods.get(currentProd) == null) {
        node.setArrow(new TArrow(node.getId().getLine(), node.getId().getPos() + node.getId().getText().length()));
        node.setProdTransform(new LinkedList());
        AAlt[] alts = (AAlt[]) node.getAlts().toArray(new AAlt[0]);
        for (int i = 0; i < alts.length; i++) {
            alts[i].apply(new DepthFirstAdapter() {

                @Override
                public void inAAlt(AAlt node) {
                    if (node.getAltTransform() != null && ((AAltTransform) node.getAltTransform()).getTerms().size() > 0) {
                        error(((AAltTransform) node.getAltTransform()).getLBrace());
                    }
                    node.setAltTransform(new AAltTransform(new TLBrace(), new LinkedList(), new TRBrace()));
                }
            });
        }
    }
}
Example 49
Project: framework-master  File: ConnectorHelper.java View source code
/**
     * Creates a string containing hierarchy information for the connector
     *
     * @since 7.1
     * @param connector
     *            The connector to get hierarchy information for
     * @param builder
     *            The StringBuilder where the information should be written
     */
public static void writeHierarchyInformation(ClientConnector connector, StringBuilder builder) {
    LinkedList<ClientConnector> h = new LinkedList<>();
    h.add(connector);
    ClientConnector parent = connector.getParent();
    while (parent != null) {
        h.addFirst(parent);
        parent = parent.getParent();
    }
    builder.append("\nConnector hierarchy:\n");
    int l = 0;
    for (ClientConnector connector2 : h) {
        if (l != 0) {
            builder.append("\n");
            for (int i = 0; i < l; i++) {
                builder.append("  ");
            }
        }
        l++;
        Class<? extends ClientConnector> connectorClass = connector2.getClass();
        Class<?> topClass = connectorClass;
        while (topClass.getEnclosingClass() != null) {
            topClass = topClass.getEnclosingClass();
        }
        builder.append(connectorClass.getName());
        builder.append("(");
        builder.append(topClass.getSimpleName());
        builder.append(".java:1)");
    }
}
Example 50
Project: TextSecureSMP-master  File: ListPartitionTest.java View source code
public void testPartitionEven() {
    List<Integer> list = new LinkedList<>();
    for (int i = 0; i < 100; i++) {
        list.add(i);
    }
    List<List<Integer>> partitions = Util.partition(list, 10);
    assertEquals(partitions.size(), 10);
    int counter = 0;
    for (int i = 0; i < partitions.size(); i++) {
        List<Integer> partition = partitions.get(i);
        assertEquals(partition.size(), 10);
        for (int j = 0; j < partition.size(); j++) {
            assertEquals((int) partition.get(j), counter++);
        }
    }
}
Example 51
Project: keratin-irc-master  File: HandlerContainerDetector.java View source code
/**
     * Get classes annotated with the HandlerContainer annotation.
     * 
     * @return All HandlerContainer annotated classes
     * @see HandlerContainer
     */
public static List<Class<?>> getContainers() {
    if (containers == null) {
        final LinkedList<Class<?>> containersTemp = new LinkedList<Class<?>>();
        Reporter containerReporter = new TypeReporter() {

            @SuppressWarnings("unchecked")
            @Override
            public Class<? extends Annotation>[] annotations() {
                return new Class[] { HandlerContainer.class };
            }

            @Override
            public void reportTypeAnnotation(Class<? extends Annotation> annotation, String className) {
                try {
                    containersTemp.add(Class.forName(className));
                } catch (ClassNotFoundException e) {
                    Logger.error(e, "Could not load detected annotated class");
                }
            }
        };
        AnnotationDetector containerDetector = new AnnotationDetector(containerReporter);
        try {
            containerDetector.detect();
        } catch (IOException e) {
            Logger.error(e, "Problem when detecting annotations");
        }
        containers = containersTemp;
    }
    return containers;
}
Example 52
Project: GATECH-master  File: DialogSplitterUtility.java View source code
/**
	 * Form a list of sentences that are all below maxL in length without
	 * cutting words.
	 * 
	 * @param words
	 *            trimmed list of strings to segment
	 * @param maxL
	 *            max Length of a line in chars
	 * @return Lines of text
	 */
public static List<StringBuffer> lineParser(final List<String> words, final int maxL) {
    List<StringBuffer> sList = new LinkedList<StringBuffer>();
    sList.add(new StringBuffer());
    int sindex = 0;
    for (int i = 0; i < words.size(); i++) {
        if (sList.get(sindex).length() + (words.get(i) + " ").length() <= maxL) {
            sList.set(sindex, sList.get(sindex).append(words.get(i)).append(" "));
        } else {
            sindex++;
            sList.add(new StringBuffer());
            sList.set(sindex, sList.get(sindex).append(words.get(i)).append(" "));
        }
    }
    return sList;
}
Example 53
Project: jxta-master  File: NettyTestUtils.java View source code
public static List<ChannelBuffer> splitIntoChunks(int chunkSize, ChannelBuffer... buffers) {
    LinkedList<ChannelBuffer> chunks = new LinkedList<ChannelBuffer>();
    ArrayList<ChannelBuffer> sourceBuffers = new ArrayList<ChannelBuffer>();
    Collections.addAll(sourceBuffers, buffers);
    Iterator<ChannelBuffer> sourceIter = sourceBuffers.iterator();
    ChannelBuffer chunk = ChannelBuffers.buffer(chunkSize);
    while (sourceIter.hasNext()) {
        ChannelBuffer source = sourceIter.next();
        int index = source.readerIndex();
        while (source.writerIndex() > index) {
            int fragmentSize = Math.min(source.writerIndex() - index, chunk.writableBytes());
            chunk.writeBytes(source, index, fragmentSize);
            if (!chunk.writable()) {
                chunks.add(chunk);
                chunk = ChannelBuffers.buffer(chunkSize);
            }
            index += fragmentSize;
        }
    }
    if (chunk.readable()) {
        chunks.add(chunk);
    }
    return chunks;
}
Example 54
Project: modeshape-master  File: AddAccessNodesTest.java View source code
/**
     * Before:
     * 
     * <pre>
     *          ...
     *           |
     *        SOURCE
     * </pre>
     * 
     * And after:
     * 
     * <pre>
     *          ...
     *           |
     *        ACCESS
     *           |
     *        SOURCE
     * </pre>
     */
@Test
public void shouldAddAccessNodeAboveSourceNode() {
    PlanNode project = new PlanNode(Type.PROJECT, selector("Selector1"));
    PlanNode source = new PlanNode(Type.SOURCE, project, selector("Selector1"));
    // Execute the rule ...
    PlanNode result = rule.execute(context, project, new LinkedList<OptimizerRule>());
    assertThat(result, is(sameInstance(project)));
    PlanNode access = project.getFirstChild();
    assertThat(access.getType(), is(Type.ACCESS));
    assertSelectors(access, "Selector1");
    assertChildren(access, source);
    assertChildren(source);
}
Example 55
Project: FireflowEngine20-master  File: RPN.java View source code
/**
     * 计算
     */
private Object calculate(LinkedList<Object> el2) {
    if (el2.peek() instanceof Operator) {
        Operator obj = (Operator) el2.peek();
        return obj.calculate();
    }
    if (el2.peek() instanceof Elobj) {
        return ((Elobj) el2.peek()).fetchVal();
    }
    return el2.peek();
}
Example 56
Project: quickml-master  File: TemporallyReweightedClassifierBuilderTest.java View source code
@Test(expectedExceptions = IllegalArgumentException.class)
public void testError3ClassificationsInDataSet() throws Exception {
    final List<ClassifierInstance> instances = new LinkedList<>();
    AttributesMap map = AttributesMap.newHashMap();
    map.put("2", "2");
    instances.add(new ClassifierInstance(map, "1"));
    instances.add(new ClassifierInstance(map, "2"));
    instances.add(new ClassifierInstance(map, "3"));
    PredictiveModelBuilder predictiveModelBuilder = new DecisionTreeBuilder();
    final TemporallyReweightedClassifierBuilder cpmb = new TemporallyReweightedClassifierBuilder(predictiveModelBuilder, 1.0, new OnespotDateTimeExtractor());
    cpmb.buildPredictiveModel(instances);
}
Example 57
Project: JAME-master  File: EnumeratorProcessorRuntime.java View source code
/**
	 * @see net.sf.jame.devtools.processor.extension.ProcessorExtensionRuntime#process(java.io.File, net.sf.jame.devtools.ProcessorDescriptor, java.util.List, java.util.Map)
	 */
@Override
public void process(File path, ProcessorParameters parameters, Map<String, String> variables) throws DevToolsException {
    try {
        ProcessorDescriptor element = parameters.getElement();
        if (element.isExtension() || element.isConfigurableExtension()) {
            if (variables.containsKey("generateEnumerator")) {
                File packagePath = new File(path, variables.get("enumeratorPackageName").replace('.', '/'));
                packagePath.mkdirs();
                Configuration config = new Configuration();
                config.setTemplateLoader(new ProcessorTemplateLoader());
                HashMap<String, Object> map = new HashMap<String, Object>();
                Set<String> imports = new HashSet<String>();
                prepare(imports, element);
                map.putAll(variables);
                prepareEnumerator(imports, element, variables);
                List<String> sortedImports = new LinkedList<String>(imports);
                Collections.sort(sortedImports);
                map.put("imports", sortedImports);
                map.put("extension", element);
                Template template = config.getTemplate("templates/EnumeratorRuntime.ftl");
                template.process(map, new PrintWriter(new File(packagePath, capitalize(element.getElementName()) + "EnumeratorRuntime.java")));
            }
        } else if (element.isComplexElement() || element.isSimpleElement()) {
        }
    } catch (Exception e) {
        throw new DevToolsException(e);
    }
}
Example 58
Project: GlassCompute-master  File: ResultsScrollAdapter.java View source code
@Override
public int getPosition(Object id) {
    // Make sure object is in fact the pod
    if (id instanceof HashMap) // convert to pod
    {
        HashMap<String, LinkedList<String>> obj = (HashMap<String, LinkedList<String>>) id;
        // Check if the title contained in the pod is contained in results
        // HashMap will contain only 1 <key, value> pair
        // The key is the pod title, the value is a LinkedList containing all result image URLs
        // Look at ResultObject.getPod() for more details
        String titleToSearch = (String) obj.keySet().toArray()[0];
        for (int i = 0; i < getCount(); i++) {
            String currentTitle = results.getPodTitle(i);
            if (titleToSearch.equals(currentTitle)) {
                return i;
            }
        }
    }
    return AdapterView.INVALID_POSITION;
}
Example 59
Project: lucene-solr-master  File: TestClusteringResponse.java View source code
@Test
public void testClusteringResponse() throws Exception {
    XMLResponseParser parser = new XMLResponseParser();
    /*Load a simple XML with the clustering response encoded in an XML format*/
    InputStream is = new SolrResourceLoader().openResource("solrj/sampleClusteringResponse.xml");
    assertNotNull(is);
    Reader in = new InputStreamReader(is, StandardCharsets.UTF_8);
    NamedList<Object> response = parser.processResponse(in);
    in.close();
    QueryResponse qr = new QueryResponse(response, null);
    ClusteringResponse clusteringResponse = qr.getClusteringResponse();
    List<Cluster> clusters = clusteringResponse.getClusters();
    Assert.assertEquals(4, clusters.size());
    //First Cluster
    Cluster cluster1 = clusters.get(0);
    List<String> expectedLabel1 = new LinkedList<String>();
    expectedLabel1.add("label1");
    List<String> expectedDocs1 = new LinkedList<String>();
    expectedDocs1.add("id1");
    expectedDocs1.add("id2");
    expectedDocs1.add("id3");
    Assert.assertEquals(expectedLabel1, cluster1.getLabels());
    Assert.assertEquals(expectedDocs1, cluster1.getDocs());
    Assert.assertEquals(expectedLabel1, cluster1.getLabels());
    Assert.assertEquals(0.6, cluster1.getScore(), 0);
    //Second Cluster
    Cluster cluster2 = clusters.get(1);
    List<String> expectedLabel2 = new LinkedList<String>();
    expectedLabel2.add("label2");
    List<String> expectedDocs2 = new LinkedList<String>();
    expectedDocs2.add("id5");
    expectedDocs2.add("id6");
    Assert.assertEquals(expectedLabel2, cluster2.getLabels());
    Assert.assertEquals(expectedDocs2, cluster2.getDocs());
    Assert.assertEquals(expectedLabel2, cluster2.getLabels());
    Assert.assertEquals(0.93, cluster2.getScore(), 0);
    //Third Cluster
    Cluster cluster3 = clusters.get(2);
    List<String> expectedLabel3 = new LinkedList<String>();
    expectedLabel3.add("label3");
    List<String> expectedDocs3 = new LinkedList<String>();
    expectedDocs3.add("id7");
    expectedDocs3.add("id8");
    Assert.assertEquals(expectedLabel3, cluster3.getLabels());
    Assert.assertEquals(expectedDocs3, cluster3.getDocs());
    Assert.assertEquals(expectedLabel3, cluster3.getLabels());
    Assert.assertEquals(1.26, cluster3.getScore(), 0);
    //Fourth Cluster
    Cluster cluster4 = clusters.get(3);
    List<String> expectedLabel4 = new LinkedList<String>();
    expectedLabel4.add("label4");
    List<String> expectedDocs4 = new LinkedList<String>();
    expectedDocs4.add("id9");
    Assert.assertEquals(expectedLabel4, cluster4.getLabels());
    Assert.assertEquals(expectedDocs4, cluster4.getDocs());
    Assert.assertEquals(expectedLabel4, cluster4.getLabels());
    Assert.assertEquals(0.0, cluster4.getScore(), 0);
}
Example 60
Project: yarn-comment-master  File: Count.java View source code
@Override
protected void processOptions(LinkedList<String> args) {
    CommandFormat cf = new CommandFormat(1, Integer.MAX_VALUE, "q");
    cf.parse(args);
    if (args.isEmpty()) {
        // default path is the current working directory
        args.add(".");
    }
    showQuotas = cf.getOpt("q");
}
Example 61
Project: flink-master  File: ShardConsumerTest.java View source code
@Test
public void testCorrectNumOfCollectedRecordsAndUpdatedState() {
    KinesisStreamShard fakeToBeConsumedShard = new KinesisStreamShard("fakeStream", new Shard().withShardId(KinesisShardIdGenerator.generateFromShardOrder(0)).withHashKeyRange(new HashKeyRange().withStartingHashKey("0").withEndingHashKey(new BigInteger(StringUtils.repeat("FF", 16), 16).toString())));
    LinkedList<KinesisStreamShardState> subscribedShardsStateUnderTest = new LinkedList<>();
    subscribedShardsStateUnderTest.add(new KinesisStreamShardState(fakeToBeConsumedShard, new SequenceNumber("fakeStartingState")));
    TestableKinesisDataFetcher fetcher = new TestableKinesisDataFetcher(Collections.singletonList("fakeStream"), new Properties(), 10, 2, new AtomicReference<Throwable>(), subscribedShardsStateUnderTest, KinesisDataFetcher.createInitialSubscribedStreamsToLastDiscoveredShardsState(Collections.singletonList("fakeStream")), Mockito.mock(KinesisProxyInterface.class));
    new ShardConsumer<>(fetcher, 0, subscribedShardsStateUnderTest.get(0).getKinesisStreamShard(), subscribedShardsStateUnderTest.get(0).getLastProcessedSequenceNum(), FakeKinesisBehavioursFactory.totalNumOfRecordsAfterNumOfGetRecordsCalls(1000, 9)).run();
    assertTrue(fetcher.getNumOfElementsCollected() == 1000);
    assertTrue(subscribedShardsStateUnderTest.get(0).getLastProcessedSequenceNum().equals(SentinelSequenceNumber.SENTINEL_SHARD_ENDING_SEQUENCE_NUM.get()));
}
Example 62
Project: rascal-master  File: SnakesAndLadders.java View source code
public ISourceLocation getSnakesAndLaddersPath() {
    try {
        URIResolverRegistry reg = URIResolverRegistry.getInstance();
        ISourceLocation tempRoot = URIUtil.correctLocation("tmp", "", "/snakes-ladders/");
        File expandedTempFolder = new File(reg.logicalToPhysical(tempRoot).getPath());
        if (new File(expandedTempFolder, ".project").exists()) {
            expandedTempFolder.deleteOnExit();
            return tempRoot;
        }
        ISourceLocation sourceRoot = vf.sourceLocation("testdata", "", "example-project/p2-SnakesAndLadders/");
        Queue<ISourceLocation> toCopy = new LinkedList<>();
        toCopy.add(sourceRoot);
        ISourceLocation current;
        while ((current = toCopy.poll()) != null) {
            if (reg.isDirectory(current)) {
                for (ISourceLocation ent : reg.list(current)) {
                    toCopy.add(ent);
                }
            } else {
                copyFile(reg, sourceRoot, current, expandedTempFolder);
            }
        }
        expandedTempFolder.deleteOnExit();
        return tempRoot;
    } catch (Throwable e) {
        return URIUtil.invalidLocation();
    }
}
Example 63
Project: openjdk-master  File: ReadArrayLengthDataProvider.java View source code
public static List<Object> createListOfDummyArrays(int length) {
    List<Object> arrays = new LinkedList<>();
    arrays.add(new boolean[length]);
    arrays.add(new byte[length]);
    arrays.add(new short[length]);
    arrays.add(new char[length]);
    arrays.add(new int[length]);
    arrays.add(new long[length]);
    arrays.add(new float[length]);
    arrays.add(new double[length]);
    arrays.add(new Object[length]);
    arrays.add(new boolean[length][2]);
    arrays.add(new byte[length][2]);
    arrays.add(new short[length][2]);
    arrays.add(new char[length][2]);
    arrays.add(new int[length][2]);
    arrays.add(new long[length][2]);
    arrays.add(new float[length][2]);
    arrays.add(new double[length][2]);
    arrays.add(new Object[length][2]);
    return arrays;
}
Example 64
Project: geotoolkit-master  File: StringToDoubleWArrayConverter.java View source code
@Override
public Double[] apply(final String source) throws UnconvertibleObjectException {
    if (source != null && !source.trim().isEmpty()) {
        final List<Double> doubleList = new LinkedList<Double>();
        if (source.contains(",")) {
            final String[] sourceSplit = source.split(",");
            for (final String str : sourceSplit) {
                try {
                    final Double dbl = Double.valueOf(str.trim());
                    if (dbl != null) {
                        doubleList.add(dbl);
                    }
                } catch (NumberFormatException ex) {
                    throw new UnconvertibleObjectException(ex.getMessage(), ex);
                }
            }
        } else {
            try {
                final Double dbl = Double.valueOf(source.trim());
                if (dbl != null) {
                    doubleList.add(dbl);
                }
            } catch (NumberFormatException ex) {
                throw new UnconvertibleObjectException(ex.getMessage(), ex);
            }
        }
        if (!doubleList.isEmpty()) {
            return doubleList.toArray(new Double[doubleList.size()]);
        } else {
            throw new UnconvertibleObjectException("Invalid source String : " + source);
        }
    }
    return new Double[0];
}
Example 65
Project: geotools-old-master  File: PolygonBuilder.java View source code
/**
     * Builds the a polygon using the linestring geometries (Sell and holes).
     * @param linestringNode LineString identifier defined in the grammar file
     */
@Override
public Geometry build(final int linestringNode) throws CQLException {
    Result result = getResultStack().peek();
    try {
        // Retrieve the liner ring for shell and holes
        final List<Geometry> geometryList = popGeometry(linestringNode);
        assert geometryList.size() >= 1;
        // retrieves the shell
        LineString line = (LineString) geometryList.get(0);
        final LinearRing shell = getGeometryFactory().createLinearRing(line.getCoordinates());
        // if it has holes, creates a ring for each linestring
        LinearRing[] holes = new LinearRing[0];
        if (geometryList.size() > 1) {
            List<LinearRing> holeList = new LinkedList<LinearRing>();
            for (int i = 1; i < geometryList.size(); i++) {
                LineString holeLines = (LineString) geometryList.get(i);
                LinearRing ring = getGeometryFactory().createLinearRing(holeLines.getCoordinates());
                holeList.add(ring);
            }
            int holesSize = holeList.size();
            holes = holeList.toArray(new LinearRing[holesSize]);
        }
        // creates the polygon
        Polygon polygon = getGeometryFactory().createPolygon(shell, holes);
        return polygon;
    } catch (Exception e) {
        throw new CQLException(e.getMessage(), result.getToken(), getStatemet());
    }
}
Example 66
Project: astrid-master  File: BaseTestCase.java View source code
protected View findViewByClassName(View root, String className) {
    LinkedList<View> lookupQueue = new LinkedList<View>();
    lookupQueue.add(root);
    while (!lookupQueue.isEmpty()) {
        View target = lookupQueue.removeFirst();
        if (className.equals(target.getClass().getName())) {
            return target;
        }
        if (target instanceof ViewGroup) {
            ViewGroup targetGroup = (ViewGroup) target;
            for (int i = 0, count = targetGroup.getChildCount(); i < count; i++) {
                lookupQueue.addLast(targetGroup.getChildAt(i));
            }
        }
    }
    return null;
}
Example 67
Project: sonar-java-master  File: ExpressionsHelper.java View source code
public static String concatenate(@Nullable ExpressionTree tree) {
    if (tree == null) {
        return "";
    }
    Deque<String> pieces = new LinkedList<>();
    ExpressionTree expr = tree;
    while (expr.is(Tree.Kind.MEMBER_SELECT)) {
        MemberSelectExpressionTree mse = (MemberSelectExpressionTree) expr;
        pieces.push(mse.identifier().name());
        pieces.push(".");
        expr = mse.expression();
    }
    if (expr.is(Tree.Kind.IDENTIFIER)) {
        IdentifierTree idt = (IdentifierTree) expr;
        pieces.push(idt.name());
    }
    StringBuilder sb = new StringBuilder();
    for (String piece : pieces) {
        sb.append(piece);
    }
    return sb.toString();
}
Example 68
Project: FriendlyAlarmClock-master  File: ServerUtil.java View source code
public static LinkedList<CommentModel> readFromPost(AsyncFacebookRunner mAsyncFacebookRunner, String pid) {
    final LinkedList<CommentModel> comments = new LinkedList<CommentModel>();
    mAsyncFacebookRunner.request(pid + "/comments", new RequestListener() {

        @Override
        public void onMalformedURLException(MalformedURLException e, Object state) {
        }

        @Override
        public void onIOException(IOException e, Object state) {
        }

        @Override
        public void onFileNotFoundException(FileNotFoundException e, Object state) {
        }

        @Override
        public void onFacebookError(FacebookError e, Object state) {
        }

        @Override
        public void onComplete(String response, Object state) {
            try {
                JSONObject obj = new JSONObject(response);
                JSONArray commentsArray = obj.getJSONArray("data");
                for (int i = 0; i < commentsArray.length(); i++) {
                    JSONObject comment = commentsArray.getJSONObject(i);
                    CommentModel c = new CommentModel();
                    c.setCommentID(comment.getString("id"));
                    JSONObject from = comment.getJSONObject("from");
                    c.setFrom(from.getString("name"));
                    c.setMsg(comment.getString("message"));
                    comments.add(c);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    return comments;
}
Example 69
Project: DataGenerator-master  File: SparkDistributor.java View source code
@Override
public void distribute(final List<Frontier> frontierList) {
    JavaSparkContext sc = new JavaSparkContext(new SparkConf().setAppName("dg-spark").setMaster(masterURL));
    generatedMaps = sc.parallelize(frontierList).flatMap(new FlatMapFunction<Frontier, Map<String, String>>() {

        @Override
        public Iterable<Map<String, String>> call(Frontier frontier) {
            LinkedList<Map<String, String>> storage = new LinkedList<>();
            frontier.searchForScenarios(new CatchAndStoreProcessing(storage), searchExitFlag);
            return storage;
        }
    }).flatMap(new FlatMapFunction<Map<String, String>, Map<String, String>>() {

        @Override
        public Iterable<Map<String, String>> call(Map<String, String> initialVars) {
            return SparkDistributor.dataConsumer.transformAndReturn(initialVars);
        }
    });
}
Example 70
Project: Yhb-2.0-master  File: TileRenderTask.java View source code
@Override
protected Void doInBackground(Void... params) {
    // have we been stopped or dereffed?
    TileManager tileManager = reference.get();
    // if not go ahead, but check again in each iteration
    if (tileManager != null) {
        // avoid concurrent modification exceptions by duplicating
        LinkedList<Tile> renderList = tileManager.getRenderList();
        // start rendering, checking each iteration if we need to break out
        for (Tile m : renderList) {
            // check again if we've been stopped or gc'ed
            tileManager = reference.get();
            if (tileManager == null) {
                return null;
            }
            // quit if we've been forcibly stopped
            if (tileManager.getRenderIsCancelled()) {
                return null;
            }
            // quit if task has been cancelled or replaced
            if (isCancelled()) {
                return null;
            }
            // once the bitmap is decoded, the heavy lift is done
            tileManager.decodeIndividualTile(m);
            // pass it to the UI thread for insertion into the view tree
            publishProgress(m);
        }
    }
    return null;
}
Example 71
Project: Tank-master  File: ScriptUploadRequestTest.java View source code
/**
     * Run the ScriptDescription getScript() method test.
     *
     * @throws Exception
     *
     * @generatedBy CodePro at 12/15/14 3:09 PM
     */
@Test
public void testGetScript_1() throws Exception {
    ScriptUploadRequest fixture = new ScriptUploadRequest(new ScriptDescription(), new LinkedList());
    ScriptDescription result = fixture.getScript();
    assertNotNull(result);
    assertEquals(null, result.toString());
    assertEquals(null, result.getName());
    assertEquals(0, result.getRuntime());
    assertEquals(null, result.getId());
    assertEquals(null, result.getModified());
    assertEquals(null, result.getProductName());
    assertEquals(null, result.getComments());
    assertEquals(null, result.getCreator());
    assertEquals(null, result.getCreated());
}
Example 72
Project: javalang-master  File: Refactorization.java View source code
/**
    * Generic method to rename a SymbolDefinition variable/parameter.
    * @param n variable to rename.
    * @param newName new name to set.
    * @return if the rename procedure has been applied successfully.
    */
public boolean refactorVariable(SymbolDefinition n, final String newName) {
    Map<String, SymbolDefinition> scope = n.getVariableDefinitions();
    if (!scope.containsKey(newName)) {
        if (n.getUsages() != null) {
            List<SymbolReference> usages = new LinkedList<SymbolReference>(n.getUsages());
            VoidVisitorAdapter<?> visitor = new VoidVisitorAdapter<Object>() {

                @Override
                public void visit(NameExpr nexpr, Object ctx) {
                    Map<String, SymbolDefinition> innerScope = nexpr.getVariableDefinitions();
                    if (innerScope.containsKey(newName)) {
                        nexpr.getParentNode().replaceChildNode(nexpr, new FieldAccessExpr(new ThisExpr(), newName));
                    } else {
                        nexpr.getParentNode().replaceChildNode(nexpr, new NameExpr(newName));
                    }
                }

                @Override
                public void visit(FieldAccessExpr nexpr, Object ctx) {
                    nexpr.getParentNode().replaceChildNode(nexpr, new FieldAccessExpr(nexpr.getScope(), nexpr.getTypeArgs(), newName));
                }
            };
            for (SymbolReference usage : usages) {
                Node aux = (Node) usage;
                aux.accept(visitor, null);
            }
        }
        return true;
    }
    return false;
}
Example 73
Project: TFC2-master  File: ItemAxe.java View source code
@Override
public boolean onBlockDestroyed(ItemStack stack, World worldIn, IBlockState state, BlockPos pos, EntityLivingBase entityLiving) {
    if (worldIn.isRemote || !Core.isNaturalLog(state))
        return super.onBlockDestroyed(stack, worldIn, state, pos, entityLiving);
    LinkedList<BlockPos> queue = new LinkedList<BlockPos>();
    queue.add(pos);
    BlockPos scanPos;
    IBlockState scanState;
    while (!queue.isEmpty()) {
        scanPos = queue.pop();
        scanState = worldIn.getBlockState(scanPos);
        if (Core.isNaturalLog(scanState)) {
            scanState.getBlock().dropBlockAsItem(worldIn, scanPos, scanState, 0);
            worldIn.setBlockToAir(scanPos);
            Iterable<BlockPos> list = BlockPos.getAllInBox(scanPos.add(-1, 0, -1), scanPos.add(1, 1, 1));
            for (BlockPos p : list) {
                queue.add(p);
            }
        }
    }
    return false;
}
Example 74
Project: spring-framework-2.5.x-master  File: ClassUtilsTests.java View source code
public void testClassNamesToString() {
    List ifcs = new LinkedList();
    ifcs.add(Serializable.class);
    ifcs.add(Runnable.class);
    assertEquals("[interface java.io.Serializable, interface java.lang.Runnable]", ifcs.toString());
    assertEquals("[java.io.Serializable, java.lang.Runnable]", ClassUtils.classNamesToString(ifcs));
    List classes = new LinkedList();
    classes.add(LinkedList.class);
    classes.add(Integer.class);
    assertEquals("[class java.util.LinkedList, class java.lang.Integer]", classes.toString());
    assertEquals("[java.util.LinkedList, java.lang.Integer]", ClassUtils.classNamesToString(classes));
    assertEquals("[interface java.util.List]", Collections.singletonList(List.class).toString());
    assertEquals("[java.util.List]", ClassUtils.classNamesToString(Collections.singletonList(List.class)));
    assertEquals("[]", Collections.EMPTY_LIST.toString());
    assertEquals("[]", ClassUtils.classNamesToString(Collections.EMPTY_LIST));
}
Example 75
Project: ArubaSyslog-master  File: SessionExtractor.java View source code
public static void main(String[] args) throws IOException, ParseException {
    // Initial options
    String input_location = "";
    String output_location = "";
    // fetch command line options 
    int optSetting = 0;
    for (; optSetting < args.length; optSetting++) {
        if ("-i".equals(args[optSetting])) {
            input_location = args[++optSetting];
        } else if ("-o".equals(args[optSetting])) {
            output_location = args[++optSetting];
        }
    }
    if (input_location.length() == 0) {
        System.out.println("Usage: SessionExtractor -i <source> -o <destination>>");
        System.exit(-1);
    }
    // for statistics
    long start = System.currentTimeMillis();
    // reading filtered files one by one to extract user sessions
    System.out.println("Extracting user trace sessions from raw logs ...");
    Utils.createFolder(output_location);
    File[] user_files = Utils.getInputFiles(input_location);
    for (File file : user_files) {
        String umac = file.getName();
        System.out.println(System.currentTimeMillis() + " " + umac);
        // read the file
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String thisLine = "";
        List<String> allLines = new LinkedList<String>();
        // read each line
        while ((thisLine = reader.readLine()) != null) {
            thisLine = thisLine.replaceAll("[\\r\\n]", "");
            if (thisLine.length() == 0) {
                continue;
            }
            allLines.add(thisLine);
        }
        // extract session and save to file
        allLines = SessionExtraction.extractSessions(allLines);
        // write into file
        BufferedWriter bw = new BufferedWriter(new FileWriter(FilenameUtils.concat(output_location, umac)));
        for (String l : allLines) bw.write(l + "\n");
        bw.close();
        reader.close();
    }
    System.out.println(String.format("Total time: %.3f sec", (System.currentTimeMillis() - start) / 1000.0));
}
Example 76
Project: core-android-master  File: SegmentCluster.java View source code
public List<Segment> getSegments(double[] array) {
    PitchHandler pitchHandler = new PitchHandler();
    List<Segment> segmentList = new LinkedList<Segment>();
    double segmentMean = 0;
    int segmentSize = 0;
    if (array.length > 0) {
        segmentMean = array[1];
        segmentSize = 1;
    }
    for (int i = 1; i < array.length; i++) {
        double diff = Math.abs(pitchHandler.getToneChanged(array[i], segmentMean));
        if (diff < diffThreshold) {
            // same cluster, add to the cluster and change the cluster data
            segmentMean = (segmentMean * segmentSize + array[i]) / (++segmentSize);
        } else {
            // not the cluster, create a new one
            //System.out.println("New Cluster: "+clusterMean);
            Segment segment = new Segment();
            segment.setMean(segmentMean);
            segment.setStartPosition(i - segmentSize);
            segment.setSize(segmentSize);
            segmentList.add(segment);
            // end current cluster
            // set new cluster
            segmentMean = array[i];
            segmentSize = 1;
        }
    }
    // add the last cluster
    Segment segment = new Segment();
    segment.setMean(segmentMean);
    segment.setStartPosition(array.length - segmentSize);
    segment.setSize(segmentSize);
    segmentList.add(segment);
    return segmentList;
}
Example 77
Project: xmind-master  File: SVGPolygonShape.java View source code
private void parserPolygon(Element implemention, SVGShape parent) {
    if (implemention.hasAttribute(SVGDefinitionConstants.POINTS)) {
        String pointString = implemention.getAttribute(SVGDefinitionConstants.POINTS);
        final Matcher match = pattern.matcher(pointString);
        LinkedList<String> strs = new LinkedList<String>();
        while (match.find()) strs.add(match.group());
        if (strs.size() % 2 == 1)
            return;
        while (!strs.isEmpty()) {
            float x = Float.valueOf(strs.removeFirst());
            float y = Float.valueOf(strs.removeFirst());
            points.add(new PrecisionPoint(x, y));
        }
    }
}
Example 78
Project: MadStore-master  File: CrawlerConfigurationsFactoryBean.java View source code
public Object getObject() throws Exception {
    MadStoreConfigurationBean madstoreConfiguration = getMadStoreConfiguration();
    List<CrawlerConfiguration> crawlerConfigurationsResult = new LinkedList<CrawlerConfiguration>();
    List<MadStoreConfigurationBean.CrawlerConfiguration> crawlerConfigurations = madstoreConfiguration.getCrawlerConfigurations();
    for (MadStoreConfigurationBean.CrawlerConfiguration tmpConfig : crawlerConfigurations) {
        CrawlerConfiguration crawlerConfiguration = new CrawlerConfigurationImpl();
        crawlerConfiguration.setServer(tmpConfig.getHostName());
        crawlerConfiguration.setStartLink(tmpConfig.getStartLink());
        crawlerConfiguration.setMaxConcurrentDownloads(tmpConfig.getMaxConcurrentDownloads());
        crawlerConfiguration.setMaxVisitedLinks(tmpConfig.getMaxVisitedLinks());
        crawlerConfiguration.setPipeline(getPipeline(tmpConfig));
        crawlerConfigurationsResult.add(crawlerConfiguration);
    }
    return crawlerConfigurationsResult;
}
Example 79
Project: jlibs-master  File: SequenceTest.java View source code
@Test
public void testHasNext() {
    List<E> list = SequenceUtil.addAll(new LinkedList<E>(), seq);
    assert !seq.hasNext() : "next()==null then hasNext()==false";
    seq.reset();
    E elem;
    while (true) {
        boolean hasNext = seq.hasNext();
        assert hasNext == seq.hasNext() : "seq.hasNext()==seq.hasNext()";
        elem = seq.next();
        assert hasNext == (elem != null) : "hasNext() == next()!=null";
        if (!hasNext)
            return;
        E prev = list.remove(0);
        assert prev.equals(elem) : prev + "!=" + elem;
    }
}
Example 80
Project: flybook-master  File: SearchItemTree.java View source code
public void updateSubTrees() {
    ListIterator<FBTree> nodeIterator = subTrees().listIterator();
    final Set<NetworkBookItem.AuthorData> authorsSet = myResult.BooksMap.keySet();
    for (NetworkBookItem.AuthorData author : authorsSet) {
        if (nodeIterator != null) {
            if (nodeIterator.hasNext()) {
                FBTree currentNode = nodeIterator.next();
                if (!(currentNode instanceof NetworkAuthorTree)) {
                    throw new RuntimeException("That's impossible!!!");
                }
                NetworkAuthorTree child = (NetworkAuthorTree) currentNode;
                if (!child.Author.equals(author)) {
                    throw new RuntimeException("That's impossible!!!");
                }
                LinkedList<NetworkBookItem> authorBooks = myResult.BooksMap.get(author);
                child.updateSubTrees(authorBooks);
                continue;
            }
            nodeIterator = null;
        }
        LinkedList<NetworkBookItem> authorBooks = myResult.BooksMap.get(author);
        if (authorBooks.size() != 0) {
            NetworkAuthorTree child = new NetworkAuthorTree(this, author);
            child.updateSubTrees(authorBooks);
        }
    }
    if (nodeIterator != null && nodeIterator.hasNext()) {
        throw new RuntimeException("That's impossible!!!");
    }
}
Example 81
Project: geofence-master  File: CategorizedCircularBuffer.java View source code
private void removeLastEntry() {
    Pair<T, K> lastEntry = mainList.pollLast();
    LinkedList<T> typedList = typedLists.get(lastEntry.key);
    if (typedList == null)
        throw new IllegalStateException("Internal error - can't find list for " + lastEntry);
    T remove = typedList.removeLast();
    if (!lastEntry.value.equals(remove))
        throw new IllegalStateException("Internal error - mismatching values " + lastEntry.value + " , " + remove);
    if (typedList.size() == 0)
        typedLists.remove(lastEntry.key);
}
Example 82
Project: aokp-gerrit-master  File: Schema_60.java View source code
@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException {
    Pattern patternA = Pattern.compile("Patch Set ([0-9]+):.*", Pattern.DOTALL);
    Pattern patternB = Pattern.compile("Uploaded patch set ([0-9]+).");
    ResultSet<ChangeMessage> results = db.changeMessages().all();
    List<ChangeMessage> updates = new LinkedList<>();
    for (ChangeMessage cm : results) {
        Change.Id id = cm.getKey().getParentKey();
        String msg = cm.getMessage();
        Matcher matcherA = patternA.matcher(msg);
        Matcher matcherB = patternB.matcher(msg);
        PatchSet.Id newId = null;
        if (matcherA.matches()) {
            int patchSetNum = Integer.parseInt(matcherA.group(1));
            newId = new PatchSet.Id(id, patchSetNum);
        } else if (matcherB.matches()) {
            int patchSetNum = Integer.parseInt(matcherB.group(1));
            newId = new PatchSet.Id(id, patchSetNum);
        }
        if (newId != null) {
            cm.setPatchSetId(newId);
            updates.add(cm);
        }
        if (updates.size() >= 100) {
            db.changeMessages().update(updates);
            updates.clear();
        }
    }
    if (!updates.isEmpty()) {
        db.changeMessages().update(updates);
    }
}
Example 83
Project: statalign-master  File: HashTable.java View source code
/**
     * Puts a bi-partition into the hash table. If this bi-partition becomes a majority partition
     * this function will also put that into the <code>partitions</code> linked list.
     * @param partition the bi-partition.
     * @param tableKey the key that indexes the actual hash table.
     * @param bucketKey the bucket key which is kept in each entry.
     * @param resRate how many trees a bi-partition has to be in, to be a majority bi-partition.
     * @param partitions a [email protected] LinkedList} containing the majority partitions.
     */
public void put(BitSet partition, double edgeLength, int tableKey, int bucketKey, double resRate, LinkedList<HashEntry> partitions) {
    if (hashTable[tableKey].isEmpty()) {
        // No entry exists for this key (1): Create.
        HashEntry entry = new HashEntry(bucketKey, partition, edgeLength);
        if (1.0 > resRate && !entry.isMajority) {
            // A new partition of interest!
            // is majority if is of interest at this point...!
            entry.isMajority = true;
            partitions.add(entry);
        }
        hashTable[tableKey].add(entry);
    } else {
        boolean found = false;
        for (HashEntry entry : hashTable[tableKey]) {
            // Searches the bucket.
            if (entry.hashKey2 == bucketKey) {
                // An entry was found.
                // Increase the occurrence of the entry.
                entry.count++;
                entry.edgeLengthsSum += edgeLength;
                if ((double) entry.count > resRate && !entry.isMajority) {
                    // A new partition of interest!
                    // is majority if is of interest at this point...!
                    entry.isMajority = true;
                    partitions.add(entry);
                }
                found = true;
                break;
            }
        }
        if (!found) {
            // No entry exists for this key (2): Create.
            HashEntry entry = new HashEntry(bucketKey, partition, edgeLength);
            if (1.0 > resRate && !entry.isMajority) {
                // A new partition of interest!
                // is majority if is of interest at this point...!
                entry.isMajority = true;
                partitions.add(entry);
            }
            hashTable[tableKey].add(entry);
        }
    }
}
Example 84
Project: ProjectLibre-master  File: MPPTimephasedBaselineWorkNormaliser.java View source code
/**
    * This method merges together assignment data for the same day.
    * 
    * @param calendar current calendar
    * @param list assignment data
    */
@Override
protected void mergeSameDay(ProjectCalendar calendar, LinkedList<TimephasedWork> list) {
    LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();
    TimephasedWork previousAssignment = null;
    for (TimephasedWork assignment : list) {
        if (previousAssignment == null) {
            assignment.setAmountPerDay(assignment.getTotalAmount());
            result.add(assignment);
        } else {
            Date previousAssignmentStart = previousAssignment.getStart();
            Date previousAssignmentStartDay = DateHelper.getDayStartDate(previousAssignmentStart);
            Date assignmentStart = assignment.getStart();
            Date assignmentStartDay = DateHelper.getDayStartDate(assignmentStart);
            if (previousAssignmentStartDay.getTime() == assignmentStartDay.getTime()) {
                result.removeLast();
                double work = previousAssignment.getTotalAmount().getDuration();
                work += assignment.getTotalAmount().getDuration();
                Duration totalWork = Duration.getInstance(work, TimeUnit.MINUTES);
                TimephasedWork merged = new TimephasedWork();
                merged.setStart(previousAssignment.getStart());
                merged.setFinish(assignment.getFinish());
                merged.setTotalAmount(totalWork);
                assignment = merged;
            }
            assignment.setAmountPerDay(assignment.getTotalAmount());
            result.add(assignment);
        }
        previousAssignment = assignment;
    }
    list.clear();
    list.addAll(result);
}
Example 85
Project: openjdk8-jdk-master  File: CCAdminReconnectTest.java View source code
public static void main(String... args) throws Exception {
    final ExecutorService e = Executors.newFixedThreadPool(THREAD_COUNT);
    final AtomicBoolean beingReconnected = new AtomicBoolean();
    final Collection<Exception> thrownExceptions = new LinkedList<>();
    System.out.println(": Testing concurrent restart of ClientCommunicatorAdmin");
    final ClientCommunicatorAdmin cca = new ClientCommunicatorAdmin(50) {

        @Override
        protected void checkConnection() throws IOException {
        // empty
        }

        @Override
        protected void doStart() throws IOException {
            if (!beingReconnected.compareAndSet(false, true)) {
                IOException e = new IOException("Detected overlayed reconnect requests");
                thrownExceptions.add(e);
                throw e;
            }
            try {
                // simulating a workload
                Thread.sleep(800);
                beingReconnected.set(false);
            } catch (InterruptedException e) {
            }
        }

        @Override
        protected void doStop() {
        // empty
        }
    };
    Runnable r = new Runnable() {

        private final IOException e = new IOException("Forced reconnect");

        @Override
        public void run() {
            try {
                // forcing the reconnect request
                cca.gotIOException(e);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };
    System.out.println(": Spawning " + THREAD_COUNT + " concurrent reconnect requests");
    for (int i = 0; i < THREAD_COUNT; i++) {
        e.execute(r);
    }
    Thread.sleep(THREAD_COUNT * 1000);
    e.shutdown();
    e.awaitTermination(10, TimeUnit.SECONDS);
    cca.terminate();
    for (Exception thrown : thrownExceptions) {
        throw thrown;
    }
    System.out.println(": Requests processed successfully");
}
Example 86
Project: devcoin-android-master  File: KeyTimeCoinSelector.java View source code
@Override
public Wallet.CoinSelection select(BigInteger target, LinkedList<TransactionOutput> candidates) {
    try {
        LinkedList<TransactionOutput> gathered = Lists.newLinkedList();
        BigInteger valueGathered = BigInteger.ZERO;
        for (TransactionOutput output : candidates) {
            if (ignorePending && !isConfirmed(output))
                continue;
            // Find the key that controls output, assuming it's a regular pay-to-pubkey or pay-to-address output.
            // We ignore any other kind of exotic output on the assumption we can't spend it ourselves.
            final Script scriptPubKey = output.getScriptPubKey();
            ECKey controllingKey;
            if (scriptPubKey.isSentToRawPubKey()) {
                controllingKey = wallet.findKeyFromPubKey(scriptPubKey.getPubKey());
            } else if (scriptPubKey.isSentToAddress()) {
                controllingKey = wallet.findKeyFromPubHash(scriptPubKey.getPubKeyHash());
            } else {
                log.info("Skipping tx output {} because it's not of simple form.", output);
                continue;
            }
            if (controllingKey.getCreationTimeSeconds() >= unixTimeSeconds)
                continue;
            // It's older than the cutoff time so select.
            valueGathered = valueGathered.add(output.getValue());
            gathered.push(output);
            if (gathered.size() >= MAX_SIMULTANEOUS_INPUTS) {
                log.warn("Reached {} inputs, going further would yield a tx that is too large, stopping here.", gathered.size());
                break;
            }
        }
        return new Wallet.CoinSelection(valueGathered, gathered);
    } catch (ScriptException e) {
        throw new RuntimeException(e);
    }
}
Example 87
Project: openmap-master  File: LineUtil.java View source code
/**
     * Extract a length on a polyline.
     * 
     * @param length the curve length to extract from points
     * @param points the original points
     * @param polysegment the returned points
     * @return true if we got the desired length, false otherwise
     */
protected static boolean retrievePoints(float length, LinkedList<Point2D> points, LinkedList<Point2D> polysegment) {
    polysegment.clear();
    // first point
    Point2D point = points.removeFirst();
    polysegment.add(point);
    double consumedLength = 0.0;
    double norm = 0.0;
    Point2D nextPoint = null;
    while (consumedLength < length && !points.isEmpty()) {
        // consume points while distance is not reached
        nextPoint = (Point2D) points.removeFirst();
        polysegment.add(nextPoint);
        norm = LineUtil.norm(point, nextPoint);
        consumedLength += norm;
        point = nextPoint;
    }
    if (MoreMath.approximately_equal(consumedLength, length)) {
        // we got the exact distance with an existing point.
        // we need to copy the last point back: it will be the
        // first for the next call
        points.addFirst(point);
        return true;
    } else {
        if (consumedLength > length) {
            // we went too far, we need to put back the last point
            points.addFirst(polysegment.removeLast());
            consumedLength -= norm;
            // and interpolate a new point
            point = (Point2D) polysegment.getLast();
            double d = length - consumedLength;
            // between point and nextPoint at distance d
            Point2D interp = LineUtil.interpolatedPoint(point, nextPoint, d);
            polysegment.add(interp);
            points.addFirst(interp);
            return true;
        } else {
            // no more points !
            return false;
        }
    }
}
Example 88
Project: gradle-ecgine-plugin-master  File: EcgineLoginTask.java View source code
private String getApiKey(String username, String pwd) {
    EcgineExtension ext = (EcgineExtension) getProject().getExtensions().getByName(EcgineExtension.NAME);
    try {
        String url = ext.getLoginUrl();
        System.out.println("Getting API key: " + url);
        List<NameValuePair> params = new LinkedList<NameValuePair>();
        params.add(new BasicNameValuePair("email", username));
        params.add(new BasicNameValuePair("password", pwd));
        HttpClient client = ext.getHttpClient();
        HttpGet request = new HttpGet(url + "?" + URLEncodedUtils.format(params, "utf-8"));
        HttpResponse response = client.execute(request);
        int code = response.getStatusLine().getStatusCode();
        if (code != 200) {
            EntityUtils.consume(response.getEntity());
            throw new GradleException("StatusCode:" + code + " URL:" + url);
        }
        String json = EntityUtils.toString(response.getEntity());
        JSONObject result = new JSONObject(json);
        if (result.getInt("code") == 1) {
            return result.getString("message");
        } else {
            throw new GradleException("Request failed:" + result.getString("message"));
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 89
Project: molgenis-master  File: AnnotatorDependencyOrderResolver.java View source code
public Queue<RepositoryAnnotator> getAnnotatorSelectionDependencyList(List<RepositoryAnnotator> availableAnnotatorList, List<RepositoryAnnotator> requestedAnnotatorList, Repository<Entity> repo, EntityTypeFactory entityTypeFactory) {
    Queue<RepositoryAnnotator> sortedList = new LinkedList<>();
    for (RepositoryAnnotator annotator : requestedAnnotatorList) {
        if (annotator instanceof EffectBasedAnnotator) {
            // FIXME: implement correct dependency resolving for Effect annotator
            sortedList.add(annotator);
        } else if (!sortedList.contains(annotator)) {
            requestedAnnotator = annotator;
            sortedList = getSingleAnnotatorDependencyList(annotator, availableAnnotatorList, sortedList, repo.getEntityType(), entityTypeFactory);
        }
    }
    return sortedList;
}
Example 90
Project: Rio-master  File: RegistrationManager.java View source code
public List<RegisteredNotification> getRegisteredNotifications(ProxyPreparer listenerPreparer) {
    List<RegisteredNotification> registeredNotifications = new LinkedList<RegisteredNotification>();
    File[] files = persistentRegistrationDirectory.listFiles();
    if (files == null) {
        logger.warn(String.format("%s returned null file array", persistentRegistrationDirectory.getPath()));
        return registeredNotifications;
    }
    for (File file : files) {
        ObjectInputStream inputStream = null;
        try {
            inputStream = new ObjectInputStream(new FileInputStream(file));
            RegisteredNotification registeredNotification = (RegisteredNotification) inputStream.readObject();
            if (ensure(registeredNotification)) {
                registeredNotification.restore(listenerPreparer);
                registeredNotifications.add(registeredNotification);
            } else {
                if (file.delete()) {
                    logger.debug("Removed expired registration");
                }
            }
        } catch (Exception e) {
            logger.error(String.format("Could not read serialized event [%s] from disk", file.getPath()), e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.warn("Trying to close OIS", e);
                }
            }
        }
    }
    return registeredNotifications;
}
Example 91
Project: liferay-ide-master  File: PortletNamePossibleValueService.java View source code
/*
     * (non-Javadoc)
     * @see org.eclipse.sapphire.modeling.PossibleValuesService#fillPossibleValues(java.util.SortedSet)
     */
@Override
protected void compute(Set<String> values) {
    final IFile displayXmlFile = context(Element.class).resource().adapt(IFile.class);
    final IFolder resourceFolder = (IFolder) displayXmlFile.getParent();
    final IFile portletXml = resourceFolder.getFile("portlet.xml");
    IDOMModel portletModel = null;
    try {
        portletModel = (IDOMModel) StructuredModelManager.getModelManager().getModelForRead(portletXml);
        IDOMDocument portletDocument = portletModel.getDocument();
        NodeList elements = portletDocument.getElementsByTagName(PORTLET_NAME_ELEMENT);
        List<String> portletNameList = new LinkedList<String>();
        for (int i = 0; i < elements.getLength(); i++) {
            Node portletElement = elements.item(i);
            if (portletElement != null) {
                String portletName = portletElement.getTextContent();
                portletNameList.add(portletName);
            }
        }
        this.localPortletNames = portletNameList.toArray(new String[0]);
    } catch (Exception e) {
        LiferayCore.logError(e);
    } finally {
        if (portletModel != null) {
            portletModel.releaseFromRead();
        }
    }
    if (this.localPortletNames != null) {
        Collections.addAll(values, this.localPortletNames);
    }
}
Example 92
Project: pcgen-master  File: SpellTreeViewModel.java View source code
@Override
@SuppressWarnings("unchecked")
public List<TreeViewPath<SuperNode>> getPaths(SuperNode node) {
    TreeViewPath<SuperNode> path;
    if (node instanceof SpellNode) {
        SpellNode pobj = (SpellNode) node;
        LinkedList<Object> pathList = new LinkedList<>();
        switch(this) {
            case CLASS_LEVEL_SPELL:
                Collections.addAll(pathList, pobj.getRootNode(), pobj.getSpellcastingClass(), pobj.getSpellLevel());
                pathList.removeAll(Collections.singleton(null));
                if (pobj.getSpell() == null) {
                    pathList.removeLast();
                }
                path = new TreeViewPath<>(pobj, pathList.toArray());
                break;
            case CLASS_LEVEL_SCHOOL_SPELL:
                Collections.addAll(pathList, pobj.getRootNode(), pobj.getSpellcastingClass(), pobj.getSpellLevel());
                if (pobj.getSpell() != null) {
                    pathList.add(pobj.getSpell().getSchool());
                }
                pathList.removeAll(Collections.singleton(null));
                if (pobj.getSpell() == null) {
                    pathList.removeLast();
                }
                path = new TreeViewPath<>(pobj, pathList.toArray());
                break;
            default:
                throw new InternalError();
        }
    } else {
        path = new TreeViewPath<>(node);
    }
    return Arrays.asList(path);
}
Example 93
Project: android_platform_libcore-master  File: ConcurrentModificationExceptionTest.java View source code
/**
     * java.util.ConcurrentModificationException#ConcurrentModificationException()
     */
public void test_Constructor() {
    // Test for method java.util.ConcurrentModificationException()
    Collection myCollection = new LinkedList();
    Iterator myIterator = myCollection.iterator();
    for (int counter = 0; counter < 50; counter++) myCollection.add(new Integer(counter));
    CollectionModifier cm = new CollectionModifier(myCollection);
    Thread collectionSlapper = new Thread(cm);
    try {
        collectionSlapper.start();
        while (myIterator.hasNext()) myIterator.next();
    } catch (ConcurrentModificationException e) {
        cm.stopNow();
        return;
    }
    cm.stopNow();
    // The exception should have been thrown--if the code flow makes it here
    // the test has failed
    fail("Failed to throw expected ConcurrentModificationException");
}
Example 94
Project: android-15-master  File: TestsListPreloaderThread.java View source code
/**
     * Loads all the tests from the given directories and all the subdirectories
     * into mTestsList.
     *
     * @param dirRelativePath
     */
private void loadTestsFromUrl(String rootRelativePath) {
    LinkedList<String> directoriesList = new LinkedList<String>();
    directoriesList.add(rootRelativePath);
    String relativePath;
    String itemName;
    while (!directoriesList.isEmpty()) {
        relativePath = directoriesList.removeFirst();
        List<String> dirRelativePaths = FsUtils.getLayoutTestsDirContents(relativePath, false, true);
        if (dirRelativePaths != null) {
            for (String dirRelativePath : dirRelativePaths) {
                itemName = new File(dirRelativePath).getName();
                if (FileFilter.isTestDir(itemName)) {
                    directoriesList.add(dirRelativePath);
                }
            }
        }
        List<String> testRelativePaths = FsUtils.getLayoutTestsDirContents(relativePath, false, false);
        if (testRelativePaths != null) {
            for (String testRelativePath : testRelativePaths) {
                itemName = new File(testRelativePath).getName();
                if (FileFilter.isTestFile(itemName)) {
                    /** We choose to skip all the tests that are expected to crash. */
                    if (!mFileFilter.isCrash(testRelativePath)) {
                        mTestsList.add(testRelativePath);
                    } else {
                    /**
                             * TODO: Summarizer is now in service - figure out how to send the info.
                             * Previously: mSummarizer.addSkippedTest(relativePath);
                             */
                    }
                }
            }
        }
    }
}
Example 95
Project: JPaxos-master  File: TestLoader.java View source code
public void parse() {
    MyBufferedReader testBufferedReader = new MyBufferedReader(testReader);
    try {
        modelnetFile = testBufferedReader.readLine();
        replicaCmd = testBufferedReader.readLine();
        clientCmd = testBufferedReader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
    while (true) {
        try {
            line = testBufferedReader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        if (line == null)
            break;
        String line = this.line.toUpperCase();
        LinkedList<String> tokens = new LinkedList<String>();
        tokens.addAll(Arrays.asList(line.split("[\t ]")));
        String time = tokens.removeFirst();
        try {
            scheduler.addTask(time, readCommand(tokens));
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}
Example 96
Project: gs-collections-master  File: Java8TestClass.java View source code
private static List<Class<?>> getInterfaces(Class<?> testClass) {
    LinkedList<Class<?>> queue = new LinkedList<Class<?>>();
    queue.add(testClass);
    Set<Class<?>> visited = new HashSet<Class<?>>();
    visited.add(testClass);
    List<Class<?>> results = new ArrayList<Class<?>>();
    while (!queue.isEmpty()) {
        Class<?> anInterface = queue.poll();
        results.add(anInterface);
        Class<?>[] parentInterfaces = anInterface.getInterfaces();
        for (Class<?> parentInterface : parentInterfaces) {
            if (!visited.contains(parentInterface)) {
                visited.add(parentInterface);
                queue.add(parentInterface);
            }
        }
    }
    return results;
}
Example 97
Project: Eclipse-Postfix-Code-Completion-master  File: RemoveBlockCommentAction.java View source code
/*
	 * @see org.eclipse.jdt.internal.ui.actions.AddBlockCommentAction#runInternal(org.eclipse.jface.text.ITextSelection, org.eclipse.jface.text.IDocumentExtension3, org.eclipse.jdt.internal.ui.actions.AddBlockCommentAction.Edit.EditFactory)
	 */
@Override
protected void runInternal(ITextSelection selection, IDocumentExtension3 docExtension, Edit.EditFactory factory) throws BadPartitioningException, BadLocationException {
    List<Edit> edits = new LinkedList<Edit>();
    int tokenLength = getCommentStart().length();
    int offset = selection.getOffset();
    int endOffset = offset + selection.getLength();
    ITypedRegion partition = docExtension.getPartition(IJavaPartitions.JAVA_PARTITIONING, offset, false);
    int partOffset = partition.getOffset();
    int partEndOffset = partOffset + partition.getLength();
    while (partEndOffset < endOffset) {
        if (partition.getType() == IJavaPartitions.JAVA_MULTI_LINE_COMMENT) {
            //$NON-NLS-1$
            edits.add(//$NON-NLS-1$
            factory.createEdit(partOffset, tokenLength, ""));
            //$NON-NLS-1$
            edits.add(//$NON-NLS-1$
            factory.createEdit(partEndOffset - tokenLength, tokenLength, ""));
        }
        partition = docExtension.getPartition(IJavaPartitions.JAVA_PARTITIONING, partEndOffset, false);
        partOffset = partition.getOffset();
        partEndOffset = partOffset + partition.getLength();
    }
    if (partition.getType() == IJavaPartitions.JAVA_MULTI_LINE_COMMENT) {
        //$NON-NLS-1$
        edits.add(factory.createEdit(partOffset, tokenLength, ""));
        //$NON-NLS-1$
        edits.add(factory.createEdit(partEndOffset - tokenLength, tokenLength, ""));
    }
    executeEdits(edits);
}
Example 98
Project: btpka3.github.com-master  File: TestOrder.java View source code
private static List<Queue<Item>> groupByUser(List<Item> itemList) {
    List<Queue<Item>> groupedList = new LinkedList<Queue<Item>>();
    Queue<Item> lastQueue = null;
    for (Item curItem : itemList) {
        if (lastQueue == null) {
            lastQueue = new LinkedList<Item>();
            groupedList.add(lastQueue);
        } else {
            Item lastItem = lastQueue.peek();
            if (lastItem.userId != curItem.userId) {
                lastQueue = new LinkedList<Item>();
                groupedList.add(lastQueue);
            }
        }
        lastQueue.add(curItem);
    }
    return groupedList;
}
Example 99
Project: k3po-master  File: K3poTestRule.java View source code
@Override
public Statement apply(Statement statement, final Description description) {
    TestSpecification testSpecification = description.getAnnotation(TestSpecification.class);
    String[] scripts = (testSpecification != null) ? testSpecification.value() : null;
    if (scripts != null) {
        String packagePath = this.scriptRoot;
        if (packagePath == null) {
            Class<?> testClass = description.getTestClass();
            String packageName = testClass.getPackage().getName();
            packagePath = packageName.replaceAll("\\.", "/");
        }
        List<String> scriptNames = new LinkedList<>();
        for (String script : scripts) {
            // strict compatibility (relax to support fully qualified paths later)
            if (script.startsWith("/")) {
                throw new IllegalArgumentException("Script path must be relative");
            }
            String scriptName = format("%s/%s", packagePath, script);
            scriptNames.add(scriptName);
        }
        this.k3poTestStatement = new K3poTestStatement(statement, latch, scriptNames);
        statement = this.k3poTestStatement;
    }
    return super.apply(statement, description);
}
Example 100
Project: gluu-opendj-master  File: PropertiesFilesTest.java View source code
/**
   * Tests that a properties file does not have duplicate keys.  This
   * is not enforced by GenerateMessageFile because it uses
   * java.util.Properties to load and process the files which ignores
   * duplicate keys.
   *
   * @param propertiesFile file
   * @throws IOException if problems reading the file
   */
@Test(dataProvider = "messagePropertiesFiles")
public void testForDuplicateKeys(File propertiesFile) throws IOException {
    Set<String> keys = new HashSet<String>();
    BufferedReader reader = new BufferedReader(new FileReader(propertiesFile));
    List<String> errors = new LinkedList<String>();
    String prevLine = null;
    String line;
    while (null != (line = reader.readLine())) {
        if (// not a value continuation
        !(prevLine == null || prevLine.endsWith("\\")) && // not a comment
        !(line.startsWith("#")) && (line.indexOf('=') > 0)) {
            // defines a key
            String key = line.substring(0, line.indexOf('='));
            if (keys.contains(key)) {
                errors.add(key);
            } else {
                keys.add(key);
            }
        }
        prevLine = line;
    }
    assertTrue(errors.isEmpty(), "The following keys are defined multiple times in " + propertiesFile.getName() + ":" + EOL + StaticUtils.listToString(errors, EOL));
}
Example 101
Project: SpaceDefence-master  File: ParseBytes.java View source code
@Override
public void run() {
    GameEvent event;
    while (bMonitor.isOpen()) {
        boolean gsEvent = false;
        byte[] byteArray = bMonitor.readArrayFromServer();
        Queue<Byte> byteQueue = new LinkedList<Byte>();
        for (Byte b : byteArray) {
            byteQueue.add(b);
        }
        byte p = byteQueue.poll();
        if (p != EventProtocol.PLAYER_ID) {
            Logger.log("ERROR IN PROTOCOL, recieved:" + p + " excpected:" + EventProtocol.PLAYER_ID);
            continue;
        }
        byte id = byteQueue.poll();
        event = new GameEvent();
        Byte b = null;
        float xpos;
        float ypos;
        Vector2f pos;
        while ((b = byteQueue.poll()) != null) {
            switch(b) {
                case EventProtocol.GAME_STARTED:
                    gsMonitor.startGame();
                    gsEvent = true;
                    break;
                case EventProtocol.LOCAL_PLAYER_INIT:
                    Logger.log("Local player init");
                    gsMonitor.addLocalPlayer(id);
                    break;
                case EventProtocol.OPPONENT_PLAYER_INIT:
                    Logger.log("opponent init");
                    gsMonitor.addOpponentPlayer(id);
                    break;
                case EventProtocol.PLAYER_LOST_CONNECTION:
                    Logger.log("Player lost connection");
                    gsMonitor.removePlayer(id);
                    break;
                case EventProtocol.EVENT_POS:
                    xpos = bytesToFloat(byteQueue);
                    ypos = bytesToFloat(byteQueue);
                    pos = new Vector2f(xpos, ypos);
                    try {
                        event.putPosition(pos);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case EventProtocol.PLAYER_DIR:
                    float xdir = bytesToFloat(byteQueue);
                    float ydir = bytesToFloat(byteQueue);
                    Vector2f dir = new Vector2f(xdir, ydir);
                    try {
                        event.putDirection(dir);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case EventProtocol.PLAYER_SCORE:
                    event.setScore(this.bytesToInt(byteQueue));
                    break;
                case EventProtocol.PLAYER_HP:
                    event.setPlayerHp(this.bytesToInt(byteQueue));
                    break;
                case EventProtocol.CREEP_INIT:
                    {
                        // get rid of CREEP_ID byte
                        byteQueue.poll();
                        int creepId = bytesToInt(byteQueue);
                        byte sendId = byteQueue.poll();
                        event.setRole(GameRole.CREEP);
                        event.setId(creepId);
                        event.setSendId(sendId);
                        break;
                    }
                case EventProtocol.CREEP_DIED:
                    {
                        byteQueue.poll();
                        int creepId = bytesToInt(byteQueue);
                        event.setRole(GameRole.CREEP);
                        event.setId(creepId);
                        event.setDead();
                        break;
                    }
                case EventProtocol.CREEP_SENT:
                    {
                        event.setRole(GameRole.CREEP);
                        event.setId(id);
                        event.setInit(bytesToInt(byteQueue));
                        id = gsMonitor.getLocalID();
                        break;
                    }
                case EventProtocol.BULLET_INIT:
                    {
                        // get rid of BULLET_ID byte
                        byteQueue.poll();
                        int bulletId = bytesToInt(byteQueue);
                        event.setRole(GameRole.BULLET);
                        event.setId(bulletId);
                        break;
                    }
                case EventProtocol.BULLET_DIED:
                    {
                        byteQueue.poll();
                        int bulletId = bytesToInt(byteQueue);
                        event.setRole(GameRole.BULLET);
                        event.setId(bulletId);
                        event.setDead();
                        break;
                    }
            }
        }
        if (!gsEvent) {
            gsMonitor.put(id, event);
        }
    }
    gsMonitor.removeLocalPlayer();
}