Ejemplo n.º 1
0
 public void forceQueRequest(Request request) {
   synchronized (lock) {
     if (blockingRequest == null) {
       requestQueue.add(request);
       channel.writeAndFlush(request.getRequest());
       if (request.isBlocking()) {
         blockingRequest = new BlockingRequestInProgress(request);
         request
             .getToComplete()
             .addListener(
                 new DbListener<Object>() {
                   @Override
                   public void onCompletion(DbFuture<Object> future) {
                     blockingRequest.continueWithRequests();
                   }
                 });
       }
     } else {
       if (blockingRequest.unblockBy(request)) {
         requestQueue.add(request);
         channel.writeAndFlush(request.getRequest());
       } else {
         blockingRequest.add(request);
       }
     }
   }
 }
Ejemplo n.º 2
0
  public int numIslands(char[][] grid) {
    int counter = 0;
    int n = grid.length;
    if (n == 0) return 0;
    int m = grid[0].length;
    if (m == 0) return 0;
    int[][] direct = new int[][] {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        if (grid[i][j] == '1') {
          counter++;
          ArrayDeque<Integer> q = new ArrayDeque<Integer>();
          grid[i][j] = 0;
          q.add(i);
          q.add(j);
          while (!q.isEmpty()) {
            int r = q.poll();
            int c = q.poll();
            for (int[] d : direct) {
              int rr = d[0] + r;
              int cc = d[1] + c;
              if (rr >= 0 && rr < n && cc >= 0 && cc < m && grid[rr][cc] == '1') {
                grid[rr][cc] = 0;
                q.add(rr);
                q.add(cc);
              }
            }
          }
        }
      }
    }
    return counter;
  }
Ejemplo n.º 3
0
  void analyzeWhereExpression() {

    // nothing to do if there's no where expression
    if (where == null) return;

    // this first chunk of code breaks the code into a list of expression that
    // all have to be true for the where clause to be true

    ArrayDeque<AbstractExpression> in = new ArrayDeque<AbstractExpression>();
    ArrayDeque<AbstractExpression> out = new ArrayDeque<AbstractExpression>();
    in.add(where);

    AbstractExpression inExpr = null;
    while ((inExpr = in.poll()) != null) {
      if (inExpr.getExpressionType() == ExpressionType.CONJUNCTION_AND) {
        in.add(inExpr.getLeft());
        in.add(inExpr.getRight());
      } else {
        out.add(inExpr);
      }
    }

    // the where selection list contains all the clauses
    whereSelectionList.addAll(out);
    this.analyzeWhereExpression(whereSelectionList);
  }
Ejemplo n.º 4
0
  public void testFlatten() {
    // test many arrays
    EventBean[] testEvents =
        makeEventArray(new String[] {"a1", "a2", "b1", "b2", "b3", "c1", "c2"});
    ArrayDeque<EventBean[]> eventVector = new ArrayDeque<EventBean[]>();
    eventVector.add(new EventBean[] {testEvents[0], testEvents[1]});
    eventVector.add(new EventBean[] {testEvents[2]});
    eventVector.add(new EventBean[] {testEvents[3], testEvents[4], testEvents[5]});
    eventVector.add(new EventBean[] {testEvents[6]});

    EventBean[] events = EventBeanUtility.flatten(eventVector);
    assertEquals(7, events.length);
    for (int i = 0; i < testEvents.length; i++) {
      assertEquals(events[i], testEvents[i]);
    }

    // test just one array
    eventVector.clear();
    eventVector.add(new EventBean[] {testEvents[2]});
    events = EventBeanUtility.flatten(eventVector);
    assertEquals(events[0], testEvents[2]);

    // test empty vector
    eventVector.clear();
    events = EventBeanUtility.flatten(eventVector);
    assertNull(events);
  }
Ejemplo n.º 5
0
 public SNode createNode(@Nullable int... childrenAtLevel) {
   ArrayDeque<SNode> thisLevel = new ArrayDeque<SNode>();
   ArrayDeque<SNode> nextLevel = new ArrayDeque<SNode>();
   final SNode top = new jetbrains.mps.smodel.SNode(ourConcept);
   thisLevel.add(top);
   if (childrenAtLevel == null || childrenAtLevel.length == 0) {
     return top;
   }
   for (int count : childrenAtLevel) {
     while (!thisLevel.isEmpty()) {
       SNode parent = thisLevel.removeFirst();
       for (int i = 0; i < count; i++) {
         SNode c = new jetbrains.mps.smodel.SNode(ourConcept);
         final String v = nextNodeName(i + 1);
         c.setProperty(SNodeUtil.property_INamedConcept_name, v);
         c.setProperty(SNodeUtil.property_BaseConcept_alias, v);
         parent.addChild(ourRole, c);
         nextLevel.add(c);
       }
     }
     ArrayDeque<SNode> t = thisLevel;
     thisLevel = nextLevel;
     nextLevel = t;
   }
   return top;
 }
  public ArrayDeque shunting(ArrayDeque<Token> infix) throws IOException {
    operatorStack = new Stack<Character>();
    postfixDeque = new ArrayDeque<String>();

    while (!infix.isEmpty()) {
      Token token = infix.poll();
      if (token.type == "OPERATOR") {
        processOperator((token.data).charAt(0));
      } else if (token.type == "SIN") {
        // TODO: This is kind of a weird place to put this... should be delegated to a more generic
        // method.
        String d = "";
        Pattern pattern = Pattern.compile("([-]?[0-9.]+)");
        Matcher matcher = pattern.matcher(token.data);
        while (matcher.find()) {
          d = matcher.group(1);
        }
        processOperator('s'); // 's' will be sin function.
        postfixDeque.add(d);
      } else {
        postfixDeque.add(token.data);
      }
    }
    // Pop any remaining operators and
    // append them to postfix.
    while (!operatorStack.empty()) {
      char op = operatorStack.pop();
      postfixDeque.add(String.valueOf(op));
    }
    return postfixDeque;
  }
 private void processOperator(char op) {
   if (operatorStack.empty()) {
     operatorStack.push(op);
   } else {
     char topOp = operatorStack.peek();
     if (op == '(') {
       operatorStack.push(op);
     } else if ((topOp == '(' || precedence(op) > precedence(topOp)) && op != ')') {
       operatorStack.push(op);
     } else if (op == ')') {
       while (topOp != '(') {
         operatorStack.pop();
         postfixDeque.add(String.valueOf(topOp));
         if (!operatorStack.empty()) {
           topOp = operatorStack.peek();
         }
       }
       operatorStack.pop(); // removes the right parenthesis
     } else {
       // Pop all stacked operators with equal
       // or higher precedence than op.
       while (!operatorStack.empty() && precedence(op) <= precedence(topOp) && topOp != '(') {
         operatorStack.pop();
         postfixDeque.add(String.valueOf(topOp));
         if (!operatorStack.empty()) {
           // Reset topOp.
           topOp = operatorStack.peek();
         }
       }
       operatorStack.push(op);
     }
   }
 }
 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;
 }
Ejemplo n.º 9
0
 protected static Object addUpgradeToDequeIfPopulated(Object holder, EventBean theEvent) {
   if (holder == null) {
     return theEvent;
   } else if (holder instanceof Deque) {
     Deque<EventBean> deque = (Deque<EventBean>) holder;
     deque.add(theEvent);
     return deque;
   } else {
     ArrayDeque<EventBean> deque = new ArrayDeque<EventBean>(4);
     deque.add((EventBean) holder);
     deque.add(theEvent);
     return deque;
   }
 }
Ejemplo n.º 10
0
 //    private void setOverlapFilterCallback() {
 //        OverlapFilterCallback callback = new OverlapFilterCallback() {
 //
 //            public boolean needBroadphaseCollision(BroadphaseProxy bp, BroadphaseProxy bp1) {
 //                boolean collides = (bp.collisionFilterGroup & bp1.collisionFilterMask) != 0;
 //                if (collides) {
 //                    collides = (bp1.collisionFilterGroup & bp.collisionFilterMask) != 0;
 //                }
 //                if (collides) {
 //                    assert (bp.clientObject instanceof
 // com.bulletphysics.collision.dispatch.CollisionObject && bp.clientObject instanceof
 // com.bulletphysics.collision.dispatch.CollisionObject);
 //                    com.bulletphysics.collision.dispatch.CollisionObject colOb =
 // (com.bulletphysics.collision.dispatch.CollisionObject) bp.clientObject;
 //                    com.bulletphysics.collision.dispatch.CollisionObject colOb1 =
 // (com.bulletphysics.collision.dispatch.CollisionObject) bp1.clientObject;
 //                    assert (colOb.getUserPointer() != null && colOb1.getUserPointer() != null);
 //                    PhysicsCollisionObject collisionObject = (PhysicsCollisionObject)
 // colOb.getUserPointer();
 //                    PhysicsCollisionObject collisionObject1 = (PhysicsCollisionObject)
 // colOb1.getUserPointer();
 //                    if ((collisionObject.getCollideWithGroups() &
 // collisionObject1.getCollisionGroup()) > 0
 //                            || (collisionObject1.getCollideWithGroups() &
 // collisionObject.getCollisionGroup()) > 0) {
 //                        PhysicsCollisionGroupListener listener =
 // collisionGroupListeners.get(collisionObject.getCollisionGroup());
 //                        PhysicsCollisionGroupListener listener1 =
 // collisionGroupListeners.get(collisionObject1.getCollisionGroup());
 //                        if (listener != null) {
 //                            return listener.collide(collisionObject, collisionObject1);
 //                        } else if (listener1 != null) {
 //                            return listener1.collide(collisionObject, collisionObject1);
 //                        }
 //                        return true;
 //                    } else {
 //                        return false;
 //                    }
 //                }
 //                return collides;
 //            }
 //        };
 //        dynamicsWorld.getPairCache().setOverlapFilterCallback(callback);
 //    }
 //    private void setTickCallback() {
 //        final PhysicsSpace space = this;
 //        InternalTickCallback callback2 = new InternalTickCallback() {
 //
 //            @Override
 //            public void internalTick(DynamicsWorld dw, float f) {
 //                //execute task list
 //                AppTask task = pQueue.poll();
 //                task = pQueue.poll();
 //                while (task != null) {
 //                    while (task.isCancelled()) {
 //                        task = pQueue.poll();
 //                    }
 //                    try {
 //                        task.invoke();
 //                    } catch (Exception ex) {
 //                        logger.log(Level.SEVERE, null, ex);
 //                    }
 //                    task = pQueue.poll();
 //                }
 //                for (Iterator<PhysicsTickListener> it = tickListeners.iterator(); it.hasNext();)
 // {
 //                    PhysicsTickListener physicsTickCallback = it.next();
 //                    physicsTickCallback.prePhysicsTick(space, f);
 //                }
 //            }
 //        };
 //        dynamicsWorld.setPreTickCallback(callback2);
 //        InternalTickCallback callback = new InternalTickCallback() {
 //
 //            @Override
 //            public void internalTick(DynamicsWorld dw, float f) {
 //                for (Iterator<PhysicsTickListener> it = tickListeners.iterator(); it.hasNext();)
 // {
 //                    PhysicsTickListener physicsTickCallback = it.next();
 //                    physicsTickCallback.physicsTick(space, f);
 //                }
 //            }
 //        };
 //        dynamicsWorld.setInternalTickCallback(callback, this);
 //    }
 //    private void setContactCallbacks() {
 //        BulletGlobals.setContactAddedCallback(new ContactAddedCallback() {
 //
 //            public boolean contactAdded(ManifoldPoint cp,
 // com.bulletphysics.collision.dispatch.CollisionObject colObj0,
 //                    int partId0, int index0,
 // com.bulletphysics.collision.dispatch.CollisionObject colObj1, int partId1,
 //                    int index1) {
 //                System.out.println("contact added");
 //                return true;
 //            }
 //        });
 //
 //        BulletGlobals.setContactProcessedCallback(new ContactProcessedCallback() {
 //
 //            public boolean contactProcessed(ManifoldPoint cp, Object body0, Object body1) {
 //                if (body0 instanceof CollisionObject && body1 instanceof CollisionObject) {
 //                    PhysicsCollisionObject node = null, node1 = null;
 //                    CollisionObject rBody0 = (CollisionObject) body0;
 //                    CollisionObject rBody1 = (CollisionObject) body1;
 //                    node = (PhysicsCollisionObject) rBody0.getUserPointer();
 //                    node1 = (PhysicsCollisionObject) rBody1.getUserPointer();
 //
 // collisionEvents.add(eventFactory.getEvent(PhysicsCollisionEvent.TYPE_PROCESSED, node, node1,
 // cp));
 //                }
 //                return true;
 //            }
 //        });
 //
 //        BulletGlobals.setContactDestroyedCallback(new ContactDestroyedCallback() {
 //
 //            public boolean contactDestroyed(Object userPersistentData) {
 //                System.out.println("contact destroyed");
 //                return true;
 //            }
 //        });
 //    }
 private void addCollisionEvent_native(
     PhysicsCollisionObject node, PhysicsCollisionObject node1, long manifoldPointObjectId) {
   //        System.out.println("addCollisionEvent:"+node.getObjectId()+" "+ node1.getObjectId());
   collisionEvents.add(
       eventFactory.getEvent(
           PhysicsCollisionEvent.TYPE_PROCESSED, node, node1, manifoldPointObjectId));
 }
Ejemplo n.º 11
0
  /** Get a list of all the people that ignorer is ignoring */
  public static ArrayDeque<UUIDName> get_ignoring(UUID ignorer) {
    ArrayDeque<UUIDName> ret = null;
    try {
      String query = "SELECT * FROM ignores WHERE " + "ignorer = ?;";
      PreparedStatement st = conn.prepareStatement(query);
      st.setString(1, ignorer.toString());

      ResultSet rs = st.executeQuery();
      ret = new ArrayDeque<UUIDName>();
      while (rs.next()) {
        UUID uuid = UUID.fromString(rs.getString("ignored"));
        String name = rs.getString("ignoredname");

        UUIDName tmp = new UUIDName(uuid, name);
        ret.add(tmp);
      }

      rs.close();
      st.close();

    } catch (Exception e) {
      Ignore.instance.getLogger().warning(e.getMessage());
    }

    return ret;
  }
Ejemplo n.º 12
0
 public MySqlRequest forceQueRequest(MySqlRequest request) {
   synchronized (lock) {
     requestQueue.add(request);
     channel.write(request.getRequest());
     return request;
   }
 }
Ejemplo n.º 13
0
  @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);
  }
Ejemplo n.º 14
0
 public Explainer(LinArSolve solver, boolean generateProofTree, Literal explainedLiteral) {
   mSolver = solver;
   mExplainedLiteral = explainedLiteral;
   mSubReasons = new HashMap<LAReason, LAAnnotation>();
   mAnnotationStack = new ArrayDeque<LAAnnotation>();
   mAnnotationStack.add(new LAAnnotation());
 }
  @Override
  public void createLocalFragmentWork(FragmentTaskMessage task, boolean nonTransactional) {
    if (task.getFragmentCount() <= 0) return;

    WorkUnit w =
        new WorkUnit(
            m_site.getSiteTracker(),
            task,
            task.getAllUnorderedInputDepIds(),
            m_hsId,
            m_nonCoordinatingSites,
            false,
            m_allowMismatchedResults);
    w.nonTransactional = nonTransactional;

    for (int i = 0; i < task.getFragmentCount(); i++) {
      ArrayList<Integer> inputDepIds = task.getInputDepIds(i);
      if (inputDepIds == null) continue;
      for (int inputDepId : inputDepIds) {
        if (m_missingDependencies == null) m_missingDependencies = new HashMap<Integer, WorkUnit>();
        assert (!m_missingDependencies.containsKey(inputDepId));
        m_missingDependencies.put(inputDepId, w);
      }
    }

    if (w.allDependenciesSatisfied()) m_readyWorkUnits.add(w);
  }
Ejemplo n.º 16
0
 private void _submitQuery(WorkerRunnable runnable) {
   attachRunnable(runnable);
   synchronized (runQueue) {
     runQueue.add(runnable);
     runQueue.notify();
   }
 }
Ejemplo n.º 17
0
 synchronized void add(Chunk c) throws InterruptedException {
   int len = c.getData().length;
   if (BLOCK_WHEN_FULL) while (len + dataSizeBytes > maxDataSize) wait();
   else chunks.remove();
   dataSizeBytes += len;
   chunks.add(c);
 }
Ejemplo n.º 18
0
 /**
  * Add a single dependency. Exists only for test cases.
  *
  * @param depId
  * @param vt
  */
 void addDependency(final int depId, final VoltTable vt) {
   ArrayDeque<VoltTable> deque = m_depsById.get(depId);
   if (deque == null) {
     deque = new ArrayDeque<VoltTable>();
     m_depsById.put(depId, deque);
   }
   deque.add(vt);
 }
Ejemplo n.º 19
0
    TreeRangeIterator(MerkleTree tree, Range range) {
      Token mintoken = tree.partitioner().getMinimumToken();
      tovisit = new ArrayDeque<TreeRange>();
      tovisit.add(new TreeRange(tree, mintoken, mintoken, (byte) 0, tree.root));

      this.tree = tree;
      this.range = range;
    }
Ejemplo n.º 20
0
  @Override
  public void init(Graph graph, Node start, Node goal) {
    this.graph = graph;
    this.start = start;
    this.goal = goal;
    this.isRunning = true;

    openedList.add(start);
  }
  private Collection<SchemaTypeInfo> gatherInheritors(XmlTagImpl xml) {
    XmlAttribute name = getNameAttr(xml);
    if (name == null || StringUtil.isEmptyOrSpaces(name.getValue())) return null;
    String localName = name.getValue();
    final boolean hasPrefix = localName.contains(":");
    localName = hasPrefix ? localName.substring(localName.indexOf(':') + 1) : localName;
    final String nsPrefix =
        hasPrefix ? name.getValue().substring(0, name.getValue().indexOf(':')) : null;

    final XmlFile file = XmlUtil.getContainingFile(xml);
    if (file == null) return null;
    final Project project = file.getProject();
    if (project == null) return null;

    final Set<SchemaTypeInfo> result = new HashSet<SchemaTypeInfo>();
    final ArrayDeque<SchemaTypeInfo> queue = new ArrayDeque<SchemaTypeInfo>();

    String nsUri;
    if (!hasPrefix) {
      nsUri = getDefaultNs(file);
    } else {
      nsUri = XmlUtil.findNamespaceByPrefix(nsPrefix, file.getRootTag());
    }
    if (nsUri == null) return null;

    queue.add(new SchemaTypeInfo(localName, true, nsUri));

    final PairConvertor<String, String, List<Set<SchemaTypeInfo>>> worker =
        SchemaTypeInheritanceIndex.getWorker(project, file.getContainingFile().getVirtualFile());
    while (!queue.isEmpty()) {
      final SchemaTypeInfo info = queue.removeFirst();
      final List<Set<SchemaTypeInfo>> childrenOfType =
          worker.convert(info.getNamespaceUri(), info.getTagName());
      for (Set<SchemaTypeInfo> infos : childrenOfType) {
        for (SchemaTypeInfo typeInfo : infos) {
          if (typeInfo.isIsTypeName()) {
            queue.add(typeInfo);
          }
          result.add(typeInfo);
        }
      }
    }
    return result;
  }
  @Override
  public boolean doWork(boolean rejoining) {
    if (rejoining && (m_rejoinState == RejoinState.NORMAL)) {
      m_rejoinState = RejoinState.REJOINING;
      if (!m_isReadOnly) {
        m_loggedFragments =
            new FragmentTaskLogMessage(
                m_notice.getInitiatorHSId(), m_notice.getCoordinatorHSId(), m_notice.getTxnId());
        assert (m_loggedFragments.getTxnId() == getNotice().getTxnId());
      }
    }

    if (!m_hasStartedWork) {
      m_site.beginNewTxn(this);
      m_hasStartedWork = true;
    }

    if (m_done) {
      return true;
    }

    while (!isBlocked()) {
      WorkUnit wu = m_readyWorkUnits.poll();
      if (wu.shouldResumeProcedure()) {
        assert (m_stackFrameDropWUs != null);
        m_stackFrameDropWUs.remove(wu);

        m_shouldResumeProcedure = true;
        m_previousStackFrameDropDependencies = wu.getDependencies();

        for (WorkUnit sfd : m_stackFrameDropWUs) {
          sfd.m_stackCount--;
          if (sfd.allDependenciesSatisfied()) {
            m_readyWorkUnits.add(sfd);
          }
        }

        return m_done;
      }

      VoltMessage payload = wu.getPayload();

      if (payload instanceof InitiateTaskMessage) {
        initiateProcedure((InitiateTaskMessage) payload);
      } else if (payload instanceof FragmentTaskMessage) {
        if ((m_rejoinState == RejoinState.REJOINING) && (wu.nonTransactional == false)) {
          processRejoiningFragmentWork((FragmentTaskMessage) payload, wu.getDependencies());
        } else {
          // when recovering, still do non-transactional work
          processFragmentWork((FragmentTaskMessage) payload, wu.getDependencies());
        }
      }
    }

    return m_done;
  }
Ejemplo n.º 23
0
 /** 广度优先遍历 采用非递归实现 需要辅助数据结构:队列 */
 public void levelOrderTraversal() {
   if (root == null) {
     System.out.println("empty tree");
     return;
   }
   ArrayDeque<TreeNode> queue = new ArrayDeque<TreeNode>();
   queue.add(root);
   while (queue.isEmpty() == false) {
     TreeNode node = queue.remove();
     System.out.print(node.value + "    ");
     if (node.left != null) {
       queue.add(node.left);
     }
     if (node.right != null) {
       queue.add(node.right);
     }
   }
   System.out.print("\n");
 }
Ejemplo n.º 24
0
 private void updateState(String newMap) {
   for (int i = 0, j = 0; i < newMap.length(); i++, j = i / size) {
     raw[i % size][j] = newMap.charAt(i);
     ElementType type = ElementType.parseChar(newMap.charAt(i));
     Element el;
     if (type == ElementType.ME) {
       me = new Tank(ElementType.ME, i % size, j);
       el = me;
     } else if (type == ElementType.TANK) {
       el = new Tank(ElementType.TANK, i % size, j);
       actors.add((Actor) el);
     } else if (type == ElementType.SHELL) {
       el = new Shell(i % size, j);
       actors.add((Actor) el);
     } else {
       el = new Element(type);
     }
     map[i % size][j] = el;
   }
 }
 private long testingArrayDeque() {
   ArrayDeque<Object> array = new ArrayDeque<Object>();
   long start = System.currentTimeMillis();
   for (int i = 0; i < getMax(); i++) {
     array.add(i);
   }
   long end = System.currentTimeMillis();
   long time = (end - start);
   refreshTotalTime(time);
   return time;
 }
Ejemplo n.º 26
0
Archivo: A.java Proyecto: t8m8/AtCoder
  static void solve() {
    int r = in.nextInt();
    int c = in.nextInt();
    int sy = in.nextInt() - 1;
    int sx = in.nextInt() - 1;
    int gy = in.nextInt() - 1;
    int gx = in.nextInt() - 1;
    char[][] t = new char[r][c];
    for (int i = 0; i < r; i++) {
      t[i] = in.next().toCharArray();
    }

    ArrayDeque<int[]> que = new ArrayDeque<>();
    BitSet visited = new BitSet();

    que.add(new int[] {sy, sx, 0});
    visited.set(sy * c + sx);

    int[] dx = {0, 1, 0, -1};
    int[] dy = {1, 0, -1, 0};
    int[][] dist = new int[r][c];

    while (!que.isEmpty()) {
      int[] p = que.pollFirst();
      int cy = p[0];
      int cx = p[1];
      int d = p[2];
      dist[cy][cx] = d;

      for (int i = 0; i < 4; i++) {
        int ny = cy + dy[i];
        int nx = cx + dx[i];
        if (ny < 0 || nx < 0 || r <= ny || c <= nx) continue;
        if (visited.get(ny * c + nx) || t[ny][nx] == '#') continue;
        que.add(new int[] {ny, nx, d + 1});
        visited.set(ny * c + nx);
      }
    }

    out.println(dist[gy][gx]);
  }
  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);
    }
  }
Ejemplo n.º 28
0
 public static String create_string(DFA_Node head) {
   String transitions;
   ArrayDeque<DFA_Node> temp_stack = new ArrayDeque<DFA_Node>();
   Set<DFA_Node> temp_set2 = new HashSet<DFA_Node>();
   temp_stack.add(head);
   temp_set2.add(head);
   while (!temp_stack.isEmpty()) {
     DFA_Node current = temp_stack.pop();
     for (String character : Regex.character_set_test) {}
   }
   return null;
 }
Ejemplo n.º 29
0
  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());
  }
Ejemplo n.º 30
0
 @Command(
     aliases = "npc",
     usage = "set [text]",
     desc = "set the text of an NPC",
     modifiers = "set",
     min = 2)
 @CommandPermissions("basic.modify.settext")
 public static void set(CommandContext args, Player player, HumanNPC npc) {
   String text = args.getJoinedStrings(1);
   ArrayDeque<String> texts = new ArrayDeque<String>();
   texts.add(text);
   NPCDataManager.setText(npc.getUID(), texts);
   player.sendMessage(
       StringUtils.wrapFull("{" + npc.getName() + "}'s text was set to {" + text + "}."));
 }