@Override public void run() { MidimsgHolder msg = null; if (playQueue.size() > 0) { synchronized (playQueue) { msg = playQueue.getFirst(); } } while (msg != null && msg.offset <= playOffset) { if (msg.newTempo != null) { tempo = msg.newTempo; } else { if (msg.offset == playOffset) receiver.send(msg.msg, -1); } synchronized (playQueue) { playQueue.removeFirst(); if (playQueue.size() > 0) msg = playQueue.getFirst(); else msg = null; } } playOffset++; synchronized (playQueue) { if (playQueue.size() == 0) { playTasks.remove(this); return; } } if (play) // continue to play if not paused meanwhile { timer.schedule(newTask(), (long) (60000f / tempo / 32f)); } }
@Test public void testBlockUnblockWithPresence() throws Exception { JID connJid = JID.jidInstanceNS("[email protected]/test-111"); JID userJid = JID.jidInstanceNS("[email protected]/res-1"); XMPPResourceConnection sess = getSession(connJid, userJid); String blockJid = "*****@*****.**"; RosterAbstract roster_util = RosterFactory.getRosterImplementation(true); roster_util.addBuddy(sess, JID.jidInstance(blockJid), "Block-1", null, null); roster_util.setBuddySubscription( sess, RosterAbstract.SubscriptionType.both, JID.jidInstance(blockJid)); checkPrivacyJidBlocked(sess, blockJid, false); List<String> blocked = getBlocked(sess); assertTrue(blocked == null || blocked.isEmpty()); block(sess, blockJid); assertEquals(3, results.size()); privacy.filter(null, sess, null, results); assertEquals(3, results.size()); Packet result = results.poll(); assertNotNull(result); assertEquals(tigase.server.Presence.ELEM_NAME, result.getElemName()); assertEquals(StanzaType.unavailable, result.getType()); result = results.poll(); assertNotNull(result); assertEquals(Iq.ELEM_NAME, result.getElemName()); assertEquals(StanzaType.result, result.getType()); result = results.poll(); assertNotNull(result); assertEquals(Iq.ELEM_NAME, result.getElemName()); assertEquals(StanzaType.set, result.getType()); checkPrivacyJidBlocked(sess, blockJid, true); blocked = getBlocked(sess); assertTrue(blocked.contains(blockJid)); unblock(sess, blockJid); assertEquals(3, results.size()); privacy.filter(null, sess, null, results); assertEquals(3, results.size()); result = results.poll(); assertNotNull(result); assertEquals(tigase.server.Presence.ELEM_NAME, result.getElemName()); assertEquals(StanzaType.probe, result.getType()); result = results.poll(); assertNotNull(result); assertEquals(Iq.ELEM_NAME, result.getElemName()); assertEquals(StanzaType.result, result.getType()); result = results.poll(); assertNotNull(result); assertEquals(Iq.ELEM_NAME, result.getElemName()); assertEquals(StanzaType.set, result.getType()); checkPrivacyJidBlocked(sess, blockJid, false); blocked = getBlocked(sess); assertTrue(blocked == null || blocked.isEmpty()); }
public boolean subsetFound(int t, ArrayDeque<BaseVertex> complement, ArrayDeque<BaseVertex> set) { if (max <= set.size()) { max = set.size(); maxsets.add(new ArrayDeque<BaseVertex>(set)); } return false; }
public boolean subsetFound(int t, ArrayDeque<BaseVertex> complement, ArrayDeque<BaseVertex> set) { nn++; if (max < set.size()) { max = set.size(); } return false; }
@Test public void test7() throws Exception { HotSpotInstalledCode installedBenchmarkCode = getInstalledCode("queueTest", Object.class, Object.class); ArrayDeque<Object> q = new ArrayDeque<>(); Object[] objects = new Object[512]; for (int i = 0; i < objects.length; i++) { objects[i] = new Object(); } int j = 0; while (j < objects.length) { if (!installedBenchmarkCode.isValid()) { // This can get invalidated due to lack of MDO update installedBenchmarkCode = getInstalledCode("queueTest", Object.class, Object.class); } installedBenchmarkCode.executeVarargs(q, objects[j]); j++; } System.gc(); Assert.assertTrue(q.size() == objects.length); Assert.assertTrue(!q.isEmpty()); j = 0; while (j < objects.length) { Assert.assertTrue(objects[j] == q.remove()); j++; } Assert.assertTrue(q.size() == 0); Assert.assertTrue(q.isEmpty()); }
public void pushSRI(StreamSRI header) { if (logger != null) { logger.trace("bulkio.InPort pushSRI ENTER (port=" + name + ")"); } synchronized (sriUpdateLock) { if (!currentHs.containsKey(header.streamID)) { if (logger != null) { logger.debug("pushSRI PORT:" + name + " NEW SRI:" + header.streamID); } if (sriCallback != null) { sriCallback.newSRI(header); } currentHs.put(header.streamID, new sriState(header, true)); if (header.blocking) { // If switching to blocking we have to set the semaphore synchronized (dataBufferLock) { if (!blocking) { try { queueSem.acquire(workQueue.size()); } catch (InterruptedException e) { e.printStackTrace(); } } blocking = true; } } } else { StreamSRI oldSri = currentHs.get(header.streamID).getSRI(); boolean cval = false; if (sri_cmp != null) { cval = sri_cmp.compare(header, oldSri); } if (cval == false) { if (sriCallback != null) { sriCallback.changedSRI(header); } this.currentHs.put(header.streamID, new sriState(header, true)); if (header.blocking) { // If switching to blocking we have to set the semaphore synchronized (dataBufferLock) { if (!blocking) { try { queueSem.acquire(workQueue.size()); } catch (InterruptedException e) { e.printStackTrace(); } } blocking = true; } } } } } if (logger != null) { logger.trace("bulkio.InPort pushSRI EXIT (port=" + name + ")"); } }
private void provaCoaArrayDeque() { ArrayDeque<String> array = new ArrayDeque<>(); System.out.println("EMPTY? " + array.isEmpty()); for (int comptador = 0; comptador < 10; comptador++) { array.add(comptador + ""); } System.out.println("EMPTY? " + array.isEmpty()); System.out.println("Total? " + array.size()); System.out.println(array.remove()); System.out.println("Total? " + array.size()); System.out.println(array.element()); array.clear(); System.out.println("Total? " + array.size()); }
@Test public void testBlockUnblock() throws Exception { JID connJid = JID.jidInstanceNS("[email protected]/test-111"); JID userJid = JID.jidInstanceNS("[email protected]/res-1"); XMPPResourceConnection sess = getSession(connJid, userJid); String blockJid = "*****@*****.**"; checkPrivacyJidBlocked(sess, blockJid, false); List<String> blocked = getBlocked(sess); assertTrue(blocked == null || blocked.isEmpty()); block(sess, blockJid); assertEquals(2, results.size()); privacy.filter(null, sess, null, results); assertEquals(2, results.size()); Packet result = results.poll(); assertNotNull(result); assertEquals(Iq.ELEM_NAME, result.getElemName()); assertEquals(StanzaType.result, result.getType()); result = results.poll(); assertNotNull(result); assertEquals(Iq.ELEM_NAME, result.getElemName()); assertEquals(StanzaType.set, result.getType()); checkPrivacyJidBlocked(sess, blockJid, true); blocked = getBlocked(sess); assertTrue(blocked.contains(blockJid)); unblock(sess, blockJid); assertEquals(2, results.size()); privacy.filter(null, sess, null, results); assertEquals(2, results.size()); result = results.poll(); assertNotNull(result); assertEquals(Iq.ELEM_NAME, result.getElemName()); assertEquals(StanzaType.result, result.getType()); result = results.poll(); assertNotNull(result); assertEquals(Iq.ELEM_NAME, result.getElemName()); assertEquals(StanzaType.set, result.getType()); checkPrivacyJidBlocked(sess, blockJid, false); blocked = getBlocked(sess); assertTrue(blocked == null || blocked.isEmpty()); }
@Override public void onNotify(ActionValueNotifierClient source, ActionValueEvent notification) { L.d(notification.toString()); queue.add(new ActionNotification(source, notification)); if (queue.size() == 1 && !jobRunning) Synapse.handler.post(dequeJob); }
@Override public void render(float delta) { super.render(delta); int nextNodeIndex = -1; // prepare text kApplication.spriteBatch().begin(); { this.background.draw(kApplication.spriteBatch()); } kApplication.spriteBatch().end(); this.chessboard_renderer_.begin(); { nextNodeIndex = game_path_.peek().render(region_of_interest_); } this.chessboard_renderer_.end(); kApplication.spriteBatch().begin(); { hud.render(kApplication.spriteBatch(), delta); } kApplication.spriteBatch().end(); if (nextNodeIndex > -1) { if (game_path_.size() > 1) { // Cull grandchildren to deallocate memory GraphSquare cur_top = game_path_.pop(); game_path_.peek().CullGrandChildrenExcept(cur_top); game_path_.push(cur_top); } this.region_of_interest_.Reconstrain( game_path_.peek().getChildVirtualPosition(nextNodeIndex)); game_path_.push(game_path_.peek().getChildNode(nextNodeIndex)); this.hud.pushMove(this.game_path_.peek().toString()); } else if (game_path_.size() > 1 && this.region_of_interest_.ZoomOutRequired()) { GraphSquare previous = game_path_.pop(); region_of_interest_.Deconstrain( game_path_.peek().getChildVirtualPosition(game_path_.peek().getChildIndex(previous))); this.hud.popMove(); } }
private boolean parseMtdt(BoxHeader header) { // if mCurrentBoxSequence contains trak, then add metadata to current // track // else metadata is for file // we're currently not interested in anything on track level try { int numberOfUnits = mDataSource.readShort(); mHmmpTitles = new ArrayList<>(1); ArrayDeque<String> titleLanguages = new ArrayDeque<>(1); ArrayDeque<String> iconLanguages = new ArrayDeque<>(1); for (int i = 0; i < numberOfUnits; i++) { short dataUnitSize = mDataSource.readShort(); int dataTypeID = mDataSource.readInt(); short language = mDataSource.readShort(); char l1 = Character.toChars(((language >> 10) & 0x1F) + 96)[0]; char l2 = Character.toChars(((language >> 5) & 0x1F) + 96)[0]; char l3 = Character.toChars(((language) & 0x1F) + 96)[0]; String languageString = "" + l1 + l2 + l3; short encodingType = mDataSource.readShort(); if (encodingType == 0x01) { byte[] metadata = new byte[dataUnitSize - 10]; mDataSource.read(metadata); String metadataString = new String(metadata, "UTF-16BE").trim(); if ((dataTypeID & 0xFFFF) == 0x01) { mHmmpTitles.add(metadataString); titleLanguages.add(languageString); } } else if (encodingType == 0x101) { if (dataTypeID == 0xA04) { if (mIconList == null) { mIconList = new ArrayList<>(); } mDataSource.skipBytes(4); // selectionFlags mDataSource.skipBytes(4); // reserved int artworkCount = mDataSource.readInt(); for (int j = 0; j < artworkCount; j++) { IconInfo iconInfo = new IconInfo(); iconInfo.mtsmId = mDataSource.readInt(); iconInfo.mdstIndex = mDataSource.readInt(); iconInfo.languageIndex = iconLanguages.size(); mDataSource.skipBytes(4); mIconList.add(iconInfo); } iconLanguages.add(languageString); } } } addMetaDataValue(KEY_HMMP_TITLE_LANGUAGES, titleLanguages.toArray()); addMetaDataValue(KEY_HMMP_ICON_LANGUAGES, iconLanguages.toArray()); } catch (EOFException e) { if (LOGS_ENABLED) Log.e(TAG, "Exception while reading from 'MTDT' box", e); return false; } catch (IOException e) { if (LOGS_ENABLED) Log.e(TAG, "Exception while reading from 'MTDT' box", e); return false; } return true; }
/** * The maximum number of {@link LoggingEvent}s to hold in the buffer. When this size is reached * older {@link LoggingEvent}s are dropped for new ones (FIFO) * * <p>Usually called by the log4j framework: eg. <code>log4j.appender.InMem.Capacity=1000</code> * * <p>Defaults to 1000 if not set * * @param capacity the number of {@link LoggingEvent}s to hold in the buffer. */ public void setCapacity(int capacity) { synchronized (bufferLock) { if (buffer.size() > capacity) { throw new IllegalArgumentException("Can't set capacity to less than current buffer size"); } else { this.capacity = capacity; } } }
/* * (non-Javadoc) * * @see * org.apache.log4j.AppenderSkeleton#append(org.apache.log4j.spi.LoggingEvent * ) */ @Override protected void append(LoggingEvent loggingEvent) { synchronized (bufferLock) { if (buffer.size() == capacity) { buffer.poll(); } buffer.offer(loggingEvent); } }
public Clause createClause(DPLLEngine engine) { assert (mAnnotationStack.size() == 1); LAAnnotation baseAnnotation = mAnnotationStack.getLast(); Literal[] lits = baseAnnotation.collectLiterals(); Clause clause = new Clause(lits); if (engine.isProofGenerationEnabled()) { clause.setProof(new LeafNode(LeafNode.THEORY_LA, baseAnnotation)); } assert validClause(); return clause; }
public PortUsageType state() { int queueSize = 0; synchronized (dataBufferLock) { queueSize = workQueue.size(); if (queueSize == maxQueueDepth) { return PortUsageType.BUSY; } else if (queueSize == 0) { return PortUsageType.IDLE; } return PortUsageType.ACTIVE; } }
public static Vector<ArrayDeque<BaseVertex>> getMaxIndependentSet(GraphModel graph) { Partitioner p = new Partitioner(graph); MaxIndSetSubSetListener l = new MaxIndSetSubSetListener(); p.findAllSubsets(l); Vector<ArrayDeque<BaseVertex>> ret = new Vector<ArrayDeque<BaseVertex>>(); for (ArrayDeque<BaseVertex> set : l.maxsets) { if (set.size() == l.max) { ret.add(set); } } return ret; }
public synchronized void dump(PrintWriter pw, String indent, DumpFilter filter) { if (ENABLE_AGGREGATED_IN_MEMORY_STATS) { for (AggregatedStats as : mStats.values()) { if (filter != null && !filter.matches(as.key)) continue; as.dump(pw, indent); } pw.println(indent + "mStatsArrays.size(): " + mStatsArrays.size()); } if (ENABLE_SQLITE_LOG) { mSQLiteLog.dump(pw, indent, filter); } }
public Main() { try { BufferedReader in; in = new BufferedReader(new InputStreamReader(System.in)); // Used for CCC int numLights = Integer.parseInt(in.readLine()); int[] states = new int[numLights]; for (int i = 0; i < numLights; i++) { states[i] = Integer.parseInt(in.readLine()); } ArrayDeque<Scenario> Q = new ArrayDeque<Scenario>(); HashMap<String, Integer> dp = new HashMap<String, Integer>(); int moves = 0; Q.addLast(new Scenario(states)); while (!Q.isEmpty()) { int size = Q.size(); for (int q = 0; q < size; q++) { Scenario temp = Q.removeFirst(); if (isEmpty(temp.states)) { System.out.println(moves); return; } else { for (int i = 0; i < temp.states.length; i++) { if (temp.states[i] == 0) { int[] newArr = Arrays.copyOf(temp.states, temp.states.length); newArr[i] = 1; newArr = fixArray(newArr); String arr = ""; for (int p = 0; p < newArr.length; p++) arr += newArr[p]; if (dp.get(arr) == null) { dp.put(arr, moves); Q.addLast(new Scenario(newArr)); } else { int val = dp.get(arr); if (val != 0 && moves < val) { dp.put(arr, moves); Q.addLast(new Scenario(newArr)); } } // outputArr(newArr); } } } } moves++; } } catch (IOException e) { System.out.println("IO: General"); } }
@Override public boolean addItem(Item it) throws Exception { if (itemList.size() < maxItemCnt) { if (it.getProperties().toLowerCase().contains("плоский")) { maxItemCnt += 1; return super.addItem(it); // To change body of generated methods, choose Tools | Templates. } else { throw new ItemStoreException("в стопку можно добавлять только плоские предметы"); } } else { throw new ItemStoreException( "в эту стопку нельзя складывать больше " + maxItemCnt + " предмета(ов)"); } }
public void doControl() { if (!isDone.getBooleanValue()) hasAborted.set(currentTask.abortRequested()); if (!hasAborted.getBooleanValue()) { handleTransitions(); numberOfTasksRemaining.set(taskQueue.size()); isDone.set(isDone()); if (!isDone.getBooleanValue()) { timeInCurrentTask.set(yoTime.getDoubleValue() - switchTime.getDoubleValue()); currentTask.doAction(); } } }
public MySqlRequest queRequest(MySqlRequest request) { synchronized (lock) { int requestsPending = requestQueue.size(); if (requestsPending > maxQueueSize) { throw new DbException( "To many pending requests. The current maximum is " + maxQueueSize + "." + "Ensure that your not overloading the database with requests. " + "Also check the " + StandardProperties.MAX_QUEUE_LENGTH + " property"); } return forceQueRequest(request); } }
public VoltTable nextDependency(final int dependencyId) { // this formulation retains an arraydeque in the tracker that is // overwritten by the next transaction using this dependency id. If // the EE requests all dependencies (as is expected), the deque // will not retain any references to VoltTables (which is the goal). final ArrayDeque<VoltTable> vtstack = m_depsById.get(dependencyId); if (vtstack != null && vtstack.size() > 0) { // java doc. says this amortized constant time. return vtstack.pop(); } else if (vtstack == null) { assert (false) : "receive without associated tracked dependency."; return null; } else { return null; } }
private boolean validClause() { if (mAnnotationStack == null) return true; assert (mAnnotationStack.size() == 1); MutableAffinTerm mat = mAnnotationStack.getFirst().addLiterals(); assert (mat.isConstant() && InfinitNumber.ZERO.less(mat.getConstant())); for (Map.Entry<LAReason, LAAnnotation> reasonEntry : mSubReasons.entrySet()) { LAReason reason = reasonEntry.getKey(); mat = reasonEntry.getValue().addLiterals(); Rational coeff = reason.isUpper() ? Rational.MONE : Rational.ONE; mat.add(coeff, reason.getVar()); mat.add(reason.getBound().mul(coeff.negate())); mat.add(reason.getVar().getEpsilon()); assert (mat.isConstant() && InfinitNumber.ZERO.less(mat.getConstant())); } return true; }
private void replenishAdQueue() { if (AD_QUEUE.size() < PREFETCHED_ADS_SIZE && mFetchFailCount < MAX_FETCH_ATTEMPT && mFetchSucceedCount < MAX_ADS_TO_FETCH) { mIsCurrentlyFetching = true; Context context = mContextReference.get(); mCurrentFlurryAdNative = new FlurryAdNative(context, mAdSpaceName); if (mFlurryAdTargeting != null) { mCurrentFlurryAdNative.setTargeting(mFlurryAdTargeting); } mCurrentFlurryAdNative.setListener(internalListener); mCurrentFlurryAdNative.fetchAd(); } else { mIsCurrentlyFetching = false; } }
private List<String> getBlocked(XMPPResourceConnection sess) throws XMPPException, TigaseStringprepException { Element iq = new Element("iq", new String[] {"type"}, new String[] {"get"}); Element blocklist = new Element("blocklist", new String[] {"xmlns"}, new String[] {BlockingCommand.XMLNS}); iq.addChild(blocklist); Packet p = Packet.packetInstance(iq); blockingCommand.process(p, sess, null, results, null); assertEquals(1, results.size()); Packet result = results.poll(); assertEquals(Iq.ELEM_NAME, result.getElemName()); return result .getElement() .getChild("blocklist") .mapChildren(c -> c.getName() == "item", c -> c.getAttributeStaticStr("jid")); }
void queRequest(Request request) { synchronized (lock) { int requestsPending = requestQueue.size() + ((null != blockingRequest) ? blockingRequest.waitingRequests.size() : 0); if (requestsPending > maxQueueSize) { throw new DbException( "To many pending requests. The current maximum is " + maxQueueSize + "." + "Ensure that your not overloading the database with requests. " + "Also check the " + StandardProperties.MAX_QUEUE_LENGTH + " property"); } forceQueRequest(request); } }
@Override public void endFunction() throws SAXPathException { ArrayDeque params = popFrame(); javax.xml.namespace.QName name = (javax.xml.namespace.QName) params.pollFirst(); if (name.getNamespaceURI().length() == 0) push(createFunction(name.getLocalPart(), params).simplify()); else { int noOfParams = params.size(); XPathFunction function = functionResolver.resolveFunction(name, noOfParams); if (function == null) throw new SAXPathException("Unknown Function: " + name); FunctionCall functionCall = new FunctionCall( new Functions.UserFunction(name.getNamespaceURI(), name.getLocalPart(), function), noOfParams); for (int i = 0; i < noOfParams; i++) functionCall.addMember(params.pollFirst(), i); push(functionCall); } }
public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> r = new ArrayList<List<Integer>>(); ArrayDeque<TreeNode> q = new ArrayDeque<TreeNode>(); if (root == null) return r; q.offer(root); boolean reversedOrder = false; while (!q.isEmpty()) { int len = q.size(); List<Integer> level = new LinkedList<Integer>(); for (int i = 0; i < len; i++) { TreeNode n = q.poll(); if (reversedOrder) level.add(0, n.val); else level.add(n.val); if (n.left != null) q.offer(n.left); if (n.right != null) q.offer(n.right); } r.add(level); reversedOrder = !reversedOrder; } return r; }
void handleWorkUnitComplete(WorkUnit w) { for (int depId : w.getDependencyIds()) { m_missingDependencies.remove(depId); } // slide this new stack frame drop into the right position // (before any other stack frame drops) if ((w.shouldResumeProcedure()) && (m_readyWorkUnits.peekLast() != null) && (m_readyWorkUnits.peekLast().shouldResumeProcedure())) { ArrayDeque<WorkUnit> deque = new ArrayDeque<WorkUnit>(); while ((m_readyWorkUnits.peekLast() != null) && (m_readyWorkUnits.peekLast().shouldResumeProcedure())) { deque.add(m_readyWorkUnits.pollLast()); } deque.add(w); while (deque.size() > 0) m_readyWorkUnits.add(deque.pollLast()); } else { m_readyWorkUnits.add(w); } }
public Serializer serialize(RemoteEvent event) throws IOException { synchronized (lock) { if (writer == null) { throw new IOException("Serializer already closed."); } // An alternative way of solving GH-92 and GH-110. Instead of buffering // serialized json we emit directly. If a recursive call occurs to serialize() // we enqueue the event and continue, serializing them in order. events.addLast(event); if (events.size() > 1) { // SlaveMain.warn("Serializing " + event.getType() + " (postponed, " + events.size() + " in // queue)", null); return this; } // SlaveMain.warn("Serializing " + event.getType(), null); flushQueue(); return this; } }