Java Code Examples for java.util.LinkedList#removeFirst()

The following examples show how to use java.util.LinkedList#removeFirst() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ATESwitchPreference.java    From MyBookshelf with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onBindView(View view) {
    super.onBindView(view);
    if (view.isInEditMode()) {
        return;
    }
    if (view instanceof ViewGroup) {
        ViewGroup viewGroup = (ViewGroup) view;
        LinkedList<ViewGroup> queue = new LinkedList<>();
        queue.add(viewGroup);
        while (!queue.isEmpty()) {
            ViewGroup current = queue.removeFirst();
            for (int i = 0; i < current.getChildCount(); i++) {
                if (current.getChildAt(i) instanceof Switch) {
                    ATH.setTint(current.getChildAt(i), ThemeStore.accentColor(view.getContext()));
                    return;
                } else if (current.getChildAt(i) instanceof ViewGroup) {
                    queue.addLast((ViewGroup) current.getChildAt(i));
                }
            }
        }
    }

}
 
Example 2
Source File: 00383 Shipping Routes.java    From UVA with GNU General Public License v3.0 6 votes vote down vote up
public static int bfs (HashMap<String,ArrayList<String>> adjList, String src, String dest) {
	if (src.equals(dest)) return 0;
	
	LinkedList<String> queue=new LinkedList<>();
	HashMap<String,Integer> dist=new HashMap<>();
	HashSet<String> visited=new HashSet<>();
	
	queue.add(src);
	visited.add(src);
	dist.put(src,0);
	
	while (!queue.isEmpty()) {
		String curr=queue.removeFirst();
		if (curr.equals(dest)) return dist.get(curr);
		
		for (String neighbour : adjList.get(curr)) if (!dist.containsKey(neighbour)) {
			queue.addLast(neighbour);
			dist.put(neighbour,dist.get(curr)+1);
		}
	}
	return -1;
}
 
Example 3
Source File: Solution4.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public int[] maxSlidingWindow(int[] nums, int k) {
    int len = nums.length;
    if (len == 0) {
        return new int[0];
    }
    int[] res = new int[len - k + 1];
    LinkedList<Integer> queue = new LinkedList<>();
    for (int i = 0; i < len; i++) {
        if (i >= k && queue.getFirst() == i - k) {
            queue.removeFirst();
        }
        while (!queue.isEmpty() && nums[queue.getLast()] <= nums[i]) {
            queue.removeLast();
        }
        queue.add(i);
        if (i >= k - 1) {
            res[i - k + 1] = nums[queue.getFirst()];
        }
    }
    return res;
}
 
Example 4
Source File: JSRInlinerAdapter.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates the new instructions, inlining each instantiation of each
 * subroutine until the code is fully elaborated.
 */
private void emitCode() {
    LinkedList<Instantiation> worklist = new LinkedList<Instantiation>();
    // Create an instantiation of the "root" subroutine, which is just the
    // main routine
    worklist.add(new Instantiation(null, mainSubroutine));

    // Emit instantiations of each subroutine we encounter, including the
    // main subroutine
    InsnList newInstructions = new InsnList();
    List<TryCatchBlockNode> newTryCatchBlocks = new ArrayList<TryCatchBlockNode>();
    List<LocalVariableNode> newLocalVariables = new ArrayList<LocalVariableNode>();
    while (!worklist.isEmpty()) {
        Instantiation inst = worklist.removeFirst();
        emitSubroutine(inst, worklist, newInstructions, newTryCatchBlocks,
                newLocalVariables);
    }
    instructions = newInstructions;
    tryCatchBlocks = newTryCatchBlocks;
    localVariables = newLocalVariables;
}
 
Example 5
Source File: JSRInlinerAdapter.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates the new instructions, inlining each instantiation of each
 * subroutine until the code is fully elaborated.
 */
private void emitCode() {
    LinkedList<Instantiation> worklist = new LinkedList<Instantiation>();
    // Create an instantiation of the "root" subroutine, which is just the
    // main routine
    worklist.add(new Instantiation(null, mainSubroutine));

    // Emit instantiations of each subroutine we encounter, including the
    // main subroutine
    InsnList newInstructions = new InsnList();
    List<TryCatchBlockNode> newTryCatchBlocks = new ArrayList<TryCatchBlockNode>();
    List<LocalVariableNode> newLocalVariables = new ArrayList<LocalVariableNode>();
    while (!worklist.isEmpty()) {
        Instantiation inst = worklist.removeFirst();
        emitSubroutine(inst, worklist, newInstructions, newTryCatchBlocks,
                newLocalVariables);
    }
    instructions = newInstructions;
    tryCatchBlocks = newTryCatchBlocks;
    localVariables = newLocalVariables;
}
 
Example 6
Source File: MyCloudProvider.java    From android-StorageProvider with Apache License 2.0 5 votes vote down vote up
@Override
public Cursor querySearchDocuments(String rootId, String query, String[] projection)
        throws FileNotFoundException {
    Log.v(TAG, "querySearchDocuments");

    // Create a cursor with the requested projection, or the default projection.
    final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection));
    final File parent = getFileForDocId(rootId);

    // This example implementation searches file names for the query and doesn't rank search
    // results, so we can stop as soon as we find a sufficient number of matches.  Other
    // implementations might use other data about files, rather than the file name, to
    // produce a match; it might also require a network call to query a remote server.

    // Iterate through all files in the file structure under the root until we reach the
    // desired number of matches.
    final LinkedList<File> pending = new LinkedList<File>();

    // Start by adding the parent to the list of files to be processed
    pending.add(parent);

    // Do while we still have unexamined files, and fewer than the max search results
    while (!pending.isEmpty() && result.getCount() < MAX_SEARCH_RESULTS) {
        // Take a file from the list of unprocessed files
        final File file = pending.removeFirst();
        if (file.isDirectory()) {
            // If it's a directory, add all its children to the unprocessed list
            Collections.addAll(pending, file.listFiles());
        } else {
            // If it's a file and it matches, add it to the result cursor.
            if (file.getName().toLowerCase().contains(query)) {
                includeFile(result, null, file);
            }
        }
    }
    return result;
}
 
Example 7
Source File: MaximaDifferentiater.java    From Gaalop with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public LinkedList<AssignmentNode> differentiate(LinkedList<AssignmentNode> toDerive, MultivectorComponent variable) {
    try {
        MaximaConnection connection = new ProcessBuilderMaximaConnection(maximaCommand);
        connection.setProgressListeners(new LoggingListenerGroup());
        
        MaximaInput input = new MaximaInput();
        input.add("display2d:false;"); // very important!
        input.add("ratprint:false;"); // very important!
        input.add("keepfloat:true;");
        fillMaximaInput(toDerive, input, variable);
        input.add("quit();"); // very important!

        MaximaOutput output = connection.optimizeWithMaxima(input);

        //connect in and output
        LinkedList<String> connected = new LinkedList<String>();
        MaximaRoutines.groupMaximaInAndOutputs(connected, output);

        connected.removeFirst(); // remove display2d
        connected.removeFirst(); // remove ratsimp
        connected.removeFirst(); // remove keepfloat
        
        LinkedList<AssignmentNode> result = new LinkedList<AssignmentNode>();
        ListIterator<AssignmentNode> listIterator = toDerive.listIterator();
        for (String io : connected) {
            AssignmentNode node = listIterator.next();
            Expression exp = MaximaRoutines.getExpressionFromMaximaOutput(io);
            result.add(new AssignmentNode(node.getGraph(), new MultivectorComponent(node.getVariable().getName(), 0), exp));
        }

        return result; 
    } catch (OptimizationException ex) {
        Logger.getLogger(MaximaDifferentiater.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}
 
Example 8
Source File: LastSameInTree.java    From coding-interviews with MIT License 5 votes vote down vote up
/**
 * 两个链表前面的结点都是相同的,找到最后一个相同的结点就是最低公共祖先
 */
private Node getLastSameNode(LinkedList<Node> path1, LinkedList<Node> path2) {
    Node lastSameNode = null;
    while (!path1.isEmpty() && !path2.isEmpty()) {
        if (path1.peekFirst() == path2.removeFirst()) {
            lastSameNode = path1.removeFirst();
        } else {
            return lastSameNode;
        }
    }
    return lastSameNode;
}
 
Example 9
Source File: Rule.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
/** Creates all rules with length<=minComplexity. */
@Override
public LinkedList<Hypothesis> init(int minComplexity) {
	LinkedList<Hypothesis> border = new LinkedList<Hypothesis>();
	LinkedList<Hypothesis> result = new LinkedList<Hypothesis>();

	// Add all hypothesis of lenght 1 to border.
	for (int attributeIndex = 0; attributeIndex < allLiterals.length; attributeIndex++) {
		for (int valueIndex = 0; valueIndex < allLiterals[attributeIndex].length; valueIndex++) {
			border.addLast(new Rule(allLiterals[attributeIndex][valueIndex], POSITIVE_CLASS)); // Create
																								// h->Y+
																								// first.
		}
	}

	while (!border.isEmpty()) {
		Rule rule = (Rule) border.removeFirst();
		result.addLast(rule); // Add h->Y+ to result.
		if (createAllHypothesis) {
			result.addLast(new Rule(rule.getLiterals(), NEGATIVE_CLASS)); // Add h->Y- to
																			// result.
		}

		// No need to refine anymore if rule length already is equal to minComplexity.
		if (rule.getComplexity() < minComplexity) {
			border.addAll(rule.refine()); // Add h->Y+ only
		}
	}
	return result;
}
 
Example 10
Source File: NativeDebug.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Expands the event queue capacity, or truncates if capacity is lower than
 * current capacity. Then only the newest entries are kept
 * @param self self reference
 * @param newCapacity new capacity
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static void expandEventQueueCapacity(final Object self, final Object newCapacity) {
    final LinkedList<RuntimeEvent<?>> q = getEventQueue(self);
    final int nc = JSType.toInt32(newCapacity);
    while (q.size() > nc) {
        q.removeFirst();
    }
    setEventQueueCapacity(self, nc);
}
 
Example 11
Source File: StandardObjectSizeCalculator.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public long sizeOf(final Object obj) {


   final Map<Object, Object> visited = new IdentityHashMap<Object, Object>(11);

   final LinkedList<Object> stack = new LinkedList<Object>();


   long result = calculate(obj, visited, stack);
   while (!stack.isEmpty()) {

      final Object pop = stack.removeFirst();
      result += calculate(pop, visited, stack);
   }
   visited.clear();
   return result;
}
 
Example 12
Source File: Helper.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
public static int deepHashCode(Object obj) {
	Set visited = new HashSet();
	LinkedList<Object> stack = new LinkedList<Object>();
	stack.addFirst(obj);
	int hash = 0;

	while (!stack.isEmpty()) {
		obj = stack.removeFirst();
		if (obj == null || visited.contains(obj)) {
			continue;
		}

		visited.add(obj);

		if (obj.getClass().isArray()) {
			int len = Array.getLength(obj);
			for (int i = 0; i < len; i++) {
				stack.addFirst(Array.get(obj, i));
			}
			continue;
		}

		if (obj instanceof Collection) {
			stack.addAll(0, (Collection) obj);
			continue;
		}

		if (obj instanceof Map) {
			stack.addAll(0, ((Map) obj).keySet());
			stack.addAll(0, ((Map) obj).values());
			continue;
		}

		if (hasCustomHashCode(obj.getClass())) {
			hash += obj.hashCode();
			continue;
		}

		Collection<Field> fields = getDeepDeclaredFields(obj.getClass());
		for (Field field : fields) {
			try {
				stack.addFirst(field.get(obj));
			} catch (Exception ignored) {
			}
		}
	}
	return hash;
}
 
Example 13
Source File: AreaTree.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
/** Find the nearest parent with a non-null, non-empty Area, and interpolate from {@code nd} to it.
 *
 * @param nd The node to start interpolating from, towards its nearest parent with an area.
 * @param node_centric If true, consider areas relative to the node coordinates. If false, relative to the overall AreaTree.
 *
 * @throws Exception */
public boolean interpolateTowardsParent(final Node<Area> nd, final boolean node_centric, final boolean always_use_distance_map) throws Exception {
	if (null == nd || null == nd.parent) return false;
	Area first = nd.getData();
	if (null == first || first.isEmpty()) {
		return false;
	}
	final LinkedList<Node<Area>> chain = new LinkedList<Node<Area>>();
	Node<Area> p = nd.parent;
	while (null != p && (null == p.getData() || p.getData().isEmpty())) {
		chain.add(p);
		p = p.parent;
	}
	if (p == nd.parent) {
		// Nothing to interpolate
		return false;
	}

	Area last = p.getData();

	int minx = 0, miny = 0;
	if (node_centric) {
		// Make areas relative to the nodes:
		first = first.createTransformedArea(new AffineTransform(1, 0, 0, 1, -nd.x, -nd.y));
		last = last.createTransformedArea(new AffineTransform(1, 0, 0, 1, -p.x, -p.y));
		// Remove translations
		final Rectangle bfirst = first.getBounds();
		final Rectangle blast = last.getBounds();
		minx = Math.min(bfirst.x, blast.x);
		miny = Math.min(bfirst.y, blast.y);
		final AffineTransform rmtrans = new AffineTransform(1, 0, 0, 1, -minx, -miny);
		first = first.createTransformedArea(rmtrans);
		last = last.createTransformedArea(rmtrans);
	}
	// Interpolate
	final Area[] as;
	if (!always_use_distance_map && first.isSingular() && last.isSingular()) {
		as = AreaUtils.singularInterpolation(first, last, chain.size());
	} else {
		as = AreaUtils.manyToManyInterpolation(first, last, chain.size());
	}
	// Assign each area
	for (final Area interpolated : as) {
		final Node<Area> target = chain.removeFirst();
		if (node_centric) {
			interpolated.transform(new AffineTransform(1, 0, 0, 1, minx + target.x, miny + target.y));
		}
		target.setData(interpolated);
	}

	return true;
}
 
Example 14
Source File: SST.java    From symbolicautomata with Apache License 2.0 4 votes vote down vote up
/**
 * Computes the pre-image of sst on the set outputNonMin
 * 
 * @throws TimeoutException
 */
public static <A, B, C> SFA<A, C> preImage(SST<A, B, C> sstWithEps, SFA<A, C> outputNonMin,
		BooleanAlgebraSubst<A, B, C> ba) throws TimeoutException {
	SFA<A, C> output = outputNonMin.minimize(ba);
	SST<A, B, C> sst = sstWithEps.removeEpsilonMoves(ba);

	Collection<SFAMove<A, C>> transitions = new ArrayList<SFAMove<A, C>>();
	Collection<Integer> finalStates = new HashSet<Integer>();
	Integer initialState = 0;

	// A state is a pair (q, f) where q is a state of the sst and f: X -> QO
	// -> QO is a function
	// mapping each variable x to a function from QO to QO (the
	// summarization)
	Map<Pair<Integer, HashMap<Integer, HashMap<Integer, Integer>>>, Integer> reached = new HashMap<Pair<Integer, HashMap<Integer, HashMap<Integer, Integer>>>, Integer>();
	LinkedList<Pair<Integer, HashMap<Integer, HashMap<Integer, Integer>>>> toVisit = new LinkedList<Pair<Integer, HashMap<Integer, HashMap<Integer, Integer>>>>();

	// The initial state is the identity for every variable
	HashMap<Integer, Integer> identityStateMap = new HashMap<Integer, Integer>();
	HashMap<Integer, HashMap<Integer, Integer>> identityMap = new HashMap<Integer, HashMap<Integer, Integer>>();
	for (int stateId : output.getStates())
		identityStateMap.put(stateId, stateId);
	for (int varId = 0; varId < sst.variableCount; varId++)
		identityMap.put(varId, identityStateMap);

	Pair<Integer, HashMap<Integer, HashMap<Integer, Integer>>> initialStatePair = new Pair<Integer, HashMap<Integer, HashMap<Integer, Integer>>>(
			sst.initialState, identityMap);
	reached.put(initialStatePair, 0);
	toVisit.add(initialStatePair);

	// do a DFS and look for reachable states
	while (!toVisit.isEmpty()) {
		Pair<Integer, HashMap<Integer, HashMap<Integer, Integer>>> currState = toVisit.removeFirst();
		int currStateId = reached.get(currState);

		int sstState = currState.first;
		HashMap<Integer, HashMap<Integer, Integer>> currFun = currState.second;

		// set final states to those for which the output func summarized on
		// initial state gives a final state of O
		if (sst.isFinalState(sstState)) {
			Integer fromqoOnOutputFunction = sst.outputFunction.get(sstState).getInitStateSummary(currFun, output,
					ba);
			if (fromqoOnOutputFunction != null && output.getFinalStates().contains(fromqoOnOutputFunction))
				finalStates.add(currStateId);
		}

		// For each move of the sst compute the next state
		for (SSTInputMove<A, B, C> t : sst.getInputMovesFrom(sstState)) {

			Collection<Pair<HashMap<Integer, HashMap<Integer, Integer>>, A>> nextFuns = t.variableUpdate
					.getNextSummary(currFun, t.guard, output, ba);
			for (Pair<HashMap<Integer, HashMap<Integer, Integer>>, A> pair : nextFuns) {

				Pair<Integer, HashMap<Integer, HashMap<Integer, Integer>>> nextState = new Pair<Integer, HashMap<Integer, HashMap<Integer, Integer>>>(
						t.to, pair.first);

				int nextStateId = getStateId(nextState, reached, toVisit);

				transitions.add(new SFAInputMove<A, C>(currStateId, nextStateId, pair.second));
			}
		}

	}

	return SFA.MkSFA(transitions, initialState, finalStates, ba);
}
 
Example 15
Source File: SimplePropositionTypeService.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
 * Translates the parameters on the given proposition definition to create an expression for evaluation.
 * The proposition parameters are defined in a reverse-polish notation so a stack is used for
 * evaluation purposes.
 * 
 * @param propositionDefinition the proposition definition to translate
 * 
 * @return the translated expression for the given proposition, this
 * expression, when evaluated, will return a Boolean.
 */
protected Expression<Boolean> translateToExpression(PropositionDefinition propositionDefinition) {
	LinkedList<Expression<? extends Object>> stack = new LinkedList<Expression<? extends Object>>();
	for (PropositionParameter parameter : propositionDefinition.getParameters()) {
		PropositionParameterType parameterType = PropositionParameterType.fromCode(parameter.getParameterType());
		if (parameterType == PropositionParameterType.CONSTANT) {
			// TODO - need some way to define data type on the prop parameter as well?  Not all constants will actually be String values!!!
			stack.addFirst(new ConstantExpression<String>(parameter.getValue()));
		} else if (parameterType == PropositionParameterType.FUNCTION) {
			String functionId = parameter.getValue();
			FunctionDefinition functionDefinition = functionRepositoryService.getFunction(functionId);
			if (functionDefinition == null) {
				throw new RepositoryDataException("Unable to locate function with the given id: " + functionId);
			}
			FunctionTypeService functionTypeService = typeResolver.getFunctionTypeService(functionDefinition);
			Function function = functionTypeService.loadFunction(functionDefinition);
			// TODO throw an exception if function is null?
			List<FunctionParameterDefinition> parameters = functionDefinition.getParameters();
			if (stack.size() < parameters.size()) {
				throw new RepositoryDataException("Failed to initialize custom function '" + functionDefinition.getNamespace() + " " + functionDefinition.getName() +
						"'.  There were only " + stack.size() + " values on the stack but function requires at least " + parameters.size());
			}
			List<Expression<? extends Object>> arguments = new ArrayList<Expression<? extends Object>>();
			// work backward through the list to match params to the stack
			for (int index = parameters.size() - 1; index >= 0; index--) {
				FunctionParameterDefinition parameterDefinition = parameters.get(index);
				// TODO need to check types here? expression object probably needs a getType on it so that we can confirm that the types will be compatible?
                   parameterDefinition.getParameterType();
				Expression<? extends Object> argument = stack.removeFirst();
				arguments.add(argument);
			}

               String[] parameterTypes = getFunctionParameterTypes(functionDefinition);
			stack.addFirst(new FunctionExpression(function, parameterTypes, arguments, getComparisonOperatorService()));

		} else if (parameterType == PropositionParameterType.OPERATOR) {
			ComparisonOperator operator = ComparisonOperator.fromCode(parameter.getValue());
			if (stack.size() < 2) {
				throw new RepositoryDataException("Failed to initialize expression for comparison operator " +
                           operator + " because a sufficient number of arguments was not available on the stack.  "
                           + "Current contents of stack: " + stack.toString());
			}
			Expression<? extends Object> rhs = stack.removeFirst();
			Expression<? extends Object> lhs = stack.removeFirst();
			stack.addFirst(new BinaryOperatorExpression(operator, lhs, rhs));
		} else if (parameterType == PropositionParameterType.TERM) {
			String termId = parameter.getValue();

			TermDefinition termDefinition = getTermRepositoryService().getTerm(termId);
			if (termDefinition == null) { throw new RepositoryDataException("unable to load term with id " + termId);}
			Term term = translateTermDefinition(termDefinition);
			
			stack.addFirst(new TermExpression(term));
		}
	}
	if (stack.size() != 1) {
		throw new RepositoryDataException("Final contents of expression stack are incorrect, there should only be one entry but was " + stack.size() +".  Current contents of stack: " + stack.toString());
	}
	return new BooleanValidatingExpression(stack.removeFirst());
}
 
Example 16
Source File: VarTypeProcessor.java    From JByteMod-Beta with GNU General Public License v2.0 4 votes vote down vote up
private void setInitVars(RootStatement root) {
  boolean thisVar = !method.hasModifier(CodeConstants.ACC_STATIC);

  MethodDescriptor md = methodDescriptor;

  if (thisVar) {
    StructClass cl = (StructClass) DecompilerContext.getProperty(DecompilerContext.CURRENT_CLASS);
    VarType clType = new VarType(CodeConstants.TYPE_OBJECT, 0, cl.qualifiedName);
    mapExprentMinTypes.put(new VarVersionPair(0, 1), clType);
    mapExprentMaxTypes.put(new VarVersionPair(0, 1), clType);
  }

  int varIndex = 0;
  for (int i = 0; i < md.params.length; i++) {
    mapExprentMinTypes.put(new VarVersionPair(varIndex + (thisVar ? 1 : 0), 1), md.params[i]);
    mapExprentMaxTypes.put(new VarVersionPair(varIndex + (thisVar ? 1 : 0), 1), md.params[i]);
    varIndex += md.params[i].stackSize;
  }

  // catch variables
  LinkedList<Statement> stack = new LinkedList<>();
  stack.add(root);

  while (!stack.isEmpty()) {
    Statement stat = stack.removeFirst();

    List<VarExprent> lstVars = null;
    if (stat.type == Statement.TYPE_CATCHALL) {
      lstVars = ((CatchAllStatement) stat).getVars();
    } else if (stat.type == Statement.TYPE_TRYCATCH) {
      lstVars = ((CatchStatement) stat).getVars();
    }

    if (lstVars != null) {
      for (VarExprent var : lstVars) {
        mapExprentMinTypes.put(new VarVersionPair(var.getIndex(), 1), var.getVarType());
        mapExprentMaxTypes.put(new VarVersionPair(var.getIndex(), 1), var.getVarType());
      }
    }

    stack.addAll(stat.getStats());
  }
}
 
Example 17
Source File: UploadSlotManager.java    From BiglyBT with GNU General Public License v2.0 4 votes vote down vote up
private UploadSession getNextBestSession( LinkedList best ) {
	count++;
	System.out.print( "getNextBestSession [" +count+"] best.size=" +best.size()+ "  " );

	if( !best.isEmpty() ) {
		UploadSession session = (UploadSession)best.removeFirst();   //get next

		if( !isAlreadySlotted( session ) ) {   //found an unslotted session

			System.out.println( "OK found session [" +session.getStatsTrace()+ "]" );

			return session;
		}

		System.out.println( "FAIL already-slotted session [" +session.getStatsTrace()+ "]" );

		return getNextBestSession( best );			//oops, already been slotted, try again
	}

	return null;
}
 
Example 18
Source File: 00599 The Forrest for the Trees.java    From UVA with GNU General Public License v3.0 4 votes vote down vote up
public static void main (String [] args) throws Exception {
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	int testCaseCount=Integer.parseInt(br.readLine());
	for (int testCase=0;testCase<testCaseCount;testCase++) {
		boolean [][] edges=new boolean [26][26];
		String s;
		while ((s=br.readLine()).charAt(0)!='*') {
			edges[s.charAt(1)-'A'][s.charAt(3)-'A']=true;
			edges[s.charAt(3)-'A'][s.charAt(1)-'A']=true;
		}
		
		boolean [] nodeExists=new boolean [26];
		StringTokenizer st=new StringTokenizer(br.readLine(), ",");
		while (st.hasMoreTokens()) nodeExists[st.nextToken().charAt(0)-'A']=true;
		
		int acronsCount=0, treeCount=0;
		boolean [] visited=new boolean[26];
		for (int i=0;i<26;i++) if (nodeExists[i] && !visited[i]) {
			int edgesCount=0;
			for (int e=0;e<26;e++) if (edges[i][e]) edgesCount++;
			if (edgesCount==0) {
				visited[i]=true;
				acronsCount++;
			} else {
				boolean tree=true;
				LinkedList<Integer> queue=new LinkedList<>();
				queue.add(i);
				
				boolean [][] edgeVisited=new boolean[26][26];
				while (queue.size()>0) {
					int currI=queue.removeFirst();
					if (visited[currI]) {
						tree=false;
						break;
					} else {
						visited[currI]=true;
						for (int e=0;e<26;e++) if (edges[currI][e] && !edgeVisited[currI][e] && !edgeVisited[e][currI]) {
							queue.add(e);
							edgeVisited[currI][e]=true;
							edgeVisited[e][currI]=true;
						}
					}
				}
				if (tree) treeCount++;
			}
		}
		
		StringBuilder sb=new StringBuilder();
		sb.append("There are ");
		sb.append(treeCount);
		sb.append(" tree(s) and ");
		sb.append(acronsCount);
		sb.append(" acorn(s).");
		System.out.println(sb.toString());
	}
	
}
 
Example 19
Source File: Server.java    From hadoop-gpu with Apache License 2.0 4 votes vote down vote up
private boolean processResponse(LinkedList<Call> responseQueue,
                                boolean inHandler) throws IOException {
  boolean error = true;
  boolean done = false;       // there is more data for this channel.
  int numElements = 0;
  Call call = null;
  try {
    synchronized (responseQueue) {
      //
      // If there are no items for this channel, then we are done
      //
      numElements = responseQueue.size();
      if (numElements == 0) {
        error = false;
        return true;              // no more data for this channel.
      }
      //
      // Extract the first call
      //
      call = responseQueue.removeFirst();
      SocketChannel channel = call.connection.channel;
      if (LOG.isDebugEnabled()) {
        LOG.debug(getName() + ": responding to #" + call.id + " from " +
                  call.connection);
      }
      //
      // Send as much data as we can in the non-blocking fashion
      //
      int numBytes = channelWrite(channel, call.response);
      if (numBytes < 0) {
        return true;
      }
      if (!call.response.hasRemaining()) {
        call.connection.decRpcCount();
        if (numElements == 1) {    // last call fully processes.
          done = true;             // no more data for this channel.
        } else {
          done = false;            // more calls pending to be sent.
        }
        if (LOG.isDebugEnabled()) {
          LOG.debug(getName() + ": responding to #" + call.id + " from " +
                    call.connection + " Wrote " + numBytes + " bytes.");
        }
      } else {
        //
        // If we were unable to write the entire response out, then 
        // insert in Selector queue. 
        //
        call.connection.responseQueue.addFirst(call);
        
        if (inHandler) {
          // set the serve time when the response has to be sent later
          call.timestamp = System.currentTimeMillis();
          
          incPending();
          try {
            // Wakeup the thread blocked on select, only then can the call 
            // to channel.register() complete.
            writeSelector.wakeup();
            channel.register(writeSelector, SelectionKey.OP_WRITE, call);
          } catch (ClosedChannelException e) {
            //Its ok. channel might be closed else where.
            done = true;
          } finally {
            decPending();
          }
        }
        if (LOG.isDebugEnabled()) {
          LOG.debug(getName() + ": responding to #" + call.id + " from " +
                    call.connection + " Wrote partial " + numBytes + 
                    " bytes.");
        }
      }
      error = false;              // everything went off well
    }
  } finally {
    if (error && call != null) {
      LOG.warn(getName()+", call " + call + ": output error");
      done = true;               // error. no more data for this channel.
      closeConnection(call.connection);
    }
  }
  return done;
}
 
Example 20
Source File: FastExtendedPostdominanceHelper.java    From javaide with GNU General Public License v3.0 2 votes vote down vote up
private void filterOnDominance(DominatorTreeExceptionFilter filter) {

        DominatorEngine engine = filter.getDomEngine();

        for (Integer head : new HashSet<>(mapExtPostdominators.keySet())) {

            FastFixedSet<Integer> setPostdoms = mapExtPostdominators.get(head);

            LinkedList<Statement> stack = new LinkedList<>();
            LinkedList<FastFixedSet<Integer>> stackPath = new LinkedList<>();

            stack.add(statement.getStats().getWithKey(head));
            stackPath.add(factory.spawnEmptySet());

            Set<Statement> setVisited = new HashSet<>();

            setVisited.add(stack.getFirst());

            while (!stack.isEmpty()) {

                Statement stat = stack.removeFirst();
                FastFixedSet<Integer> path = stackPath.removeFirst();

                if (setPostdoms.contains(stat.id)) {
                    path.add(stat.id);
                }

                if (path.contains(setPostdoms)) {
                    continue;
                }

                if (!engine.isDominator(stat.id, head)) {
                    setPostdoms.complement(path);
                    continue;
                }

                for (StatEdge edge : stat.getSuccessorEdges(StatEdge.TYPE_REGULAR)) {

                    Statement edge_destination = edge.getDestination();

                    if (!setVisited.contains(edge_destination)) {

                        stack.add(edge_destination);
                        stackPath.add(path.getCopy());

                        setVisited.add(edge_destination);
                    }
                }
            }

            if (setPostdoms.isEmpty()) {
                mapExtPostdominators.remove(head);
            }
        }
    }