gnu.trove.set.hash.TLongHashSet Java Examples

The following examples show how to use gnu.trove.set.hash.TLongHashSet. 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: FallingBlocksMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Make any unsupported blocks fall that are disturbed for the current tick
 */
private void fallCheck() {
    this.visitsWorstTick = Math.max(this.visitsWorstTick, this.visitsThisTick);
    this.visitsThisTick = 0;

    World world = this.getMatch().getWorld();
    TLongObjectMap<ParticipantState> blockDisturbers = this.blockDisturbersByTick.remove(this.getMatch().getClock().now().tick);
    if(blockDisturbers == null) return;

    TLongSet supported = new TLongHashSet();
    TLongSet unsupported = new TLongHashSet();
    TLongObjectMap<ParticipantState> fallsByBreaker = new TLongObjectHashMap<>();

    try {
        while(!blockDisturbers.isEmpty()) {
            long pos = blockDisturbers.keySet().iterator().next();
            ParticipantState breaker = blockDisturbers.remove(pos);

            // Search down for the first block that can actually fall
            for(;;) {
                long below = neighborPos(pos, BlockFace.DOWN);
                if(!Materials.isColliding(blockAt(world, below).getType())) break;
                blockDisturbers.remove(pos); // Remove all the blocks we find along the way
                pos = below;
            }

            // Check if the block needs to fall, if it isn't already falling
            if(!fallsByBreaker.containsKey(pos) && !this.isSupported(pos, supported, unsupported)) {
                fallsByBreaker.put(pos, breaker);
            }
        }
    } catch(MaxSearchVisitsExceeded ex) {
        this.logError(ex);
    }

    for(TLongObjectIterator<ParticipantState> iter = fallsByBreaker.iterator(); iter.hasNext();) {
        iter.advance();
        this.fall(iter.key(), iter.value());
    }
}
 
Example #2
Source File: FallingBlocksMatchModule.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Return the number of unsupported blocks connected to any blocks neighboring the given location,
 * which is assumed to contain an air block. The search may bail out early when the count is
 * greater or equal to the given limit, though this cannot be guaranteed.
 */
private int countUnsupportedNeighbors(long pos, int limit) {
  TLongSet supported = new TLongHashSet();
  TLongSet unsupported = new TLongHashSet();

  try {
    for (BlockFace face : NEIGHBORS) {
      if (!this.isSupported(neighborPos(pos, face), supported, unsupported)) {
        if (unsupported.size() >= limit) break;
      }
    }
  } catch (MaxSearchVisitsExceeded ex) {
    this.logError(ex);
  }

  return unsupported.size();
}
 
Example #3
Source File: DenseArrayOfLongs.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
@Override
public final Array<Long> distinct(int limit) {
    final int capacity = limit < Integer.MAX_VALUE ? limit : 100;
    final TLongSet set = new TLongHashSet(capacity);
    final ArrayBuilder<Long> builder = ArrayBuilder.of(capacity, Long.class);
    for (int i=0; i<length(); ++i) {
        final long value = getLong(i);
        if (set.add(value)) {
            builder.addLong(value);
            if (set.size() >= limit) {
                break;
            }
        }
    }
    return builder.toArray();
}
 
Example #4
Source File: SparseArrayOfLongs.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
@Override
public final Array<Long> distinct(int limit) {
    final int capacity = limit < Integer.MAX_VALUE ? limit : 100;
    final TLongSet set = new TLongHashSet(capacity);
    final ArrayBuilder<Long> builder = ArrayBuilder.of(capacity, Long.class);
    for (int i=0; i<length(); ++i) {
        final long value = getLong(i);
        if (set.add(value)) {
            builder.addLong(value);
            if (set.size() >= limit) {
                break;
            }
        }
    }
    return builder.toArray();
}
 
Example #5
Source File: DenseArrayWithLongCoding.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
@Override
public Array<T> distinct(int limit) {
    final int capacity = limit < Integer.MAX_VALUE ? limit : 100;
    final TLongSet set = new TLongHashSet(capacity);
    final ArrayBuilder<T> builder = ArrayBuilder.of(capacity, type());
    for (int i=0; i<length(); ++i) {
        final long code = getLong(i);
        if (set.add(code)) {
            final T value = getValue(i);
            builder.add(value);
            if (set.size() >= limit) {
                break;
            }
        }
    }
    return builder.toArray();
}
 
Example #6
Source File: CommitCanvasN5.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
private static TLongHashSet generateContainedLabelsSet(
		final RandomAccessibleInterval<Pair<UnsignedLongType, LabelMultisetType>> relevantData)
{
	final TLongHashSet currentDataAsSet = new TLongHashSet();
	for (final Pair<UnsignedLongType, LabelMultisetType> p : Views.iterable(relevantData))
	{
		final UnsignedLongType  pa  = p.getA();
		final LabelMultisetType pb  = p.getB();
		final long              pav = pa.getIntegerLong();
		if (pav == Label.INVALID)
		{
			pb
					.entrySet()
					.stream()
					.map(Entry::getElement)
					.mapToLong(Label::id)
					.forEach(currentDataAsSet::add);
		}
		else
		{
			currentDataAsSet.add(pav);
		}
	}
	return currentDataAsSet;
}
 
Example #7
Source File: MappedArrayOfLongs.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
@Override
public final Array<Long> distinct(int limit) {
    final int capacity = limit < Integer.MAX_VALUE ? limit : 100;
    final TLongSet set = new TLongHashSet(capacity);
    final ArrayBuilder<Long> builder = ArrayBuilder.of(capacity, Long.class);
    for (int i=0; i<length(); ++i) {
        final long value = getLong(i);
        if (set.add(value)) {
            builder.addLong(value);
            if (set.size() >= limit) {
                break;
            }
        }
    }
    return builder.toArray();
}
 
Example #8
Source File: MappedArrayWithLongCoding.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
@Override
public Array<T> distinct(int limit) {
    final int capacity = limit < Integer.MAX_VALUE ? limit : 100;
    final TLongSet set = new TLongHashSet(capacity);
    final ArrayBuilder<T> builder = ArrayBuilder.of(capacity, type());
    for (int i=0; i<length(); ++i) {
        final long code = getLong(i);
        if (set.add(code)) {
            final T value = getValue(i);
            builder.add(value);
            if (set.size() >= limit) {
                break;
            }
        }
    }
    return builder.toArray();
}
 
Example #9
Source File: MaskedSource.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
public static TLongSet affectedBlocks(final long[] gridDimensions, final int[] blockSize, final Interval...
		intervals)
{
	final TLongHashSet blocks              = new TLongHashSet();
	final int[]        ones                = IntStream.generate(() -> 1).limit(blockSize.length).toArray();
	final long[]       relevantIntervalMin = new long[blockSize.length];
	final long[]       relevantIntervalMax = new long[blockSize.length];
	for (final Interval interval : intervals)
	{
		Arrays.setAll(relevantIntervalMin, d -> (interval.min(d) / blockSize[d]));
		Arrays.setAll(relevantIntervalMax, d -> (interval.max(d) / blockSize[d]));
		Grids.forEachOffset(
				relevantIntervalMin,
				relevantIntervalMax,
				ones,
				offset -> blocks.add(IntervalIndexer.positionToIndex(offset, gridDimensions))
		                   );
	}

	return blocks;
}
 
Example #10
Source File: MaskedSource.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
public static TLongSet affectedBlocks(final RandomAccessibleInterval<?> input, final CellGrid grid, final Interval
		interval)
{
	if (input instanceof AccessedBlocksRandomAccessible<?>)
	{
		final AccessedBlocksRandomAccessible<?> tracker = (net.imglib2.util.AccessedBlocksRandomAccessible<?>)
				input;
		if (grid.equals(tracker.getGrid()))
		{
			final long[] blocks = tracker.listBlocks();
			LOG.debug("Got these blocks from tracker: {}", blocks);
			return new TLongHashSet(blocks);
		}
	}
	return affectedBlocks(grid, interval);
}
 
Example #11
Source File: MaskedSource.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
public static TLongSet affectedBlocks(final long[] gridDimensions, final int[] blockSize, final Interval interval)
{
	final TLongHashSet blocks              = new TLongHashSet();
	final int[]        ones                = IntStream.generate(() -> 1).limit(blockSize.length).toArray();
	final long[]       relevantIntervalMin = new long[blockSize.length];
	final long[]       relevantIntervalMax = new long[blockSize.length];
	Arrays.setAll(relevantIntervalMin, d -> (interval.min(d) / blockSize[d]));
	Arrays.setAll(relevantIntervalMax, d -> (interval.max(d) / blockSize[d]));
	Grids.forEachOffset(
			relevantIntervalMin,
			relevantIntervalMax,
			ones,
			offset -> blocks.add(IntervalIndexer.positionToIndex(offset, gridDimensions))
	                   );

	return blocks;
}
 
Example #12
Source File: MaskedSource.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
Map<Long, long[]>[] getAffectedBlocksById()
{
	@SuppressWarnings("unchecked") final Map<Long, long[]>[] maps = new HashMap[this.affectedBlocksByLabel.length];

	for (int level = 0; level < maps.length; ++level)
	{
		maps[level] = new HashMap<>();
		final Map<Long, long[]> map = maps[level];
		for (final Entry<Long, TLongHashSet> entry : this.affectedBlocksByLabel[level].entrySet())
		{
			map.put(entry.getKey(), entry.getValue().toArray());
		}
	}

	LOG.debug("Retruning affected blocks by id for {} levels: {}", maps.length, maps);
	return maps;
}
 
Example #13
Source File: SegmentMaskGenerators.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
public static <T, B extends BooleanType<B>> BiFunction<TLongHashSet, Double, Converter<T, B>> create(
		final DataSource<T, ?> source,
		final int level)
{
	final T t = source.getDataType();

	if (t instanceof LabelMultisetType)
		return new LabelMultisetTypeMaskGenerator(source, level);

	if (t instanceof IntegerType<?>)
	{
		final IntegerTypeMaskGenerator integerTypeMaskGenerator = new IntegerTypeMaskGenerator();
		return (l, minLabelRatio) -> integerTypeMaskGenerator.apply(l);
	}

	return null;
}
 
Example #14
Source File: SparseArrayWithLongCoding.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
@Override
public Array<T> distinct(int limit) {
    final int capacity = limit < Integer.MAX_VALUE ? limit : 100;
    final TLongSet set = new TLongHashSet(capacity);
    final ArrayBuilder<T> builder = ArrayBuilder.of(capacity, type());
    for (int i=0; i<length(); ++i) {
        final long code = getLong(i);
        if (set.add(code)) {
            final T value = getValue(i);
            builder.add(value);
            if (set.size() >= limit) {
                break;
            }
        }
    }
    return builder.toArray();
}
 
Example #15
Source File: Sets.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
public static final TLongHashSet containedInFirstButNotInSecond(
		final TLongHashSet first,
		final TLongHashSet second)
{
	final TLongHashSet notInSecond = new TLongHashSet();
	for (final TLongIterator fIt = first.iterator(); fIt.hasNext(); )
	{
		final long p = fIt.next();
		if (!second.contains(p))
		{
			notInSecond.add(p);
		}
	}
	LOG.debug("First:         {}", first);
	LOG.debug("Second:        {}", second);
	LOG.debug("Not in second: {}", notInSecond);
	return notInSecond;
}
 
Example #16
Source File: SetsTest.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testContainedInFirstButNotInSecond()
{


	final TLongHashSet set1 = new TLongHashSet(new long[] {1, 2});
	final TLongHashSet set2 = new TLongHashSet(new long[] {2, 3});
	final TLongHashSet set3 = new TLongHashSet(new long[] {4, 5});

	Assert.assertEquals(new TLongHashSet(), Sets.containedInFirstButNotInSecond(set1, set1));
	Assert.assertEquals(new TLongHashSet(), Sets.containedInFirstButNotInSecond(set2, set2));
	Assert.assertEquals(new TLongHashSet(), Sets.containedInFirstButNotInSecond(set3, set3));

	Assert.assertEquals(new TLongHashSet(new long[] {1}), Sets.containedInFirstButNotInSecond(set1, set2));
	Assert.assertEquals(new TLongHashSet(new long[] {3}), Sets.containedInFirstButNotInSecond(set2, set1));

	Assert.assertEquals(set1, Sets.containedInFirstButNotInSecond(set1, set3));
	Assert.assertEquals(set2, Sets.containedInFirstButNotInSecond(set2, set3));
	Assert.assertEquals(set3, Sets.containedInFirstButNotInSecond(set3, set1));
	Assert.assertEquals(set3, Sets.containedInFirstButNotInSecond(set3, set2));

}
 
Example #17
Source File: FallingBlocksMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Return the number of unsupported blocks connected to any blocks neighboring the given location,
 * which is assumed to contain an air block. The search may bail out early when the count is greater
 * or equal to the given limit, though this cannot be guaranteed.
 */
private int countUnsupportedNeighbors(long pos, int limit) {
    TLongSet supported = new TLongHashSet();
    TLongSet unsupported = new TLongHashSet();

    try {
        for(BlockFace face : NEIGHBORS) {
            if(!this.isSupported(neighborPos(pos, face), supported, unsupported)) {
                if(unsupported.size() >= limit) break;
            }
        }
    }
    catch(MaxSearchVisitsExceeded ex) {
        this.logError(ex);
    }

    return unsupported.size();
}
 
Example #18
Source File: TLongHashSetSerializer.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void write(Kryo kryo, Output output, TLongHashSet object) {
	output.writeInt(object.size(), true);
	TLongIterator it = object.iterator();
	while (it.hasNext()) {
		kryo.writeObject(output, it.next());
	}
}
 
Example #19
Source File: TLongHashSetSerializer.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public TLongHashSet read(Kryo kryo, Input input, Class<TLongHashSet> type) {
	final int size = input.readInt(true);
	TLongHashSet object = new TLongHashSet();
	for (int i = 0; i < size; ++i) {
		object.add(kryo.readObject(input, long.class));
	}
	return object;
}
 
Example #20
Source File: ChainingTSCPair.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void apply_lookback_(ExpressionLookBack lookBack) {
    final TLongHashSet retainTs = lookBack.filter(new ForwardIterator<>(timestamps.stream().mapToObj(TSCollectionImpl::new).iterator()))
            .map(TimeSeriesCollection::getTimestamp)
            .mapToLong(DateTime::getMillis)
            .collect(TLongHashSet::new, TLongHashSet::add, TLongHashSet::addAll);

    timestamps.retainAll(retainTs);
    data.values().forEach(tsvChain -> tsvChain.retainAll(retainTs));

    // Drop inactive groups.
    final long oldestTs = timestamps.backLong();
    activeGroups.retainEntries((group, ts) -> ts >= oldestTs);
    data.keySet().retainAll(activeGroups.keySet());
}
 
Example #21
Source File: BlockVectors.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
static TLongSet encodePosSet(Collection<?> vectors) {
  TLongSet encoded = new TLongHashSet(vectors.size());
  for (Object o : vectors) {
    if (o instanceof BlockVector) {
      encoded.add(encodePos((BlockVector) o));
    }
  }
  return encoded;
}
 
Example #22
Source File: IntersectingSourceState.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
private ShapeKey<TLongHashSet> createFragmentsShapeKey(final ShapeKey<IntersectingSourceStateMeshKey> key)
{
	return new ShapeKey<>(
			key.shapeId().getFragments(),
			key.scaleIndex(),
			key.simplificationIterations(),
			key.smoothingLambda(),
			key.smoothingIterations(),
			key.minLabelRatio(),
			key.min(),
			key.max());
}
 
Example #23
Source File: EdgeSerializer.java    From tinkergraph-gremlin with Apache License 2.0 5 votes vote down vote up
@Override
/** using same format to store edgeIds as for vertices */
protected Map<String, TLongSet> getEdgeIds(Edge edge, Direction direction) {
  final Map<String, TLongSet> edgeIds = new THashMap<>();
  switch (direction) {
    case IN:
      edgeIds.put(Direction.IN.name(), new TLongHashSet(Arrays.asList((long) edge.inVertex().id())));
      break;
    case OUT:
      edgeIds.put(Direction.OUT.name(), new TLongHashSet(Arrays.asList((long) edge.outVertex().id())));
      break;
    default: throw new NotImplementedException();
  }
  return edgeIds;
}
 
Example #24
Source File: VertexSerializer.java    From tinkergraph-gremlin with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, TLongSet> getEdgeIds(Vertex vertex, Direction direction) {
  Map<String, TLongSet> edgeIdsByLabel = new THashMap<>();
  vertex.edges(direction).forEachRemaining(edge -> {
    edgeIdsByLabel.computeIfAbsent(edge.label(), label -> new TLongHashSet());
    edgeIdsByLabel.get(edge.label()).add((long) edge.id());
  });
  return edgeIdsByLabel;
}
 
Example #25
Source File: ChannelManagerImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new ChannelManager instance
 *
 * @param channel
 *        {@link net.dv8tion.jda.api.entities.GuildChannel GuildChannel} that should be modified
 *        <br>Either {@link net.dv8tion.jda.api.entities.VoiceChannel Voice}- or {@link net.dv8tion.jda.api.entities.TextChannel TextChannel}
 */
public ChannelManagerImpl(GuildChannel channel)
{
    super(channel.getJDA(),
          Route.Channels.MODIFY_CHANNEL.compile(channel.getId()));
    JDA jda = channel.getJDA();
    ChannelType type = channel.getType();
    this.channel = new SnowflakeReference<>(channel, (channelId) -> jda.getGuildChannelById(type, channelId));
    if (isPermissionChecksEnabled())
        checkPermissions();
    this.overridesAdd = new TLongObjectHashMap<>();
    this.overridesRem = new TLongHashSet();
}
 
Example #26
Source File: AccessedBlocksRandomAccessible.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
public AccessedBlocksRandomAccessible(final RandomAccessibleInterval<T> source, final int[] blockSize, final
long[] blockGridDimensions)
{
	super(source);
	this.visitedBlocks = new TLongHashSet();
	this.blockSize = blockSize;
	this.blockGridDimensions = blockGridDimensions;
}
 
Example #27
Source File: BlockUtils.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public static TLongSet encodePosSet(Collection<?> vectors) {
    TLongSet encoded = new TLongHashSet(vectors.size());
    for(Object o : vectors) {
        if(o instanceof BlockVector) {
            encoded.add(encodePos((BlockVector) o));
        }
    }
    return encoded;
}
 
Example #28
Source File: AbstractCacheView.java    From JDA with Apache License 2.0 5 votes vote down vote up
public TLongSet keySet()
{
    try (UnlockHook hook = readLock())
    {
        return new TLongHashSet(elements.keySet());
    }
}
 
Example #29
Source File: Combo.java    From olca-app with Mozilla Public License 2.0 5 votes vote down vote up
public static Builder on(IResult r) {
	Combo c = new Combo();
	c.flows = new ArrayList<FlowDescriptor>();
	TLongHashSet flowIDs = new TLongHashSet();
	for (IndexFlow f : r.getFlows()) {
		if (f.flow == null || flowIDs.contains(f.flow.id))
			continue;
		flowIDs.add(f.flow.id);
		c.flows.add(f.flow);
	}

	// add LCIA categories
	if (r.hasImpactResults()) {
		c.impacts = r.getImpacts();
	}

	// add cost / added value selection
	if (r.hasCostResults() && (r instanceof SimpleResult)) {
		SimpleResult sr = (SimpleResult) r;
		CostResultDescriptor d1 = new CostResultDescriptor();
		d1.forAddedValue = false;
		d1.name = M.Netcosts;
		CostResultDescriptor d2 = new CostResultDescriptor();
		d2.forAddedValue = true;
		d2.name = M.AddedValue;
		c.costs = sr.totalCosts >= 0
				? Arrays.asList(d1, d2)
				: Arrays.asList(d2, d1);
	}

	return new Builder(c);
}
 
Example #30
Source File: CachedGridEntry.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
public boolean populateChunk(World world) {
    MutableBlockPos blockPos = new MutableBlockPos();
    boolean generatedAnything = false;
    for (OreDepositDefinition definition : oreBlocks.keySet()) {
        TLongList blockIndexList = oreBlocks.get(definition);
        TLongSet generatedBlocks = new TLongHashSet();
        boolean generatedOreVein = false;
        for (int i = 0; i < blockIndexList.size(); i++) {
            long blockIndex = blockIndexList.get(i);
            int xyzValue = (int) (blockIndex >> 32);
            int blockX = (byte) xyzValue;
            int blockZ = (byte) (xyzValue >> 8);
            int blockY = (short) (xyzValue >> 16);
            int index = (int) blockIndex;
            blockPos.setPos(chunkX * 16 + blockX, blockY, chunkZ * 16 + blockZ);
            IBlockState currentState = world.getBlockState(blockPos);
            IBlockState newState;
            if (index == 0) {
                //it's primary ore block
                if (!definition.getGenerationPredicate().test(currentState, world, blockPos))
                    continue; //do not generate if predicate didn't match
                newState = definition.getBlockFiller().apply(currentState, world, blockPos, blockX, blockY, blockZ);
            } else {
                //it's populator-generated block with index
                VeinBufferPopulator populator = (VeinBufferPopulator) definition.getVeinPopulator();
                newState = populator.getBlockByIndex(world, blockPos, index - 1);
            }
            //set flags as 16 to avoid observer updates loading neighbour chunks
            world.setBlockState(blockPos, newState, 16);
            generatedBlocks.add(Block.getStateId(newState));
            generatedOreVein = true;
            generatedAnything = true;
        }
        if (generatedOreVein) {
            this.generatedBlocksSet.put(definition, generatedBlocks);
            this.generatedOres.add(definition);
        }
    }
    return generatedAnything;
}