public static TreeNode buildTree(int[] preorder, int[] inorder) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    if (inorder.length == 0) return null;
    int value = preorder[0];
    TreeNode root = new TreeNode(value);
    int pos = 0;
    while (inorder[pos] != value) {
      pos++;
    }

    TreeNode left;
    TreeNode right;
    int[] emp = {};
    if (pos == 0) left = buildTree(emp, emp);
    else
      left =
          buildTree(Arrays.copyOfRange(preorder, 1, pos + 1), Arrays.copyOfRange(inorder, 0, pos));

    if (pos == inorder.length - 1) right = buildTree(emp, emp);
    else
      right =
          buildTree(
              Arrays.copyOfRange(preorder, pos + 1, preorder.length),
              Arrays.copyOfRange(inorder, pos + 1, inorder.length));

    root.left = left;
    root.right = right;
    return root;
  }
  /**
   * Creates a new {@code TX64Packet} object from the given payload.
   *
   * @param payload The API frame payload. It must start with the frame type corresponding to a TX64
   *     Request packet ({@code 0x00}). The byte array must be in {@code OperatingMode.API} mode.
   * @return Parsed TX (transmit) 64 Request packet.
   * @throws IllegalArgumentException if {@code payload[0] != APIFrameType.TX_64.getValue()} or if
   *     {@code payload.length < }{@value #MIN_API_PAYLOAD_LENGTH} or if {@code frameID < 0} or if
   *     {@code frameID > 255} or if {@code transmitOptions < 0} or if {@code transmitOptions >
   *     255}.
   * @throws NullPointerException if {@code payload == null}.
   */
  public static TX64Packet createPacket(byte[] payload) {
    if (payload == null)
      throw new NullPointerException("TX64 Request packet payload cannot be null.");

    // 1 (Frame type) + 1 (frame ID) + 8 (address) + 1 (transmit options)
    if (payload.length < MIN_API_PAYLOAD_LENGTH)
      throw new IllegalArgumentException("Incomplete TX64 Request packet.");

    if ((payload[0] & 0xFF) != APIFrameType.TX_64.getValue())
      throw new IllegalArgumentException("Payload is not a TX64 Request packet.");

    // payload[0] is the frame type.
    int index = 1;

    // Frame ID byte.
    int frameID = payload[index] & 0xFF;
    index = index + 1;

    // 8 bytes of address, starting at 2nd byte.
    XBee64BitAddress destAddress64 =
        new XBee64BitAddress(Arrays.copyOfRange(payload, index, index + 8));
    index = index + 8;

    // Transmit options byte.
    int transmitOptions = payload[index] & 0xFF;
    index = index + 1;

    // Get data.
    byte[] data = null;
    if (index < payload.length) data = Arrays.copyOfRange(payload, index, payload.length);

    return new TX64Packet(frameID, destAddress64, transmitOptions, data);
  }
Exemple #3
0
  public synchronized List<Transaction> getTransactions() {
    if (this.transactions == null) {
      // LOAD TRANSACTIONS
      this.transactions = new ArrayList<Transaction>();

      try {
        int position = 0;
        for (int i = 0; i < transactionCount; i++) {
          // GET TRANSACTION SIZE
          byte[] transactionLengthBytes =
              Arrays.copyOfRange(
                  this.rawTransactions, position, position + TRANSACTION_SIZE_LENGTH);
          int transactionLength = Ints.fromByteArray(transactionLengthBytes);

          // PARSE TRANSACTION
          byte[] transactionBytes =
              Arrays.copyOfRange(
                  this.rawTransactions,
                  position + TRANSACTION_SIZE_LENGTH,
                  position + TRANSACTION_SIZE_LENGTH + transactionLength);
          Transaction transaction = TransactionFactory.getInstance().parse(transactionBytes);

          // ADD TO TRANSACTIONS
          this.transactions.add(transaction);

          // ADD TO POSITION
          position += TRANSACTION_SIZE_LENGTH + transactionLength;
        }
      } catch (Exception e) {
        // FAILED TO LOAD TRANSACTIONS
      }
    }

    return this.transactions;
  }
  @Test
  public void testRemoveNode() throws Exception {
    waitForFullMesh(2000);
    IStoreClient<String, String> client0 =
        syncManagers[0].getStoreClient("global", String.class, String.class);
    IStoreClient<String, String> client1 =
        syncManagers[1].getStoreClient("global", String.class, String.class);
    IStoreClient<String, String> client2 =
        syncManagers[2].getStoreClient("global", String.class, String.class);

    client0.put("key", "value");
    waitForValue(client1, "key", "value", 2000, "client1");

    nodes.remove(0);
    nodeString = mapper.writeValueAsString(nodes);

    SyncManager oldNode = syncManagers[0];
    syncManagers = Arrays.copyOfRange(syncManagers, 1, 4);
    moduleContexts = Arrays.copyOfRange(moduleContexts, 1, 4);

    try {
      for (int i = 0; i < syncManagers.length; i++) {
        moduleContexts[i].addConfigParam(syncManagers[i], "nodes", nodeString);
        syncManagers[i].doUpdateConfiguration();
        waitForConnection(syncManagers[i], (short) 1, false, 2000);
      }
    } finally {
      oldNode.shutdown();
    }
    waitForFullMesh(2000);

    client1.put("newkey", "newvalue");
    waitForValue(client2, "key", "value", 2000, "client4");
    waitForValue(client2, "newkey", "newvalue", 2000, "client0");
  }
  public boolean evaluate(byte[] event) {
    /*Selecciona del arreglo el byte del tipo de item*/

    byte itemType = event[0];

    if (itemType == SMOKETYPE) {
      /*Selecciona del arreglo el byte relacionado al status*/
      return smokeProcess(event[5]);

    } else if (itemType == SENSORTYPE) {
      /*Procesar evento*/
      byte[] codebytes = Arrays.copyOfRange(event, 1, 5);
      int code = Util.convertArraytoInt(codebytes);
      return sensorProcess(event[5], code);
    } else if (itemType == RFIDTYPE) {
      /*Procesar evento*/
      // System.out.println("RFID");
      byte[] codebytes = Arrays.copyOfRange(event, 1, 5);
      int code = Util.convertArraytoInt(codebytes);
      return sensorProcess(event[5], code);
    } else {
      /*No contiene un tipo de item definido*/
      return false;
    }
  }
  private static BinarytreeNode ReCreateTree(int[] preOrder, int[] middleOrder) {
    if (preOrder == null || middleOrder == null) return null;
    if ((preOrder.length <= 0 && preOrder.length <= 0) || (preOrder.length != middleOrder.length))
      return null;
    BinarytreeNode root = new BinarytreeNode();
    root.value = preOrder[0];
    int middle = 0;
    for (int i = 0; i < middleOrder.length; i++) {
      if (middleOrder[i] == preOrder[0]) {
        middle = i;
      }
    }
    if (middle >= 0) { // 这里一定要是等于0也可以
      /** 每次都这样暴力的穿件一份数组其实很浪费 可以用指针移动来处理 */
      root.left =
          ReCreateTree(
              Arrays.copyOfRange(preOrder, 1, middle + 1),
              Arrays.copyOfRange(middleOrder, 0, middle));

      root.right =
          ReCreateTree(
              Arrays.copyOfRange(preOrder, middle + 1, preOrder.length),
              Arrays.copyOfRange(middleOrder, middle + 1, middleOrder.length));
    }
    return root;
  }
    @Test
    public void nemesisBlockCannotBeLoadedFromInvalidBlob() {
      // Arrange:
      final byte[] buffer = loadNemesisBlockBlobObject();
      final byte[] badBuffer1 =
          ByteBuffer.allocate(3 + buffer.length).put("bad".getBytes()).put(buffer).array();
      final byte[] badBuffer2 =
          ByteBuffer.allocate(3 + buffer.length)
              .put(Arrays.copyOfRange(buffer, 0, 100))
              .put("bad".getBytes())
              .put(Arrays.copyOfRange(buffer, 100, buffer.length))
              .array();

      // Act:
      ExceptionAssert.assertThrows(
          v ->
              NemesisBlock.fromBlobObject(
                  NEMESIS_BLOCK_INFO,
                  badBuffer1,
                  new DeserializationContext(new MockAccountLookup())),
          IllegalArgumentException.class);
      ExceptionAssert.assertThrows(
          v ->
              NemesisBlock.fromBlobObject(
                  NEMESIS_BLOCK_INFO,
                  badBuffer2,
                  new DeserializationContext(new MockAccountLookup())),
          SerializationException.class);
    }
  private static void parseTCPMsg(byte[] msg) throws UnknownHostException {
    switch (msg[0]) {
      case 0x00:
        if (msg[1] == 0x01) System.out.println("Server: OPEN");
        else System.out.println("Server: CLOSED");
        break;
      case 0x01:
        if (msg[1] == 0x00)
          System.out.printf("[ERR]: %s", new String(Arrays.copyOfRange(msg, 2, msg.length)));
        else {
          ByteBuffer buffer = ByteBuffer.wrap(Arrays.copyOfRange(msg, 1, msg.length));
          userId = new UUID(buffer.getLong(), buffer.getLong());
          groupIp =
              InetAddress.getByAddress(ByteBuffer.allocate(4).putInt(buffer.getInt()).array());

          // connect to the group and start receiving
          udpSocket.connect(groupIp.getHostAddress());
          udpSocket.startReceive(new UDPHandler());

          System.out.printf(
              "User ID: %s\nGroup IP: %s\nPort: %d\n",
              userId.toString(), groupIp.getHostAddress(), buffer.getInt());
        }
        break;
      case 0x02:
        if (msg[1] == 0x00)
          System.out.printf("[ERR]: %s", new String(Arrays.copyOfRange(msg, 2, msg.length)));
        else System.out.println("Successfully deregestered");
      default:
        System.out.println("[ERR] Inavlid msg");
    }
  }
 private static Placeholder parsePlayerPlaceholder(
     String[] tokens, Function<Context, Player> playerFunction) {
   if (tokens.length == 0) {
     return new PlayerBoundPlaceholder(playerFunction, Player::getName);
   } else if ("server".equals(tokens[0])) {
     return parseServerPlaceholder(
         Arrays.copyOfRange(tokens, 1, tokens.length),
         Functions.composeNullable(
             p -> p.get(BungeeTabListPlus.DATA_KEY_SERVER).orElse(null), playerFunction));
   } else if ("permission".equals(tokens[0])) {
     return new PermissionPlaceholder(playerFunction, tokens[1]);
   } else if (playerPlaceholders.containsKey(tokens[0])) {
     return playerPlaceholders
         .get(tokens[0])
         .apply(Arrays.copyOfRange(tokens, 1, tokens.length), playerFunction);
   } else if (thirdPartyDataKeys.containsKey(tokens[0])) {
     return new PlayerBoundPlaceholder(
         playerFunction, player -> player.get(thirdPartyDataKeys.get(tokens[0])).orElse(""));
   } else if (remoteThirdPartyDataKeys.containsKey(tokens[0])) {
     return new PlayerBoundPlaceholder(
         playerFunction, player -> player.get(remoteThirdPartyDataKeys.get(tokens[0])).orElse(""));
   } else if (placeholderAPIDataKeys.containsKey(tokens[0])) {
     return new PlayerBoundPlaceholder(
         playerFunction, player -> player.get(placeholderAPIDataKeys.get(tokens[0])).orElse(""));
   } else {
     BungeeTabListPlus.getInstance().getPlaceholderAPIHook().addMaybePlaceholder(tokens[0]);
     return NULL_PLACEHOLDER;
   }
 }
 public static <T> T[] removeElement(T[] array, int i) {
   if (i < 0) return array;
   if (i == 0) return Arrays.copyOfRange(array, 1, array.length);
   T[] result = Arrays.copyOfRange(array, 0, array.length - 1);
   for (int j = i + 1; j < array.length; j++) result[j - 1] = array[j];
   return result;
 }
Exemple #11
0
  /**
   * Method: Divide array by 2 and compare largest elements of both halves recursively
   *
   * @param A (rotated sorted array)
   * @return Largest element in rotated sorted array
   */
  public static <T extends Comparable<T>> T searchMax(T[] A) {

    // Base cases: length == 2
    // Compare the two elements
    if (A.length == 2) {
      int comparison = A[0].compareTo(A[1]);
      // if element in leftArray was 'bigger', return that
      if (comparison > 0) {
        return A[0];
        // else return element in rightArray
        // (since elements are distinct we do not consider comparison == 0)
      } else {
        return A[1];
      }
      // Base cases: length == 1
      // Return element
    } else if (A.length == 1) {
      return A[0];

      // Compare largest elements of both halves
    } else {
      T leftMax = searchMax(Arrays.copyOfRange(A, 0, A.length / 2));
      T rightMax = searchMax(Arrays.copyOfRange(A, A.length / 2, A.length));

      int leftRightComparison = leftMax.compareTo(rightMax);
      if (leftRightComparison > 0) {
        return leftMax;
      } else {
        return rightMax;
      }
    }
  }
  /**
   * Index the ntriple data
   *
   * @throws IOException
   * @throws SolrServerException
   * @throws IOException
   * @throws SolrServerException
   */
  public void index() throws SolrServerException, IOException {
    // add this document
    final SolrInputDocument document1 = new SolrInputDocument();
    document1.addField("url", doc1[0]);
    document1.addField("ntriple", doc1[1]);
    document1.addField(
        "tabular", CSV2Tabular.convert(csvConfig, Arrays.copyOfRange(doc1, 2, doc1.length)));
    add(document1);
    // add this document
    final SolrInputDocument document2 = new SolrInputDocument();
    document2.addField("url", doc2[0]);
    document2.addField("ntriple", doc2[1]);
    document2.addField(
        "tabular", CSV2Tabular.convert(csvConfig, Arrays.copyOfRange(doc2, 2, doc2.length)));
    add(document2);
    // add this document
    final SolrInputDocument document3 = new SolrInputDocument();
    document3.addField("url", doc3[0]);
    document3.addField("ntriple", doc3[1]);
    document3.addField(
        "tabular", CSV2Tabular.convert(csvConfig, Arrays.copyOfRange(doc3, 2, doc3.length)));
    add(document3);

    commit();
  }
 @Override
 public double[] evaluate(final DoubleTimeSeries<?> x) {
   Validate.notNull(x, "x");
   if (x.isEmpty()) {
     throw new IllegalArgumentException("Time series was empty");
   }
   final int h = x.size() - 1;
   final double[] result = new double[h];
   final double mean = _meanCalculator.evaluate(x);
   double[] x1, x2;
   final int n = x.size();
   double sum;
   final double[] x0 = x.valuesArrayFast();
   for (int i = 0; i < h; i++) {
     x1 = Arrays.copyOfRange(x0, 0, n - i);
     x2 = Arrays.copyOfRange(x0, i, n);
     if (x1.length != x2.length) {
       throw new IllegalArgumentException(
           "Series were not the same length; this should not happen");
     }
     sum = 0;
     for (int j = 0; j < x1.length; j++) {
       sum += (x1[j] - mean) * (x2[j] - mean);
     }
     result[i] = sum / n;
   }
   return result;
 }
  /**
   * if there is more than one peak in the histogram, reduce the histogram to only that peak, else
   * leave unaltered.
   *
   * @param hist
   * @param values
   * @param valueErrors
   * @return
   */
  public static HistogramHolder reduceHistogramToFirstPeak(
      HistogramHolder hist, float[] values, float[] valueErrors) {

    int yPeakIdx = findFirstPeakIndex(hist);

    if (yPeakIdx == -1) {
      return hist;
    }

    int yMinPeakIdx = findFirstMinimaFollowingPeak(hist, yPeakIdx);

    if (yMinPeakIdx == -1) {
      return hist;
    }

    int n = yMinPeakIdx + 1;

    HistogramHolder tmp = new HistogramHolder();
    tmp.setXHist(Arrays.copyOfRange(hist.getXHist(), 0, n));
    tmp.setYHistFloat(Arrays.copyOfRange(hist.getYHistFloat(), 0, n));
    tmp.setXErrors(Arrays.copyOfRange(hist.getXErrors(), 0, n));
    tmp.setYErrors(Arrays.copyOfRange(hist.getYErrors(), 0, n));

    return tmp;
  }
Exemple #15
0
 public static int scoresAverage(int[] nums) {
   int middle = nums.length / 2;
   int end = nums.length;
   int[] left = Arrays.copyOfRange(nums, 0, middle);
   int[] right = Arrays.copyOfRange(nums, middle, end);
   return (average(left) + average(right)) / 2;
 }
Exemple #16
0
  @Override
  public boolean removeMetadataBlob(
      UserPublicKey owner, byte[] encodedWritingPublicKey, byte[] writingKeySignedMapKeyPlusBlob) {
    UserPublicKey writingKey = new UserPublicKey(encodedWritingPublicKey);

    try {
      byte[] payload = writingKey.unsignMessage(writingKeySignedMapKeyPlusBlob);
      byte[] mapKey = Arrays.copyOfRange(payload, 0, 32);
      byte[] metadataBlob =
          Arrays.copyOfRange(
              payload,
              32,
              payload
                  .length); // will be zero length for now // TODO  change to the current blob hash
      MetadataBlob blob = new MetadataBlob(writingKey.getPublicKeys(), mapKey, metadataBlob);
      return blob.delete();
    } catch (TweetNaCl.InvalidSignatureException e) {
      System.err.println(
          "Invalid signature during removeMetadataBlob for owner: "
              + owner
              + " and sharer: "
              + writingKey);
      return false;
    }
  }
Exemple #17
0
  public static Integer[] mergeSort(Integer[] A, int p, int r) {

    if (A.length > 0) {
      String message = "";
      for (Integer i : A) {
        message += i.toString() + " ";
      }
      System.out.println(message);
    } else {
      System.out.println(A);
    }

    ArrayList<Integer> handler = new ArrayList<Integer>(A.length);

    if (p < r & A.length > 1) {
      int q = (int) Math.floor((p + r) * 0.5);
      handler.addAll(
          new ArrayList<Integer>(Arrays.asList(mergeSort((Arrays.copyOfRange(A, p, q)), p, q))));
      handler.addAll(
          new ArrayList<Integer>(
              Arrays.asList(mergeSort((Arrays.copyOfRange(A, q + 1, r)), q + 1, r))));

      //			output.addAll(new ArrayList<Integer>(Arrays.asList(merge(A, p, q, r))));
      return (merge(handler.toArray(new Integer[r]), p, q, r));

    } else if (A.length == 1) {
      return (A);
    } else {
      return (null);
    }

    //		return((Integer[]) output.toArray());
  }
Exemple #18
0
  @Override
  public Dataset buildDataset() {
    Dataset ret = new Dataset(template, Utils.relativize(file));

    int inputDim = template.inputTemplate.getDescriptionLength();
    int outputDim = template.outputTemplate.getDescriptionLength();

    if (file.exists()) {
      try {
        int index = 0, count = 0;
        BufferedReader reader = new BufferedReader(new FileReader(file));
        for (String line = reader.readLine();
            line != null && count < instanceNumber;
            line = reader.readLine(), index++) {
          if (index < startIndex) continue;
          String[] tokens = line.split(separators);
          Object input = getData(Arrays.copyOfRange(tokens, 0, inputDim), template.inputTemplate);
          Object output =
              getData(
                  Arrays.copyOfRange(tokens, inputDim, inputDim + outputDim),
                  template.outputTemplate);
          ret.add(template.newInstance(input, output));
          count++;
        }
        reader.close();
        ret.setReadyState();
      } catch (IOException e) {
      }
    }

    return ret;
  }
Exemple #19
0
 /**
  * Finds or creates a method type with some parameter types omitted. Convenience method for {@link
  * #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  *
  * @param start the index (zero-based) of the first parameter type to remove
  * @param end the index (greater than {@code start}) of the first parameter type after not to
  *     remove
  * @return the same type, except with the selected parameter(s) removed
  * @throws IndexOutOfBoundsException if {@code start} is negative or greater than {@code
  *     parameterCount()} or if {@code end} is negative or greater than {@code parameterCount()} or
  *     if {@code start} is greater than {@code end}
  */
 public MethodType dropParameterTypes(int start, int end) {
   int len = ptypes.length;
   if (!(0 <= start && start <= end && end <= len))
     throw newIndexOutOfBoundsException("start=" + start + " end=" + end);
   if (start == end) return this;
   Class<?>[] nptypes;
   if (start == 0) {
     if (end == len) {
       // drop all parameters
       nptypes = NO_PTYPES;
     } else {
       // drop initial parameter(s)
       nptypes = Arrays.copyOfRange(ptypes, end, len);
     }
   } else {
     if (end == len) {
       // drop trailing parameter(s)
       nptypes = Arrays.copyOfRange(ptypes, 0, start);
     } else {
       int tail = len - end;
       nptypes = Arrays.copyOfRange(ptypes, 0, start + tail);
       System.arraycopy(ptypes, end, nptypes, start, tail);
     }
   }
   return makeImpl(rtype, nptypes, true);
 }
  static {
    int versionLength = HttpVersion.HTTP_1_1.toString().length();

    for (int i = 0; i < __preprepared.length; i++) {
      HttpStatus.Code code = HttpStatus.getCode(i);
      if (code == null) continue;
      String reason = code.getMessage();
      byte[] line = new byte[versionLength + 5 + reason.length() + 2];
      HttpVersion.HTTP_1_1.toBuffer().get(line, 0, versionLength);
      line[versionLength + 0] = ' ';
      line[versionLength + 1] = (byte) ('0' + i / 100);
      line[versionLength + 2] = (byte) ('0' + (i % 100) / 10);
      line[versionLength + 3] = (byte) ('0' + (i % 10));
      line[versionLength + 4] = ' ';
      for (int j = 0; j < reason.length(); j++)
        line[versionLength + 5 + j] = (byte) reason.charAt(j);
      line[versionLength + 5 + reason.length()] = HttpTokens.CARRIAGE_RETURN;
      line[versionLength + 6 + reason.length()] = HttpTokens.LINE_FEED;

      __preprepared[i] = new PreparedResponse();
      __preprepared[i]._schemeCode = Arrays.copyOfRange(line, 0, versionLength + 5);
      __preprepared[i]._reason = Arrays.copyOfRange(line, versionLength + 5, line.length - 2);
      __preprepared[i]._responseLine = line;
    }
  }
 /**
  * コンストラクタ
  *
  * @param data コマンド実行結果で戻ったバイト列をセット
  */
 public CommandResponse(byte[] data) {
   this.rawData = data;
   this.length = data[0];
   this.responseCode = data[1];
   this.idm = new IDm(Arrays.copyOfRange(data, 2, 10));
   this.data = Arrays.copyOfRange(data, 10, data.length);
 }
 public CDFILESEGMENT(final byte[] data) {
   Header = new LSIG(Arrays.copyOfRange(data, 0, 6));
   DataSize = CDUtils.wordToShort(Arrays.copyOfRange(data, 6, 8));
   SegSize = CDUtils.wordToShort(Arrays.copyOfRange(data, 8, 10));
   Flags = CDUtils.dwordToInt(Arrays.copyOfRange(data, 10, 14));
   Reserved = CDUtils.dwordToInt(Arrays.copyOfRange(data, 14, 18));
 }
  /**
   * Deze methode maakt met een array van nodes een zoek goed mogelijk gebalanceerde binaire
   * zoekboom. Ale verwijzingen naar externe kinderen worden op null gezet. PRECONDITIE: De Array is
   * gesorteerd volgens de sleutels van de nodes en dat van klein naar groot.
   *
   * @return : de root van deze niewe boom.
   * @complexiteit: Recursie van de vorm T(k) = 2*T(k/2) + 0. k is de zeepbel-constante. M.b.v. de
   *     mastermethode bekomen we voor deze functie O(k).
   */
  private Node<Key> maakGebalanceerdeBoom(Node<Key>[] nodes) {
    int midIdx = nodes.length / 2;
    Node<Key> root = nodes[midIdx];
    root.setLeft(null);
    root.setRight(null);
    if (nodes.length == 1) {
      return root;
    } else if (nodes.length == 2) {
      root.setChild(nodes[0]);
      nodes[0].setLeft(null);
      nodes[0].setRight(null);
    } else if (nodes.length == 3) {
      root.setLeft(nodes[0]);
      nodes[0].setLeft(null);
      nodes[0].setRight(null);

      root.setRight(nodes[2]);
      nodes[2].setLeft(null);
      nodes[2].setRight(null);
    } else {
      Node<Key>[] linkerdeel = Arrays.copyOfRange(nodes, 0, midIdx);
      root.setLeft(maakGebalanceerdeBoom(linkerdeel));
      Node<Key>[] rechterdeel = Arrays.copyOfRange(nodes, midIdx + 1, nodes.length);
      root.setRight(maakGebalanceerdeBoom(rechterdeel));
    }
    return root;
  }
 /*
 输入二叉树的前序遍历和中序遍历结果,重建二叉树并输出头节点
 ex:12473568,47215386
  */
 public BinaryTreeNode constructCore(int[] preorder, int[] inorder) throws Exception {
   // boolean isHave =false;
   if (preorder == null || inorder == null) {
     return null;
   }
   if (preorder.length != inorder.length) {
     throw new Exception("长度不一样-非法输入");
   }
   BinaryTreeNode root = new BinaryTreeNode();
   for (int i = 0; i < inorder.length; i++) {
     if (inorder[i] == preorder[0]) {
       // isHave =true;
       root.value = inorder[i];
       root.leftNode =
           constructCore(
               Arrays.copyOfRange(preorder, 1, i + 1), Arrays.copyOfRange(inorder, 0, i));
       root.rightNode =
           constructCore(
               Arrays.copyOfRange(preorder, i + 1, preorder.length),
               Arrays.copyOfRange(inorder, i + 1, inorder.length));
     }
   }
   /*if(!isHave)
   {
   	throw new Exception("不包含根节点-非法输入");
   }*/
   return root;
 }
  @Override
  protected void compute() {
    if (arrayToCalculateSumOf.length == 1) {
      // working unit is small enough, do the work
      result = arrayToCalculateSumOf[0];
    } else {
      // split up the work into smaller parts (fork)
      int midpoint = arrayToCalculateSumOf.length / 2;

      int[] l1 = Arrays.copyOfRange(arrayToCalculateSumOf, 0, midpoint);
      int[] l2 = Arrays.copyOfRange(arrayToCalculateSumOf, midpoint, arrayToCalculateSumOf.length);

      ArraySumRecursiveActionForkJoin s1 = new ArraySumRecursiveActionForkJoin(l1);
      ArraySumRecursiveActionForkJoin s2 = new ArraySumRecursiveActionForkJoin(l2);

      s1.fork();
      s2.compute();

      // join the calculated parts and do the real calculation
      s1.join();
      Utils.doCpuIntensiveCalculation();

      result += s1.result + s2.result;
    }
  }
Exemple #26
0
 /**
  * getView
  *
  * @return
  */
 public String[] getView() {
   if (this.topLine + this.displayRows > this.content.length) {
     return Arrays.copyOfRange(this.content, getBottom() - this.displayRows, getBottom());
   } else {
     return Arrays.copyOfRange(this.content, this.topLine, getBottom());
   }
 }
Exemple #27
0
 /**
  * Create a subframe from given interval of columns.
  *
  * @param startIdx index of first column (inclusive)
  * @param endIdx index of the last column (exclusive)
  * @return a new frame containing specified interval of columns
  */
 public Frame subframe(int startIdx, int endIdx) {
   Frame result =
       new Frame(
           Arrays.copyOfRange(_names, startIdx, endIdx),
           Arrays.copyOfRange(vecs(), startIdx, endIdx));
   return result;
 }
  /**
   * Determines if the address is valid.
   *
   * @return true if the address is valid.
   */
  public static boolean isValid(@Nullable final String value) {
    if (value == null) {
      return false;
    }
    // this check should prevent leading and trailing whitespace
    if (NUM_DECODED_BYTES_LENGTH != value.length()) {
      return false;
    }

    final byte[] encodedBytes;

    try {
      encodedBytes = Base32Encoder.getBytes(value);
    } catch (final IllegalArgumentException e) {
      return false;
    }
    if (NUM_ENCODED_BYTES_LENGTH != encodedBytes.length) {
      return false;
    }

    if (AppConstants.NETWORK_VERSION.get() != encodedBytes[0]) {
      return false;
    }

    final int checksumStartIndex = NUM_ENCODED_BYTES_LENGTH - NUM_CHECKSUM_BYTES;
    final byte[] versionPrefixedHash = Arrays.copyOfRange(encodedBytes, 0, checksumStartIndex);
    final byte[] addressChecksum =
        Arrays.copyOfRange(
            encodedBytes, checksumStartIndex, checksumStartIndex + NUM_CHECKSUM_BYTES);
    final byte[] calculatedChecksum = generateChecksum(versionPrefixedHash);
    return Arrays.equals(addressChecksum, calculatedChecksum);
  }
Exemple #29
0
 /**
  * the binary protocol see {@linkplain #toBytes()}
  *
  * @param b
  */
 public void fill(byte[] b) {
   int coordinate = 0;
   storagePointer = NumberUtils.byteArrayToInt(Arrays.copyOfRange(b, coordinate, coordinate + 4));
   coordinate += 4;
   int parent_storagePointer =
       NumberUtils.byteArrayToInt(Arrays.copyOfRange(b, coordinate, coordinate + 4));
   coordinate += 4;
   if (parent_storagePointer > 0) {
     parent = new Node(storage);
     parent.storagePointer = parent_storagePointer;
   }
   count = b[coordinate];
   coordinate += 1;
   isLeaf = b[coordinate] == 1 ? true : false;
   coordinate += 1;
   for (int i = 0; i < DATAITEMS_COUNT; i++) {
     if (i < count) {
       if (dataItems[i] == null) dataItems[i] = new DataItem();
       dataItems[i].fill(Arrays.copyOfRange(b, coordinate, coordinate + DataItem.BYTE_LENGTH));
     }
     coordinate += DataItem.BYTE_LENGTH;
   }
   for (int i = 0; i <= DATAITEMS_COUNT; i++) {
     if (!isLeaf && i <= count) {
       if (child[i] == null) child[i] = new Node(this.storage);
       child[i].storagePointer =
           NumberUtils.byteArrayToInt(Arrays.copyOfRange(b, coordinate, coordinate + 4));
     }
     coordinate += 4;
   }
 }
  private void processChunk(
      int x,
      int z,
      byte[] data,
      int bitmask,
      int additionalBitmask,
      boolean addSkylight,
      boolean addBiomes) {
    if (data == null) return;
    int chunksChanged = 0;
    for (int i = 0; i < 16; i++) if ((bitmask & (1 << i)) != 0) chunksChanged++;
    if (chunksChanged == 0) return;
    byte[] biomes = new byte[256];
    synchronized (chunks) {
      int i = 0;
      for (int y = 0; y < 16; y++) {
        if ((bitmask & (1 << y)) == 0) continue;
        int dataIndex = i * 4096;
        byte[] blocks = Arrays.copyOfRange(data, dataIndex, dataIndex + 4096);
        dataIndex += ((chunksChanged - i) * 4096) + (i * 2048);
        byte[] metadata = Arrays.copyOfRange(data, dataIndex, dataIndex + 2048);
        dataIndex += chunksChanged * 2048;
        byte[] light = Arrays.copyOfRange(data, dataIndex, dataIndex + 2048);
        dataIndex += chunksChanged * 2048;
        byte[] skylight = null;
        if (addSkylight) skylight = Arrays.copyOfRange(data, dataIndex, dataIndex + 2048);

        byte[] perBlockMetadata = new byte[4096];
        byte[] perBlockLight = new byte[4096];
        byte[] perBlockSkylight = new byte[4096];

        for (int j = 0; j < 2048; j++) {
          int k = j * 2;
          perBlockMetadata[k] = (byte) (metadata[j] & 0x0F);
          perBlockLight[k] = (byte) (light[j] & 0x0F);
          if (addSkylight) perBlockSkylight[k] = (byte) (skylight[j] & 0x0F);
          k++;
          perBlockMetadata[k] = (byte) (metadata[j] >> 4);
          perBlockLight[k] = (byte) (light[j] >> 4);
          if (addSkylight) perBlockSkylight[k] = (byte) (skylight[j] >> 4);
        }

        ChunkLocation newLocation = new ChunkLocation(x, y, z);
        Chunk chunk =
            new Chunk(
                this,
                newLocation,
                blocks,
                perBlockMetadata,
                perBlockLight,
                perBlockSkylight,
                biomes);
        chunks.put(newLocation, chunk);
        bot.getEventManager().sendEvent(new ChunkLoadEvent(this, chunk));
        i++;
      }
      System.arraycopy(data, data.length - 256, biomes, 0, 256);
    }
  }