private void processQueueMessages() { LinkedList<BPServiceActorAction> duplicateQueue; synchronized (bpThreadQueue) { duplicateQueue = new LinkedList<BPServiceActorAction>(bpThreadQueue); bpThreadQueue.clear(); } while (!duplicateQueue.isEmpty()) { BPServiceActorAction actionItem = duplicateQueue.remove(); try { actionItem.reportTo(bpNamenode, bpRegistration); } catch (BPServiceActorActionException baae) { LOG.warn(baae.getMessage() + nnAddr , baae); // Adding it back to the queue if not present bpThreadEnqueue(actionItem); } } }
/** * Compute the Levenshtein distance; the number of inserted, deleted or * substituted characters. * @param diffs LinkedList of Diff objects. * @return Number of changes. */ public int diff_levenshtein(LinkedList<Diff> diffs) { int levenshtein = 0; int insertions = 0; int deletions = 0; for (Diff aDiff : diffs) { switch (aDiff.operation) { case INSERT: insertions += aDiff.text.length(); break; case DELETE: deletions += aDiff.text.length(); break; case EQUAL: // A deletion and an insertion is one substitution. levenshtein += Math.max(insertions, deletions); insertions = 0; deletions = 0; break; } } levenshtein += Math.max(insertions, deletions); return levenshtein; }
@Override public List<WorkflowInstance> getWorkflows(WorkflowInstanceQuery workflowInstanceQuery, int maxItems, int skipCount) { LinkedList<WorkflowInstance> results = new LinkedList<WorkflowInstance>(); if (Boolean.FALSE.equals(workflowInstanceQuery.getActive()) == false) { //Add active. results.addAll(getWorkflowsInternal(workflowInstanceQuery, true, maxItems, skipCount)); } if (Boolean.TRUE.equals(workflowInstanceQuery.getActive()) == false) { //Add complete results.addAll(getWorkflowsInternal(workflowInstanceQuery, false, maxItems, skipCount)); } return results; }
@DataProvider(name="listProvider", parallel=true) public static Object[][] listCases() { final List<Object[]> cases = new LinkedList<>(); cases.add(new Object[] { Collections.emptyList() }); cases.add(new Object[] { new ArrayList<>() }); cases.add(new Object[] { new LinkedList<>() }); cases.add(new Object[] { new Vector<>() }); cases.add(new Object[] { new Stack<>() }); cases.add(new Object[] { new CopyOnWriteArrayList<>() }); cases.add(new Object[] { Arrays.asList() }); List<Integer> l = Arrays.asList(42); cases.add(new Object[] { new ArrayList<>(l) }); cases.add(new Object[] { new LinkedList<>(l) }); cases.add(new Object[] { new Vector<>(l) }); Stack<Integer> s = new Stack<>(); s.addAll(l); cases.add(new Object[]{s}); cases.add(new Object[] { new CopyOnWriteArrayList<>(l) }); cases.add(new Object[] { l }); return cases.toArray(new Object[0][cases.size()]); }
public static void main(String[] args) { LinkedList dimensionlist = Lister.listdimensions(); LinkedList unitlist = Lister.listUnits(); for (Iterator e = dimensionlist.iterator(); e.hasNext();) { try { String enext = e.next().toString(); Dimension d = stringToDim(enext); enext = enext.substring(14, enext.length()); System.out.println("\n" + enext + ":"); filter(d, unitlist); } catch (Throwable er) { System.err.println(er); } } }
/** * Tests the capability to sort and paginate the list of people orderBy = * lastName ASC skip = 2, count = 3 * * @throws Exception */ @Test public void testPagingAndSortingByLastName() throws Exception { publicApiClient.setRequestContext(new RequestContext(account4.getId(), account4Admin, "admin")); // paging int skipCount = 2; int maxItems = 3; int totalResults = 5; PublicApiClient.Paging paging = getPaging(skipCount, maxItems, totalResults, totalResults); // orderBy=lastName ASC PublicApiClient.ListResponse<Person> resp = listPeople(paging, "lastName", true, 200); List<Person> expectedList = new LinkedList<>(); expectedList.add((Person) personBen); expectedList.add((Person) personAliceD); expectedList.add((Person) personAlice); checkList(expectedList, paging.getExpectedPaging(), resp); }
public String cntByTimeString() { DecimalFormat df = new DecimalFormat(DECIMAL_PATTERN); List<String> millisStr = new LinkedList<String>(); Iterator <Entry<Integer,Integer>>iter = millisMap.entrySet().iterator(); while(iter.hasNext()) { Entry<Integer,Integer> millisEntry = iter.next(); Integer bucket = (Integer)millisEntry.getKey(); Integer bucketCount = (Integer)millisEntry.getValue(); int minMillis = bucket.intValue() * millisPerBucket; int maxMillis = (bucket.intValue() + 1) * millisPerBucket; millisStr.add( df.format(minMillis/MILLIS_PER_SECOND)+" s "+ "- "+ df.format(maxMillis/MILLIS_PER_SECOND)+" s "+ "= " + bucketCount); } return millisStr.toString(); }
/** * Reads the channel buffer and returns object. * * @param cb channelBuffer * @return object of flow spec packet length * @throws BgpParseException while parsing BgpFsPacketLength */ public static BgpFsPacketLength read(ChannelBuffer cb) throws BgpParseException { List<BgpFsOperatorValue> operatorValue = new LinkedList<>(); byte option; short packetLen; do { option = (byte) cb.readByte(); int len = (option & Constants.BGP_FLOW_SPEC_LEN_MASK) >> 4; if ((1 << len) == 1) { packetLen = cb.readByte(); operatorValue.add(new BgpFsOperatorValue(option, new byte[] {(byte) packetLen})); } else { packetLen = cb.readShort(); operatorValue.add(new BgpFsOperatorValue(option, new byte[] {(byte) (packetLen >> 8), (byte) packetLen})); } } while ((option & Constants.BGP_FLOW_SPEC_END_OF_LIST_MASK) == 0); return new BgpFsPacketLength(operatorValue); }
@Override protected void resetConfigParams() { status = FunGameView.STATUS_GAME_PREPAR; controllerPosition = DIVIDING_LINE_SIZE; enemySpeed = DensityUtil.dp2px(1); bulletSpeed = DensityUtil.dp2px(4); levelNum = DEFAULT_TANK_MAGIC_TOTAL_NUM; wipeOutNum = 0; once = true; enemyTankSpace = controllerSize + barrelSize + DEFAULT_ENEMY_TANK_NUM_SPACING; bulletSpace = DEFAULT_BULLET_NUM_SPACING; eTankSparseArray = new SparseArray<>(); for (int i = 0; i < TANK_ROW_NUM; i++) { Queue<RectF> rectFQueue = new LinkedList<>(); eTankSparseArray.put(i, rectFQueue); } mBulletList = new LinkedList<>(); }
private void prepareRays() { /*Délky postranních paprsků jsou 8 a 12. Délky šikmých se vynásobí 2 a předního se vynásobí odmocninou(3).*/ int shortLength = 8; int longLength = 12; shortSideRayLength = (int) (UnrealUtils.CHARACTER_COLLISION_RADIUS * shortLength * DISTANCE_FROM_THE_WALL / 166f); //8 longSideRayLength = (int) (UnrealUtils.CHARACTER_COLLISION_RADIUS * longLength * DISTANCE_FROM_THE_WALL / 166f); //12 shortSideFrontRayLength = (int) (UnrealUtils.CHARACTER_COLLISION_RADIUS * shortLength * 2 * DISTANCE_FROM_THE_WALL / 166f); //20 longSideFrontRayLength = (int) (UnrealUtils.CHARACTER_COLLISION_RADIUS * longLength * 2 * DISTANCE_FROM_THE_WALL / 166f); //30 shortFrontRayLength = (int) (UnrealUtils.CHARACTER_COLLISION_RADIUS * shortLength * Math.sqrt(3) * DISTANCE_FROM_THE_WALL / 166f); //18 longFrontRayLength = (int) (UnrealUtils.CHARACTER_COLLISION_RADIUS * longLength * Math.sqrt(3) * DISTANCE_FROM_THE_WALL / 166f); //27 //Five rays are created. LinkedList<SteeringRay> rayList = new LinkedList<SteeringRay>(); rayList.add(new SteeringRay(NLEFT, new Vector3d(0, -1, 0), longSideRayLength)); rayList.add(new SteeringRay(NLEFTFRONT, new Vector3d(Math.sqrt(3), -1, 0), longSideFrontRayLength)); rayList.add(new SteeringRay(NRIGHTFRONT, new Vector3d(Math.sqrt(3), 1, 0), longSideFrontRayLength)); rayList.add(new SteeringRay(NRIGHT, new Vector3d(0, 1, 0), longSideRayLength)); rayList.add(new SteeringRay(NFRONT, new Vector3d(1, 0, 0), longFrontRayLength)); rayManager.addRays(SteeringType.WALL_FOLLOWING, rayList, this); raysReady = false; //System.out.println("Rays wall preparation end."); }
/** Replacing items with different objects. */ public void testReplacingObjectsDoesNotGenerateException () throws Exception { LinkedList arr = new LinkedList (); class R extends Exception implements Cloneable { } arr.add (new R ()); arr.add (new R ()); ic.set (arr, null); arr.clear(); arr.add (new R ()); arr.add (new R ()); ic.set (arr, null); }
public static void rectifyMisRecogCapUnderNotesChar(CharLearningMgr clm, StructExprRecog ser) { if (ser.mnExprRecogType == EXPRRECOGTYPE_ENUMTYPE && !ser.isLetterChar() && !ser.isNumberChar() && ser.mType != UnitProtoType.Type.TYPE_ADD && ser.mType != UnitProtoType.Type.TYPE_SUBTRACT && ser.mType != UnitProtoType.Type.TYPE_WAVE && ser.mType != UnitProtoType.Type.TYPE_STAR && ser.mType != UnitProtoType.Type.TYPE_DOT) { // because it is cap under note, it cannot be dot multiply // this letter might be miss recognized, look for another candidate. LinkedList<CharCandidate> listCands = clm.findCharCandidates(ser.mType, ser.mstrFont); for (int idx1 = 0; idx1 < listCands.size(); idx1 ++) { if (isLetterChar(listCands.get(idx1).mType) || isNumberChar(listCands.get(idx1).mType) || ser.mType == UnitProtoType.Type.TYPE_ADD || ser.mType == UnitProtoType.Type.TYPE_SUBTRACT || ser.mType == UnitProtoType.Type.TYPE_WAVE || ser.mType == UnitProtoType.Type.TYPE_STAR || ser.mType == UnitProtoType.Type.TYPE_DOT) { // ok, change it to the new char ser.changeSEREnumType(listCands.get(idx1).mType, (listCands.get(idx1).mstrFont.length() == 0)?ser.mstrFont:listCands.get(idx1).mstrFont); break; } } } }
public static void main(String[] args) throws IOException { while ((line = in.readLine()) != null) { n = Integer.parseInt(line); list = new LinkedList<Integer>(); for (int i = 2; i < n; i += 2) { list.add(i); } c = 3; while (list.size() > c) { for(int i=0; i < list.size(); i++) { if (i % c == 0) { } } c++; } } System.out.print(sb.toString()); }
public static @NonNull RefreshResult refreshDirectory(@NonNull Context context, @NonNull SignalServiceAccountManager accountManager, @NonNull String localNumber) throws IOException { TextSecureDirectory directory = TextSecureDirectory.getInstance(context); Set<String> eligibleContactNumbers = directory.getPushEligibleContactNumbers(localNumber); List<ContactTokenDetails> activeTokens = accountManager.getContacts(eligibleContactNumbers); if (activeTokens != null) { for (ContactTokenDetails activeToken : activeTokens) { eligibleContactNumbers.remove(activeToken.getNumber()); activeToken.setNumber(activeToken.getNumber()); } directory.setNumbers(activeTokens, eligibleContactNumbers); return updateContactsDatabase(context, localNumber, activeTokens, true); } return new RefreshResult(new LinkedList<String>(), false); }
public ConsolePane() { WebView view = new WebView(); view.setContextMenuEnabled(false); webEngine = view.getEngine(); messageQueue = new LinkedList<>(); ObservableValue<State> property = webEngine.getLoadWorker().stateProperty(); OnLoadListener.register(this::onLoad, property); String content = "<html><head></head><body></body></html>"; webEngine.loadContent(content); ConsolePaneEventHandler eventHandler = new ConsolePaneEventHandler(); EventRegistry.getGlobalRegistry().register(eventHandler); this.setCenter(view); }
public static String[] toArray(String oriString, String separator) { if (oriString == null) { throw new NullPointerException("The parameter [string] cannot be null."); } else if (separator == null) { throw new NullPointerException("The parameter [separator] cannot be null."); } else if (separator.length() == 0) { throw new IllegalArgumentException("The parameter [separator] cannot be empty."); } else { StringTokenizer st = new StringTokenizer(oriString, separator); List list = new LinkedList(); while (st.hasMoreTokens()) { list.add(st.nextToken()); } return (String[]) list.toArray(new String[list.size()]); } }
@Override public List<Game> pullGamesFromNetwork(Context context) throws IOException, ExpectedElementNotFound { this.context = context; if (context != null) { Log.e(TAG, "Started " + getAcronym() + " " + getScoreType()); } List<Game> updatedGameList = new LinkedList<>(); Document parsedDocument = Jsoup.connect(getBaseUrl()).timeout(60 * 1000).get(); updatedGameList = scrapeUpdateGamesFromParsedDocument(updatedGameList, parsedDocument); if (context != null) { storeDocument(parsedDocument); // Only add dates that are scheduled for that date. List<Game> tempList = new LinkedList<>(updatedGameList); for (Game game : tempList) { if (game.getGameAddDate() != new DateTime(Constants.DATE.VEGAS_TIME_ZONE).withTimeAtStartOfDay().getMillis() // || new DateTime(game.getGameDateTime(), Constants.DATE.VEGAS_TIME_ZONE).toDateTime(DateTimeZone.getDefault()).isBeforeNow() ) { updatedGameList.remove(game); } } // Initiate teams for this league if not initiated syncDateWithEspn(updatedGameList); } updateLibraryInDatabase(updatedGameList, context); return updatedGameList; }
@Test public void retrieveParametersForTimeSlice_PeriodValuesWithinTimeSliceAndOnTimeSliceEnd() { // given createPriodValue( DateTimeHandling.calculateMillis("2013-05-01 00:00:00"), DateTimeHandling.calculateMillis("2013-05-01 00:00:01"), VALUE_2); createPriodValue( DateTimeHandling.calculateMillis("2013-04-30 23:59:59"), DateTimeHandling.calculateMillis("2013-05-01 00:00:00"), VALUE_1); // when LinkedList<XParameterPeriodValue> result = calculator .retrieveParametersForTimeSlice(periodValues, timeSlice); // then assertEquals(2, result.size()); assertEquals(VALUE_2, result.get(0).getValue()); assertEquals(VALUE_1, result.get(1).getValue()); }
@Override public void onMethodEnter(final String cls, final String method, final String argTypes) { final long threadId = Thread.currentThread().getId(); Deque<MethodInfo> methodStack = threadMethodStack.get(threadId); if (methodStack == null) { //线程首次调用,创建该线程的临时调用栈 methodStack = new LinkedList<>(); threadMethodStack.put(threadId, methodStack); } //TODO 考虑使用对象池!!!! //创建新的MethodInfo MethodInfo info = new MethodInfo(); info.setThreadId(threadId); info.setSignature(createSignature(cls, method, argTypes)); //将当前方法添加到线程的临时调用栈 methodStack.push(info); }
public ColorScheme getDefaultColorScheme() { List<ColorRGB> listOfColors = new LinkedList<ColorRGB>(); Color minColor = getColorFromProperty(MainFrame.PROPERTY_RAPIDMINER_GUI_PLOTTER_LEGEND_MINCOLOR, Color.BLUE); ColorRGB minColorRGB = ColorRGB.convertColorToColorRGB(minColor); listOfColors.add(minColorRGB); Color maxColor = getColorFromProperty(MainFrame.PROPERTY_RAPIDMINER_GUI_PLOTTER_LEGEND_MAXCOLOR, Color.RED); ColorRGB maxColorRGB = ColorRGB.convertColorToColorRGB(maxColor); listOfColors.add(maxColorRGB); Color third = ContinuousColorProvider.getColorForValue(3, 255, false, 0, 4, minColor, maxColor); listOfColors.add(ColorRGB.convertColorToColorRGB(third)); Color second = ContinuousColorProvider.getColorForValue(2, 255, false, 0, 5, minColor, maxColor); listOfColors.add(ColorRGB.convertColorToColorRGB(second)); Color first = ContinuousColorProvider.getColorForValue(1, 255, false, 0, 5, minColor, maxColor); listOfColors.add(ColorRGB.convertColorToColorRGB(first)); return new ColorScheme(I18N.getGUILabel("plotter.default_color_scheme_name.label"), listOfColors, minColorRGB, maxColorRGB); }
public static void setJumpOrderIterative(PostingListNode<Integer> node) { LinkedList<PostingListNode<Integer>> queue = new LinkedList<>(); PostingListNode<Integer> current = node; int order = 0; while (current != null || !queue.isEmpty()) { if (current == null || current.data != -1) { current = queue.poll(); } if (current.data == -1) current.data = order++; if (current.next != null && current.next.data == -1) queue.addLast(current.next); current = current.jump; } }
public int deleteJournalRecords(IdentifiersContainer contactIds, @Nullable String filter) { if (contactIds.isEmpty()) return 0; boolean all = contactIds.isAll(); List<String> ids = contactIds.getIdentifiers(new LinkedList<String>()); // build 'WHERE' clause String clause = Common.concatClauses(new String[]{ Common.getLikeClause(JournalTable.Column.CALLER, filter), Common.getInClause(JournalTable.Column.ID, all, ids) }); // delete records SQLiteDatabase db = getWritableDatabase(); return db.delete(JournalTable.NAME, clause, null); }
public Collection<ItemHolder> calculateDrops(DropListScope dropListScope, L2Character victim, L2Character killer) { final List<IDropItem> dropList = getDropList(dropListScope); if (dropList == null) { return null; } Collection<ItemHolder> calculatedDrops = null; for (IDropItem dropItem : dropList) { final Collection<ItemHolder> drops = dropItem.calculateDrops(victim, killer); if ((drops == null) || drops.isEmpty()) { continue; } if (calculatedDrops == null) { calculatedDrops = new LinkedList<>(); } calculatedDrops.addAll(drops); } return calculatedDrops; }
public WebSocketChannelClient(Handler handler, WebSocketChannelEvents events) { this.handler = handler; this.events = events; roomID = null; clientID = null; wsSendQueue = new LinkedList<String>(); state = WebSocketConnectionState.NEW; }
/** * Test of getSymbolicVariables method, of class SymbolicVariableList. */ @Test public void testGetSymbolicVariables() { System.out.println("getSymbolicVariables"); String id = "test"; InternalTypeContainer internalTypeContainer = new InternalTypeContainer(InternalTypeRep.INTEGER); SymbolicVariableList instance = new SymbolicVariableList(); instance.addSymbolicVariable(id, internalTypeContainer); assert (((LinkedList<SymbolicVariable>)instance.getSymbolicVariables()).getFirst().getInternalTypeContainer().getInternalType() == InternalTypeRep.INTEGER); assert (((LinkedList<SymbolicVariable>)instance.getSymbolicVariables()).getFirst().getId().equals("test")); }
/** * Reads channel buffer and parses link identifier. * * @param cb ChannelBuffer * @param protocolId in linkstate nlri * @return object of BGPLinkLSIdentifier * @throws BgpParseException while parsing link identifier */ public static BgpLinkLSIdentifier parseLinkIdendifier(ChannelBuffer cb, byte protocolId) throws BgpParseException { //Parse local node descriptor NodeDescriptors localNodeDescriptors = new NodeDescriptors(); localNodeDescriptors = parseNodeDescriptors(cb, NodeDescriptors.LOCAL_NODE_DES_TYPE, protocolId); //Parse remote node descriptor NodeDescriptors remoteNodeDescriptors = new NodeDescriptors(); remoteNodeDescriptors = parseNodeDescriptors(cb, NodeDescriptors.REMOTE_NODE_DES_TYPE, protocolId); //Parse link descriptor LinkedList<BgpValueType> linkDescriptor = new LinkedList<>(); linkDescriptor = parseLinkDescriptors(cb); return new BgpLinkLSIdentifier(localNodeDescriptors, remoteNodeDescriptors, linkDescriptor); }
public CompilerLoader(String source_base, String target_base, String[] class_pathes, String[] dflt_import_pkgs) throws CompileException { this.source_base = source_base; this.target_base = target_base; this.class_pathes = class_pathes; this.dflt_import_pkgs = dflt_import_pkgs; this.classnode_hash = new HashMap<String, ClassNode>(); this.fspkg_hash = new HashMap<String, TFilesystemPkg>(); this.resolvedclass_hash = new HashMap<String, TResolvedClass>(); this.opfuncmap_hash = new HashMap<String, String>(); init_opfuncmap_hash(); this.jarcache_hash = new HashMap<String, JarFileCache>(); for (String cl_path : class_pathes) { if (cl_path.endsWith(JAR_FILENAME_EXTENSION)) { try { jarcache_hash.put(cl_path, new JarFileCache(cl_path)); } catch (IOException e) { throw new CompileException("IOException Occurred(" + e.getMessage() + ")"); } } } this.root_pkg = new TContextPkg("root", this); this.context_stack = new LinkedList<TContext>(); this.reduction_stack = new LinkedList<Reduction>(); this.branch_tree = new BranchTree(); }
/** * Expands a list of arguments into {@link PathData} objects. The default * behavior is to call {@link #expandArgument(String)} on each element * which by default globs the argument. The loop catches IOExceptions, * increments the error count, and displays the exception. * @param args strings to expand into {@link PathData} objects * @return list of all {@link PathData} objects the arguments * @throws IOException if anything goes wrong... */ protected LinkedList<PathData> expandArguments(LinkedList<String> args) throws IOException { LinkedList<PathData> expandedArgs = new LinkedList<PathData>(); for (String arg : args) { try { expandedArgs.addAll(expandArgument(arg)); } catch (IOException e) { // other exceptions are probably nasty displayError(e); } } return expandedArgs; }
public GOTermAnnotationReader(String annotationFile) { try { annotationMap = new HashMap<>(); BufferedReader br = new BufferedReader(new FileReader(annotationFile)); String strLine; String[] strArr; LinkedList<String> goIDList; while(br.ready()) { strLine = br.readLine(); if(strLine.startsWith("!")) continue; strArr = strLine.split("\t"); if(annotationMap.containsKey(strArr[2])) goIDList = annotationMap.get(strArr[2]); else { goIDList = new LinkedList<>(); annotationMap.put(strArr[2], goIDList); } goIDList.add(strArr[4]); } br.close(); } catch (IOException e) { e.printStackTrace(); } }
private static Collection<String> listTests(Class<?> clazz) { File dirOrArchive = FileUtil.archiveOrDirForURL(clazz.getProtectionDomain().getCodeSource().getLocation()); assertTrue(dirOrArchive.exists()); if (dirOrArchive.isFile()) { return listTestsFromJar(dirOrArchive); } else { Collection<String> result = new LinkedList<String>(); listTestsFromFilesystem(dirOrArchive, "", result); return result; } }
public ClassGenerator addConstructor(String code) { if( mConstructors == null ) mConstructors = new LinkedList<String>(); mConstructors.add(code); return this; }
/** * Constructs a new Koth instance * * @param name - the name of the Koth * @param time - the initial capture time of the Koth */ public Koth(String name, int time) { this.name = name; this.time = time; this.maxCapTime = time; this.capper = null; this.capQueue = new LinkedList<>(); }
public AbsFuncType[] getLocalConstructors() throws CompileException { TContext context = null; TContextFunc func_context = null; LinkedList<TContextFunc> const_list = new LinkedList<>(); int length = childcontext_list.size(); for (int i = 0; i < length; i++) { context = childcontext_list.get(i); if (context.isForm(AbsType.FORM_FUNC) && context.isName(AbsClassType.CONSTRUCTOR_NAME)) { func_context = (TContextFunc) context; const_list.add(func_context); } } if (const_list.size() == 0) { return null; } AbsFuncType[] arr = new AbsFuncType[const_list.size()]; for (int i = 0; i < arr.length; i++) { arr[i] = (AbsFuncType) const_list.get(i); } return arr; }
@JsonApiFindAllWithIds public Iterable<Task> findAll(Iterable<Long> ids, QuerySpec queryParams) { List<Task> values = new LinkedList<>(); for (Task value : map.values()) { if (contains(value, ids)) { values.add(value); } } return values; }
@Override public Iterable<Tunnel> getTunnels(DeviceId deviceId) { List<Tunnel> tunnelList = new LinkedList<>(); for (Tunnel t : tunnelIdAsKeyStore.values()) { for (Link l : t.path().links()) { if (l.src().deviceId().equals(deviceId) || l.dst().deviceId().equals(deviceId)) { tunnelList.add(t); break; } } } return tunnelList; }
@Test public void processOptionsHuman() throws IOException { LinkedList<String> options = new LinkedList<String>(); options.add("-h"); Ls ls = new Ls(); ls.processOptions(options); assertFalse(ls.isPathOnly()); assertTrue(ls.isDirRecurse()); assertTrue(ls.isHumanReadable()); assertFalse(ls.isRecursive()); assertFalse(ls.isOrderReverse()); assertFalse(ls.isOrderSize()); assertFalse(ls.isOrderTime()); assertFalse(ls.isUseAtime()); }
public List<Recipient> getUnverifiedRecipients(Context context) { List<Recipient> unverified = new LinkedList<>(); for (IdentityRecord identityRecord : identityRecords) { if (identityRecord.getVerifiedStatus() == VerifiedStatus.UNVERIFIED) { unverified.add(RecipientFactory.getRecipientForId(context, identityRecord.getRecipientId(), false)); } } return unverified; }
private boolean equivalentLists(List<String> newDefinitions, List<String> oldDefinitions) { LinkedList<String> checkList = new LinkedList<>(oldDefinitions); for (String filename : newDefinitions) { if (!checkList.remove(filename)) { return false; } } return checkList.isEmpty(); // If it is empty, all filenames were found / matched. }
/** * Given an array of types, return a subset of their class loaders that are maximal according to the * "can see other loaders' classes" relation, which is presumed to be a partial ordering. * @param types types * @return a collection of maximum visibility class loaders. It is guaranteed to have at least one element. */ private static Collection<ClassAndLoader> getMaximumVisibilityLoaders(final Class<?>[] types) { final List<ClassAndLoader> maximumVisibilityLoaders = new LinkedList<>(); outer: for(final ClassAndLoader maxCandidate: getClassLoadersForTypes(types)) { final Iterator<ClassAndLoader> it = maximumVisibilityLoaders.iterator(); while(it.hasNext()) { final ClassAndLoader existingMax = it.next(); final boolean candidateSeesExisting = maxCandidate.canSee(existingMax); final boolean exitingSeesCandidate = existingMax.canSee(maxCandidate); if(candidateSeesExisting) { if(!exitingSeesCandidate) { // The candidate sees the the existing maximum, so drop the existing one as it's no longer maximal. it.remove(); } // NOTE: there's also the anomalous case where both loaders see each other. Not sure what to do // about that one, as two distinct class loaders both seeing each other's classes is weird and // violates the assumption that the relation "sees others' classes" is a partial ordering. We'll // just not do anything, and treat them as incomparable; hopefully some later class loader that // comes along can eliminate both of them, if it can not, we'll end up with ambiguity anyway and // throw an error at the end. } else if(exitingSeesCandidate) { // Existing sees the candidate, so drop the candidate. continue outer; } } // If we get here, no existing maximum visibility loader could see the candidate, so the candidate is a new // maximum. maximumVisibilityLoaders.add(maxCandidate); } return maximumVisibilityLoaders; }
@Test public void testTimestampsFilter() throws Exception { // Empty timestamp list TimestampsFilter timestampsFilter = new TimestampsFilter(new LinkedList<Long>()); assertTrue(timestampsFilter.areSerializedFieldsEqual( ProtobufUtil.toFilter(ProtobufUtil.toFilter(timestampsFilter)))); // Non-empty timestamp list LinkedList<Long> list = new LinkedList<Long>(); list.add(new Long(System.currentTimeMillis())); list.add(new Long(System.currentTimeMillis())); timestampsFilter = new TimestampsFilter(list); assertTrue(timestampsFilter.areSerializedFieldsEqual( ProtobufUtil.toFilter(ProtobufUtil.toFilter(timestampsFilter)))); }