use of java.util.PriorityQueue in project PneumaticCraft by MineMaarten.
the class LogisticsManager method getTasks.
public PriorityQueue<LogisticsTask> getTasks(Object holdingStack) {
ItemStack item = holdingStack instanceof ItemStack ? (ItemStack) holdingStack : null;
FluidStack fluid = holdingStack instanceof FluidStack ? (FluidStack) holdingStack : null;
PriorityQueue<LogisticsTask> tasks = new PriorityQueue<LogisticsTask>();
for (int priority = logistics.length - 1; priority >= 0; priority--) {
for (SemiBlockLogistics requester : logistics[priority]) {
for (int i = 0; i < priority; i++) {
for (SemiBlockLogistics provider : logistics[i]) {
if (provider.shouldProvideTo(priority)) {
if (item != null) {
int requestedAmount = getRequestedAmount(requester, item);
if (requestedAmount > 0) {
ItemStack stack = item.copy();
stack.stackSize = requestedAmount;
tasks.add(new LogisticsTask(provider, requester, stack));
return tasks;
}
} else if (fluid != null) {
int requestedAmount = getRequestedAmount(requester, fluid);
if (requestedAmount > 0) {
fluid = fluid.copy();
fluid.amount = requestedAmount;
tasks.add(new LogisticsTask(provider, requester, new FluidStackWrapper(fluid)));
return tasks;
}
} else {
tryProvide(provider, requester, tasks);
}
}
}
}
}
}
return tasks;
}
use of java.util.PriorityQueue in project Android-Developers-Samples by johnjohndoe.
the class MyCloudProvider method queryRecentDocuments.
// END_INCLUDE(query_roots)
// BEGIN_INCLUDE(query_recent_documents)
@Override
public Cursor queryRecentDocuments(String rootId, String[] projection) throws FileNotFoundException {
Log.v(TAG, "queryRecentDocuments");
// This example implementation walks a local file structure to find the most recently
// modified files. Other implementations might include making a network call to query a
// server.
// Create a cursor with the requested projection, or the default projection.
final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection));
final File parent = getFileForDocId(rootId);
// Create a queue to store the most recent documents, which orders by last modified.
PriorityQueue<File> lastModifiedFiles = new PriorityQueue<File>(5, new Comparator<File>() {
public int compare(File i, File j) {
return Long.compare(i.lastModified(), j.lastModified());
}
});
// Iterate through all files and directories in the file structure under the root. If
// the file is more recent than the least recently modified, add it to the queue,
// limiting the number of results.
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
while (!pending.isEmpty()) {
// 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, add it to the ordered queue.
lastModifiedFiles.add(file);
}
}
// Add the most recent files to the cursor, not exceeding the max number of results.
for (int i = 0; i < Math.min(MAX_LAST_MODIFIED + 1, lastModifiedFiles.size()); i++) {
final File file = lastModifiedFiles.remove();
includeFile(result, null, file);
}
return result;
}
use of java.util.PriorityQueue in project pinpoint by naver.
the class AgentEventServiceImpl method createAgentEvents.
private List<AgentEvent> createAgentEvents(List<AgentEventBo> agentEventBos, boolean includeEventMessage) {
if (CollectionUtils.isEmpty(agentEventBos)) {
return Collections.emptyList();
}
List<AgentEvent> agentEvents = new ArrayList<>(agentEventBos.size());
PriorityQueue<DurationalAgentEvent> durationalAgentEvents = new PriorityQueue<>(agentEventBos.size(), AgentEvent.EVENT_TIMESTAMP_ASC_COMPARATOR);
for (AgentEventBo agentEventBo : agentEventBos) {
if (agentEventBo.getEventType().isCategorizedAs(AgentEventTypeCategory.DURATIONAL)) {
durationalAgentEvents.add(createDurationalAgentEvent(agentEventBo, includeEventMessage));
} else {
agentEvents.add(createAgentEvent(agentEventBo, includeEventMessage));
}
}
long durationStartTimestamp = DurationalAgentEvent.UNKNOWN_TIMESTAMP;
while (!durationalAgentEvents.isEmpty()) {
DurationalAgentEvent currentEvent = durationalAgentEvents.remove();
if (durationStartTimestamp == DurationalAgentEvent.UNKNOWN_TIMESTAMP) {
durationStartTimestamp = currentEvent.getEventTimestamp();
}
currentEvent.setDurationStartTimestamp(durationStartTimestamp);
DurationalAgentEvent nextEvent = durationalAgentEvents.peek();
if (nextEvent != null) {
long nextEventTimestamp = nextEvent.getEventTimestamp();
currentEvent.setDurationEndTimestamp(nextEventTimestamp);
durationStartTimestamp = nextEventTimestamp;
}
agentEvents.add(currentEvent);
}
return agentEvents;
}
use of java.util.PriorityQueue in project sessdb by ppdai.
the class Level0Merger method mergeSort.
public static void mergeSort(LevelQueue source, LevelQueue target, int ways, String dir, short shard) throws IOException, ClassNotFoundException {
List<HashMapTable> tables = new ArrayList<HashMapTable>(ways);
source.getReadLock().lock();
try {
Iterator<AbstractMapTable> iter = source.descendingIterator();
for (int i = 0; i < ways; i++) {
tables.add((HashMapTable) iter.next());
}
} finally {
source.getReadLock().unlock();
}
int expectedInsertions = 0;
for (HashMapTable table : tables) {
expectedInsertions += table.getRealSize();
}
// target table
MMFMapTable sortedMapTable = new MMFMapTable(dir, shard, SDB.LEVEL1, System.nanoTime(), expectedInsertions, ways);
PriorityQueue<QueueElement> pq = new PriorityQueue<QueueElement>();
// build initial heap
for (HashMapTable table : tables) {
QueueElement qe = new QueueElement();
final HashMapTable hmTable = table;
qe.hashMapTable = hmTable;
List<Map.Entry<ByteArrayWrapper, InMemIndex>> list = new ArrayList<Map.Entry<ByteArrayWrapper, InMemIndex>>(qe.hashMapTable.getEntrySet());
Collections.sort(list, new Comparator<Map.Entry<ByteArrayWrapper, InMemIndex>>() {
@Override
public int compare(Entry<ByteArrayWrapper, InMemIndex> o1, Entry<ByteArrayWrapper, InMemIndex> o2) {
IMapEntry mapEntry1 = hmTable.getMapEntry(o1.getValue().getIndex());
IMapEntry mapEntry2 = hmTable.getMapEntry(o2.getValue().getIndex());
try {
int hash1 = mapEntry1.getKeyHash();
int hash2 = mapEntry2.getKeyHash();
if (hash1 < hash2)
return -1;
else if (hash1 > hash2)
return 1;
else {
return o1.getKey().compareTo(o2.getKey());
}
} catch (IOException e) {
throw new RuntimeException("Fail to get hash code in map entry", e);
}
}
});
qe.iterator = list.iterator();
if (qe.iterator.hasNext()) {
Map.Entry<ByteArrayWrapper, InMemIndex> me = qe.iterator.next();
qe.key = me.getKey().getData();
qe.inMemIndex = me.getValue();
IMapEntry mapEntry = table.getMapEntry(qe.inMemIndex.getIndex());
qe.keyHash = mapEntry.getKeyHash();
pq.add(qe);
}
}
// merge sort
while (pq.size() > 0) {
QueueElement qe1 = pq.poll();
// remove old/stale entries
while (pq.peek() != null && qe1.keyHash == pq.peek().keyHash && BytesUtil.compare(qe1.key, pq.peek().key) == 0) {
QueueElement qe2 = pq.poll();
if (qe2.iterator.hasNext()) {
Map.Entry<ByteArrayWrapper, InMemIndex> me = qe2.iterator.next();
qe2.key = me.getKey().getData();
qe2.inMemIndex = me.getValue();
IMapEntry mapEntry = qe2.hashMapTable.getMapEntry(qe2.inMemIndex.getIndex());
qe2.keyHash = mapEntry.getKeyHash();
pq.add(qe2);
}
}
IMapEntry mapEntry = qe1.hashMapTable.getMapEntry(qe1.inMemIndex.getIndex());
byte[] value = mapEntry.getValue();
// disk space optimization
if (mapEntry.isDeleted() || mapEntry.isExpired()) {
value = new byte[] { 0 };
}
sortedMapTable.appendNew(mapEntry.getKey(), mapEntry.getKeyHash(), value, mapEntry.getTimeToLive(), mapEntry.getCreatedTime(), mapEntry.isDeleted(), mapEntry.isCompressed());
if (qe1.iterator.hasNext()) {
Map.Entry<ByteArrayWrapper, InMemIndex> me = qe1.iterator.next();
qe1.key = me.getKey().getData();
qe1.inMemIndex = me.getValue();
IMapEntry mEntry = qe1.hashMapTable.getMapEntry(qe1.inMemIndex.getIndex());
qe1.keyHash = mEntry.getKeyHash();
pq.add(qe1);
}
}
// persist metadata
sortedMapTable.reMap();
sortedMapTable.saveMetadata();
// dump to level 1
source.getWriteLock().lock();
target.getWriteLock().lock();
try {
for (int i = 0; i < ways; i++) {
source.removeLast();
}
for (HashMapTable table : tables) {
table.markUsable(false);
}
sortedMapTable.markUsable(true);
target.addFirst(sortedMapTable);
} finally {
target.getWriteLock().unlock();
source.getWriteLock().unlock();
}
for (HashMapTable table : tables) {
table.close();
table.delete();
}
}
use of java.util.PriorityQueue in project Cloud9 by lintool.
the class SequentialPersonalizedPageRank method main.
@SuppressWarnings({ "static-access" })
public static void main(String[] args) throws IOException {
Options options = new Options();
options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));
options.addOption(OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP));
options.addOption(OptionBuilder.withArgName("node").hasArg().withDescription("source node (i.e., destination of the random jump)").create(SOURCE));
CommandLine cmdline = null;
CommandLineParser parser = new GnuParser();
try {
cmdline = parser.parse(options, args);
} catch (ParseException exp) {
System.err.println("Error parsing command line: " + exp.getMessage());
System.exit(-1);
}
if (!cmdline.hasOption(INPUT) || !cmdline.hasOption(SOURCE)) {
System.out.println("args: " + Arrays.toString(args));
HelpFormatter formatter = new HelpFormatter();
formatter.setWidth(120);
formatter.printHelp(SequentialPersonalizedPageRank.class.getName(), options);
ToolRunner.printGenericCommandUsage(System.out);
System.exit(-1);
}
String infile = cmdline.getOptionValue(INPUT);
final String source = cmdline.getOptionValue(SOURCE);
float alpha = cmdline.hasOption(JUMP) ? Float.parseFloat(cmdline.getOptionValue(JUMP)) : 0.15f;
int edgeCnt = 0;
DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>();
BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile)));
String line;
while ((line = data.readLine()) != null) {
line.trim();
String[] arr = line.split("\\t");
for (int i = 1; i < arr.length; i++) {
graph.addEdge(new Integer(edgeCnt++), arr[0], arr[i]);
}
}
data.close();
if (!graph.containsVertex(source)) {
System.err.println("Error: source node not found in the graph!");
System.exit(-1);
}
WeakComponentClusterer<String, Integer> clusterer = new WeakComponentClusterer<String, Integer>();
Set<Set<String>> components = clusterer.transform(graph);
int numComponents = components.size();
System.out.println("Number of components: " + numComponents);
System.out.println("Number of edges: " + graph.getEdgeCount());
System.out.println("Number of nodes: " + graph.getVertexCount());
System.out.println("Random jump factor: " + alpha);
// Compute personalized PageRank.
PageRankWithPriors<String, Integer> ranker = new PageRankWithPriors<String, Integer>(graph, new Transformer<String, Double>() {
@Override
public Double transform(String vertex) {
return vertex.equals(source) ? 1.0 : 0;
}
}, alpha);
ranker.evaluate();
// Use priority queue to sort vertices by PageRank values.
PriorityQueue<Ranking<String>> q = new PriorityQueue<Ranking<String>>();
int i = 0;
for (String pmid : graph.getVertices()) {
q.add(new Ranking<String>(i++, ranker.getVertexScore(pmid), pmid));
}
// Print PageRank values.
System.out.println("\nPageRank of nodes, in descending order:");
Ranking<String> r = null;
while ((r = q.poll()) != null) {
System.out.println(r.rankScore + "\t" + r.getRanked());
}
}
Aggregations