/** * Finds and returns name matching the specified symbol, if such name already exists in the table; * or if not, creates name object, adds to the table, and returns it. * * <p>Note: this is the general purpose method that can be called for names of any length. * However, if name is less than 9 bytes long, it is preferable to call the version optimized for * short names. * * @param q Array of int32s, each of which contain 4 bytes of encoded name * @param qlen Number of int32s, starting from index 0, in quads parameter * @return Name matching the symbol passed (or constructed for it) */ public Name findName(int[] q, int qlen) { if (qlen < 3) { // another sanity check return findName(q[0], (qlen < 2) ? 0 : q[1]); } int hash = calcHash(q, qlen); // (for rest of comments regarding logic, see method above) int ix = (hash & _hashMask); int val = _hash[ix]; if ((((val >> 8) ^ hash) << 8) == 0) { Name name = _mainNames[ix]; if (name == null // main slot empty; no collision list then either || name.equals(q, qlen)) { // should be match, let's verify return name; } } else if (val == 0) { // empty slot? no match return null; } val &= 0xFF; if (val > 0) { // 0 means 'empty' val -= 1; // to convert from 1-based to 0... Bucket bucket = _collList[val]; if (bucket != null) { return bucket.find(hash, q, qlen); } } return null; }
@Override public void setSource(Resource reference, String source) { Bucket bucket = checkIndexed(reference); if (bucket != null && !bucket.isExcluded()) { persistence.setSource(reference, source); } }
/** * Finds and returns name matching the specified symbol, if such name already exists in the table. * If not, will return null. * * <p>Note: separate methods to optimize common case of relatively short element/attribute names * (8 or less ascii characters) * * @param q1 int32 containing first 4 bytes of the name. * @param q2 int32 containing bytes 5 through 8 of the name; if less than 8 bytes, padded with up * to 3 zero bytes in front (zero MSBs, ie. right aligned) * @return Name matching the symbol passed (or constructed for it) */ public Name findName(int q1, int q2) { int hash = (q2 == 0) ? calcHash(q1) : calcHash(q1, q2); int ix = (hash & _hashMask); int val = _hash[ix]; /* High 24 bits of the value are low 24 bits of hash (low 8 bits * are bucket index)... match? */ if ((((val >> 8) ^ hash) << 8) == 0) { // match // Ok, but do we have an actual match? Name name = _mainNames[ix]; if (name == null) { // main slot empty; can't find return null; } if (name.equals(q1, q2)) { return name; } } else if (val == 0) { // empty slot? no match return null; } // Maybe a spill-over? val &= 0xFF; if (val > 0) { // 0 means 'empty' val -= 1; // to convert from 1-based to 0... Bucket bucket = _collList[val]; if (bucket != null) { return bucket.find(hash, q1, q2); } } // Nope, no match whatsoever return null; }
/** {@inheritDoc} */ @Override public List<Violation> getViolations(ViolationQuery violationQuery) { Resource resource = violationQuery.getResource(); if (resource == null) { throw new IllegalArgumentException( "A resource must be set on the ViolationQuery in order to search for violations."); } if (!Scopes.isHigherThanOrEquals(resource, Scopes.FILE)) { return Collections.emptyList(); } Bucket bucket = buckets.get(resource); if (bucket == null) { return Collections.emptyList(); } List<Violation> violations = deprecatedViolations.get(bucket.getResource().getEffectiveKey()); if (violationQuery.getSwitchMode() == ViolationQuery.SwitchMode.BOTH) { return violations; } List<Violation> filteredViolations = Lists.newArrayList(); for (Violation violation : violations) { if (isFiltered(violation, violationQuery.getSwitchMode())) { filteredViolations.add(violation); } } return filteredViolations; }
public synchronized int size() { int sum = 0; for (Bucket bucket : buckets) { sum += bucket.getActivePeerCount(); } return sum; }
public void maintain() { Bucket[] buckets = getBucketsCopy(); for (Bucket bucket : buckets) { bucket.maintain(); } updateStatistics(buckets); }
public synchronized void instantiateBucket(Bucket b) { assert b.isUninstantiated() || b.isCompletelyFree(); b.reconfigure(sizeIndex, bucketSizes, bucketCapacity); bucketList.add(b); freeBuckets.add(b); completelyFreeBuckets.add(b); }
public void add(int index, Object value) { if (index < 0 || index > count) { return; } Bucket newBucket = new Bucket(value, null); if (index == 0) { newBucket.next = start; start = newBucket; count++; return; } if (index == count) { add(value); return; } Bucket cursor = start; int i = 1; while (i < index) { cursor = cursor.next; i++; } Bucket nextBucket = cursor.next; cursor.next = newBucket; newBucket.next = nextBucket; count++; }
// Not really a std method... but commonly useful public String toDebugString() { StringBuilder sb = new StringBuilder(); sb.append("[PNameTable, size: "); sb.append(mCount); sb.append('/'); sb.append(mMainHash.length); sb.append(" -> "); for (int i = 0; i < mMainHash.length; ++i) { sb.append("\n#"); sb.append(i); sb.append(": 0x"); sb.append(Integer.toHexString(mMainHash[i])); sb.append(" == "); PName name = mMainNames[i]; if (name == null) { sb.append("null"); } else { sb.append('"'); sb.append(name.toString()); sb.append('"'); } } sb.append("\nSpill("); sb.append(mCollEnd); sb.append("):"); for (int i = 0; i < mCollEnd; ++i) { Bucket bucket = mCollList[i]; sb.append("\nsp#"); sb.append(i); sb.append(": "); sb.append(bucket.toDebugString()); } return sb.toString(); }
@Override public void addViolation(Violation violation, boolean force) { Resource resource = violation.getResource(); if (resource == null) { violation.setResource(currentProject); } else if (!Scopes.isHigherThanOrEquals(resource, Scopes.FILE)) { throw new IllegalArgumentException( "Violations are only supported on files, directories and project"); } Rule rule = violation.getRule(); if (rule == null) { LOG.warn("Rule is null. Ignoring violation {}", violation); return; } Bucket bucket = getBucket(resource); if (bucket == null) { LOG.warn("Resource is not indexed. Ignoring violation {}", violation); return; } // keep a limitation (bug?) of deprecated violations api : severity is always // set by sonar. The severity set by plugins is overridden. // This is not the case with issue api. violation.setSeverity(null); violation.setResource(bucket.getResource()); moduleIssues.initAndAddViolation(violation); }
public void add(int index, T value) { // 1) index 유효범위 검사 if (index < 0 || index > this.count) { return; } // 2) index가 0일 때 if (index == 0) { Bucket<T> newBucket = new Bucket<>(value, start); start = newBucket; count++; return; } // 3) index가 빈 버킷을 가리킬 때 if (index == this.count) { this.add(value); return; } // 4) 그 밖에 // => 인덱스가 가리키는 항목의 직전 항목을 찾아서 새 버킷을 연결한다. Bucket<T> cursor = start; for (int i = 0; i < (index - 1); i++) { cursor = cursor.next; } cursor.next = new Bucket<>(value, cursor.next); count++; }
public void tick() { double totalForce = 0.0; double totalMass = 0.0; for (Map.Entry<Double, Bucket> bucketEntry : buckets.entrySet()) { Bucket bucket = bucketEntry.getValue(); bucket.tick(); double bucketAngle = rotation + bucketEntry.getKey(); double forceAngle = bucketAngle - HALF_PI; double bucketMass = bucket.getMass(); double verticalForce = bucketMass * GRAVITY; double angularForce = verticalForce * Math.cos(forceAngle); totalForce += angularForce; totalMass += bucketMass; bucketAngle = (bucketAngle + TAU) % TAU; if (bucketAngle > (TAU - spoutAngle) || bucketAngle < spoutAngle) { bucket.addWater(WATER_TO_ADD); } } double totalAcceleration = totalForce / totalMass; rotationalVelocity += (totalAcceleration / 10000); rotationalVelocity *= FRICTION; rotation += rotationalVelocity; rotation += TAU; rotation %= TAU; }
/** * Finds and returns name matching the specified symbol, if such name already exists in the table; * or if not, creates name object, adds to the table, and returns it. * * <p>Note: separate methods to optimize common case of relatively short element/attribute names * (8 or less ascii characters) * * @param firstQuad int32 containing first 4 bytes of the pname; if the whole name less than 4 * bytes, padded with zero bytes in front (zero MSBs, ie. right aligned) * @param secondQuad int32 containing bytes 5 through 8 of the pname; if less than 8 bytes, padded * with up to 4 zero bytes in front (zero MSBs, ie. right aligned) * @return PName matching the symbol passed (or constructed for it) */ public ByteBasedPName findSymbol(int hash, int firstQuad, int secondQuad) { int ix = (hash & mMainHashMask); int val = mMainHash[ix]; /* High 24 bits of the value are low 24 bits of hash (low 8 bits * are bucket index)... match? */ if ((((val >> 8) ^ hash) << 8) == 0) { // match // Ok, but do we have an actual match? ByteBasedPName pname = mMainNames[ix]; if (pname == null) { // main slot empty; can't find return null; } if (pname.equals(firstQuad, secondQuad)) { return pname; } } else if (val == 0) { // empty slot? no match return null; } // Maybe a spill-over? val &= 0xFF; if (val > 0) { // 0 means 'empty' val -= 1; // to convert from 1-based to 0... Bucket bucket = mCollList[val]; if (bucket != null) { return bucket.find(hash, firstQuad, secondQuad); } } // Nope, no match whatsoever return null; }
/** * Update a set of buckets with new values. If collisions occur, resets the memcache value to * null. * * @param updates can have null Entity values, which will record a negative cache result. Buckets * must have been obtained from getAll(). */ public void putAll(Collection<Bucket> updates) { Set<Key> good = this.cachePutIfUntouched(updates); if (good.size() == updates.size()) return; // Figure out which ones were bad List<Key> bad = new ArrayList<>(); for (Bucket bucket : updates) if (!good.contains(bucket.getKey())) bad.add(bucket.getKey()); if (!bad.isEmpty()) { // So we had some collisions. We need to reset these back to null, but do it in a safe way - // if we // blindly set null something already null, it will break any putIfUntouched() which saw the // first null. // This could result in write contention starving out a real write. The solution is to only // reset things // that are not already null. Map<Key, Object> cached = this.cacheGetAll(bad); // Remove the stuff we don't care about Iterator<Object> it = cached.values().iterator(); while (it.hasNext()) { Object value = it.next(); if (value == null) it.remove(); } this.empty(cached.keySet()); } }
/** Basically a list comprehension of the keys for convenience. */ public static Set<Key> keysOf(Iterable<Bucket> buckets) { Set<Key> keys = new HashSet<>(); for (Bucket buck : buckets) keys.add(buck.getKey()); return keys; }
boolean remove(int i) { boolean flag1; if (i >= 64) { ensureNext(); flag1 = next.remove(i - 64); } else { long l = 1L << i; boolean flag; if ((mData & l) != 0L) { flag = true; } else { flag = false; } mData = mData & (-1L ^ l); l--; mData = mData & l | Long.rotateRight(mData & (-1L ^ l), 1); flag1 = flag; if (next != null) { if (next.get(0)) { set(63); } next.remove(0); return flag; } } return flag1; }
@Override protected void doReadFrom(StreamInput in) throws IOException { if (in.getVersion().onOrAfter(Version.V_1_4_0_Beta1)) { this.docCountError = in.readLong(); } else { this.docCountError = -1; } this.order = InternalOrder.Streams.readOrder(in); this.formatter = ValueFormatterStreams.readOptional(in); this.requiredSize = readSize(in); if (in.getVersion().onOrAfter(Version.V_1_4_0_Beta1)) { this.shardSize = readSize(in); this.showTermDocCountError = in.readBoolean(); } else { this.shardSize = requiredSize; this.showTermDocCountError = false; } this.minDocCount = in.readVLong(); if (in.getVersion().onOrAfter(Version.V_1_4_0)) { this.otherDocCount = in.readVLong(); } int size = in.readVInt(); List<InternalTerms.Bucket> buckets = new ArrayList<>(size); for (int i = 0; i < size; i++) { Bucket bucket = new Bucket(formatter, showTermDocCountError); bucket.readFrom(in); buckets.add(bucket); } this.buckets = buckets; this.bucketMap = null; }
public T remove(int index) { // 1) index의 유효여부 검사: 0 미만 또는 count 이상이면 무효한 인덱스. if (index < 0 || index >= count) { return null; } T temp = null; count--; // 2) 0번째를 지울 때 if (index == 0) { temp = start.value; start = start.next; return temp; } // 3) 1 이상의 인덱스를 지우기 // => 해당 인덱스의 전 항목을 찾아서 // 다음 다음 항목으로 바로 연결한다. Bucket<T> cursor = start; for (int i = 0; i < (index - 1); i++) { cursor = cursor.next; } temp = cursor.next.value; cursor.next = cursor.next.next; return temp; }
void insert(int i, boolean flag) { if (i >= 64) { ensureNext(); next.insert(i - 64, flag); } else { long l; boolean flag1; if ((mData & 0x8000000000000000L) != 0L) { flag1 = true; } else { flag1 = false; } l = (1L << i) - 1L; mData = mData & l | (mData & (-1L ^ l)) << 1; if (flag) { set(i); } else { clear(i); } if (flag1 || next != null) { ensureNext(); next.insert(0, flag1); return; } } }
private void sequence() { int index = 0; for (Bucket bucket : buckets) { bucket.index(index); index++; } }
public SchematicMiniBucket(BeliefNetworkEx bn, int bound) { this.bn = bn; bucketMap = new HashMap<BeliefNode, Bucket>(); // order the variables from X_1 to X_n BeliefNode[] nodes = bn.bn.getNodes(); int[] topOrder = bn.getTopologicalOrder(); // place each CPT in the bucket of the highest index for (int i = topOrder.length - 1; i > -1; i--) { Bucket bucket = new Bucket(nodes[topOrder[i]]); int[] cpt = bn.getDomainProductNodeIndices(nodes[topOrder[i]]); HashSet<BeliefNode> cptNodes = new HashSet<BeliefNode>(); for (int j : cpt) { cptNodes.add(nodes[j]); } BucketVar bv = new BucketVar(cptNodes); bv.setFunction(nodes[topOrder[i]].getCPF()); bucket.addVar(bv); bucketMap.put(nodes[topOrder[i]], bucket); } // partition buckets and create arcs for (int i = topOrder.length - 1; i > -1; i--) { Bucket oldVar = bucketMap.get(nodes[topOrder[i]]); oldVar.partition(bound); HashSet<BucketVar> scopes = oldVar.createScopeFunctions(); for (BucketVar bv : scopes) { // add new variables to the bucket with the highest index BeliefNode node = bv.getMaxNode(bn); bucketMap.get(node).addVar(bv); } } }
public void add(Object value) { end.value = value; Bucket temp = new Bucket(); end.next = temp; end = temp; count++; }
/** * Finds and returns name matching the specified symbol, if such name already exists in the table; * or if not, creates name object, adds to the table, and returns it. * * <p>Note: this is the general purpose method that can be called for names of any length. * However, if name is less than 9 bytes long, it is preferable to call the version optimized for * short names. * * @param quads Array of int32s, each of which contain 4 bytes of encoded name * @param qlen Number of int32s, starting from index 0, in quads parameter * @return PName matching the symbol passed (or constructed for it) */ public ByteBasedPName findSymbol(int hash, int[] quads, int qlen) { if (qlen < 3) { // another sanity check return findSymbol(hash, quads[0], (qlen < 2) ? 0 : quads[1]); } // (for rest of comments regarding logic, see method above) int ix = (hash & mMainHashMask); int val = mMainHash[ix]; if ((((val >> 8) ^ hash) << 8) == 0) { ByteBasedPName pname = mMainNames[ix]; if (pname == null) { // main slot empty; no collision list then either return null; } if (pname.equals(quads, qlen)) { // should be match, let's verify return pname; } } else if (val == 0) { // empty slot? no match return null; } val &= 0xFF; if (val > 0) { // 0 means 'empty' val -= 1; // to convert from 1-based to 0... Bucket bucket = mCollList[val]; if (bucket != null) { return bucket.find(hash, quads, qlen); } } return null; }
public void moveRight() { if (lives > 0) { bucket = bucket.moveRight(); if (bucket.getLocation().getX() > WIDTH + Bucket.WIDTH / 2) bucket = bucket.moveTo(-Bucket.WIDTH / 2, (int) bucket.getLocation().getY()); } }
/** * Goes through the buckets from ix and out, checking for each candidate if it's in one of the * buckets, and if so, increasing its score accordingly. No new candidates are added. */ private void bumpScores(Map<Long, Score> candidates, List<Bucket> buckets, int ix) { for (; ix < buckets.size(); ix++) { Bucket b = buckets.get(ix); if (b.nextfree > CUTOFF_FACTOR_2 * candidates.size()) return; double score = b.getScore(); for (Score s : candidates.values()) if (b.contains(s.id)) s.score += score; } }
@Override public Bucket readResult(StreamInput in, BucketStreamContext context) throws IOException { Bucket buckets = new Bucket( context.formatter(), (boolean) context.attributes().get("showDocCountError")); buckets.readFrom(in); return buckets; }
public void refreshBucketStats() { mBucketStats.clear(); for (int i = 0; i < mPool.mBuckets.size(); ++i) { final int bucketedSize = mPool.mBuckets.keyAt(i); final Bucket<V> bucket = mPool.mBuckets.valueAt(i); mBucketStats.put(bucketedSize, new IntPair(bucket.getInUseCount(), bucket.mFreeList.size())); } }
/** * Free a block with the offset * * @param offset block's offset * @return size freed */ public synchronized int freeBlock(long offset) { int bucketNo = (int) (offset / bucketCapacity); assert bucketNo >= 0 && bucketNo < buckets.length; Bucket targetBucket = buckets[bucketNo]; bucketSizeInfos[targetBucket.sizeIndex()].freeBlock(targetBucket, offset); usedSize -= targetBucket.getItemAllocationSize(); return targetBucket.getItemAllocationSize(); }
public synchronized IndexStatistics statistics() { long free = 0, used = 0; for (Bucket b : bucketList) { free += b.freeCount(); used += b.usedCount(); } return new IndexStatistics(free, used, bucketSizes[sizeIndex]); }
@Override public Resource getParent(Resource resource) { Bucket bucket = getBucket(resource); if (bucket != null && bucket.getParent() != null) { return bucket.getParent().getResource(); } return null; }