/** @throws Exception If failed. */
  public void testConcurrentStart() throws Exception {
    ThreadLocalRandom rnd = ThreadLocalRandom.current();

    for (int i = 0; i < 3; i++) {
      try {
        clientNodes = new HashSet<>();

        while (clientNodes.size() < 2) clientNodes.add(rnd.nextInt(1, NODES_CNT));

        clientNodes.add(NODES_CNT - 1);

        log.info("Test iteration [iter=" + i + ", clients=" + clientNodes + ']');

        Ignite srv = startGrid(0); // Start server node first.

        assertFalse(srv.configuration().isClientMode());

        startGridsMultiThreaded(1, NODES_CNT - 1);

        checkTopology(NODES_CNT);

        awaitPartitionMapExchange();

        for (int node : clientNodes) {
          Ignite ignite = grid(node);

          assertTrue(ignite.configuration().isClientMode());
        }
      } finally {
        stopAllGrids();
      }
    }
  }
Exemplo n.º 2
0
 @Test
 public void testRandomRangeAndBatches() throws ExecutionException, InterruptedException {
   ThreadLocalRandom random = ThreadLocalRandom.current();
   int treeSize = random.nextInt(maxTreeSize / 10, maxTreeSize * 10);
   for (int i = 0; i < perThreadTrees / 10; i++)
     testInsertions(threads * 10, treeSize, random.nextInt(1, 100) / 10f, treeSize / 100, true);
 }
Exemplo n.º 3
0
 @Override
 public MutatedInstanceMetaData<MultiMaskEfsmSkeleton, MultiMaskEfsmMutation> apply(
     MultiMaskEfsmSkeleton individual) {
   List<Step> transitions = getTransitions(individual);
   if (transitions.isEmpty()) {
     return new MutatedInstanceMetaData<MultiMaskEfsmSkeleton, MultiMaskEfsmMutation>(
         new MultiMaskEfsmSkeleton(individual), new MutationCollection<MultiMaskEfsmMutation>());
   }
   MyMap num = new MyMap();
   for (Step s : transitions) {
     num.put(s, 1);
   }
   for (VarsActionsScenario s : individual.getCounterExamples()) {
     getTrace(individual, s, num);
   }
   double sum = 0;
   for (Step s : transitions) {
     sum += num.get(s);
   }
   int i = 0;
   double cur = num.get(transitions.get(0)) / sum;
   ThreadLocalRandom random = ThreadLocalRandom.current();
   while (random.nextDouble() > cur) {
     i++;
     cur += num.get(transitions.get(i)) / sum;
   }
   Step s = transitions.get(i);
   MultiMaskEfsmSkeleton ind = new MultiMaskEfsmSkeleton(individual);
   int x = random.nextInt(MultiMaskEfsmSkeleton.STATE_COUNT);
   ind.getState(s.state).getTransitionGroup(s.event, s.group).setNewState(s.index, x);
   return new MutatedInstanceMetaData<MultiMaskEfsmSkeleton, MultiMaskEfsmMutation>(
       ind,
       new MutationCollection<MultiMaskEfsmMutation>(
           new DestinationStateMutation(s.state, s.event, s.group, s.index, x)));
 }
Exemplo n.º 4
0
 private static IntFunction<Integer> twoDiceThrows() {
   return i -> {
     final ThreadLocalRandom random = ThreadLocalRandom.current();
     final int firstThrow = random.nextInt(1, 7);
     final int secondThrow = random.nextInt(1, 7);
     return firstThrow + secondThrow;
   };
 }
Exemplo n.º 5
0
  public T doWork(T context, int niters, Result<T> opts) {

    opts.setErrorCount(0);

    ActionRecord record = new ActionRecord();
    ActionRecord logRecord = new ActionRecord();

    final int transactionSize =
        ThreadLocalRandom.current().nextInt(this.maxTransactionSize) + this.minTransactionSize;
    List<String> keysToUse = keys.getRandomKeyList(transactionSize, true);

    // If this is a logger
    if (writeToLogs > 0 && ThreadLocalRandom.current().nextInt(1000) < 1) {
      System.out.println("Log Reader");

      record = machine.readLog(3, millisBetweenActions);
      workTimeMillis = System.currentTimeMillis();
      return null;
    }

    if (keysToUse.size() < 2) {
      System.out.println("whoa there...");
    }

    // Get Random number to assign task
    final int rand1 = ThreadLocalRandom.current().nextInt(1000);
    if (rand1 < chanceOfRead) {
      // Reader
      record = machine.read(keysToUse, millisBetweenActions);
    } else if (rand1 < chanceOfWrite) {
      // Writer
      record = machine.update(keysToUse, millisBetweenActions);
    } else if (rand1 < chanceOfReadModifyWrite) {
      // Reader + Writer
      record = machine.readModifyWrite(keysToUse, millisBetweenActions);
    } else if (rand1 < chanceOfBalanceTransfer) {
      record = machine.balanceTransfer(keysToUse.get(0), keysToUse.get(1), millisBetweenActions);
    } else if (rand1 < chanceOfIncrementalUpdate) {
      record = machine.incrementalUpdate(keysToUse, millisBetweenActions);
    }

    // Write the logs (if there are any to write)
    if (writeToLogs > 0) logRecord = machine.writeLog(writeToLogs, millisBetweenActions);

    // Check for success
    if (record == null
        || !record.isSuccess()
        || (writeToLogs > 0 && (logRecord == null || !logRecord.isSuccess()))) {

      opts.incrementErrorCount();
    }

    workTimeMillis = System.currentTimeMillis();

    return null;
  }
	public static int GetNext() {
		// Sequential search
		ThreadLocalRandom tlr = ThreadLocalRandom.current();
		long rank = tlr.nextLong(_obj_rank_min, _obj_rank_max + 1);

		// Return the upper bound (, which is smaller than the lower bound)
		if (_GETNEXT_METHOD == 'U') {
			// A sequential search from the end. Won't be too bad. It might be better than the
			// binary search since most of the random numbers will fall in the
			// buckets toward the end.
			int _ornrs_size = _ornrs.size();
			double num_reqs = -1.0;
			for (int i = _ornrs_size - 1; i >= 0; i --) {
				if (_ornrs.get(i).obj_rank <= rank) {
					if (i == _ornrs_size - 1) {
						num_reqs = _ornrs.get(i).num_reqs;
					} else {
						num_reqs = _ornrs.get(i+1).num_reqs;
					}
					//Cons.P(String.format("%d %f %d", rank, num_reqs, Math.round(num_reqs)));

					// Cast to float to call int round(float a);
					return Math.round((float) num_reqs);
				}
			}
		}
		// Interpolate between lower and upper bound
		else if (_GETNEXT_METHOD == 'I') {
			int _ornrs_size = _ornrs.size();
			double num_reqs = -1.0;
			for (int i = _ornrs_size - 1; i >= 0; i --) {
				if (_ornrs.get(i).obj_rank <= rank) {
					if (i == _ornrs_size - 1) {
						num_reqs = _ornrs.get(i).num_reqs;
					} else {
						// rank is always != _ornrs[i+1].obj_rank, since the same rank is
						// filtered out when loading the file
						num_reqs = (_ornrs.get(i+1).num_reqs - _ornrs.get(i).num_reqs)
							* (rank - _ornrs.get(i).obj_rank) / (_ornrs.get(i+1).obj_rank - _ornrs.get(i).obj_rank)
							+ _ornrs.get(i).num_reqs;
						//Cons.P(String.format("rank=%d i=%d num_reqs=%f %d | %d %d %f %f"
						//			, rank, i, num_reqs, Math.round(num_reqs)
						//			, _ornrs.get(i).obj_rank, _ornrs.get(i+1).obj_rank
						//			, _ornrs.get(i).num_reqs, _ornrs.get(i+1).num_reqs));
					}
					return Math.round((float) num_reqs);
				}
			}
		}

		throw new RuntimeException(
				String.format("Unexpected rank=%d _obj_rank_min=%d _obj_rank_max=%d",
					rank, _obj_rank_min, _obj_rank_max));
	}
Exemplo n.º 7
0
  private static RandomTree randomTreeByBuilder(int minSize, int maxSize) {
    assert minSize > 3;
    ThreadLocalRandom random = ThreadLocalRandom.current();
    BTree.Builder<Integer> builder = BTree.builder(naturalOrder());

    int targetSize = random.nextInt(minSize, maxSize);
    int maxModificationSize = (int) Math.sqrt(targetSize);

    TreeSet<Integer> canonical = new TreeSet<>();

    int curSize = 0;
    TreeSet<Integer> ordered = new TreeSet<>();
    List<Integer> shuffled = new ArrayList<>();
    while (curSize < targetSize) {
      int nextSize = maxModificationSize <= 1 ? 1 : random.nextInt(1, maxModificationSize);

      // leave a random selection of previous values
      (random.nextBoolean() ? ordered.headSet(random.nextInt()) : ordered.tailSet(random.nextInt()))
          .clear();
      shuffled =
          new ArrayList<>(
              shuffled.subList(0, shuffled.size() < 2 ? 0 : random.nextInt(shuffled.size() / 2)));

      for (int i = 0; i < nextSize; i++) {
        Integer next = random.nextInt();
        ordered.add(next);
        shuffled.add(next);
        canonical.add(next);
      }

      switch (random.nextInt(5)) {
        case 0:
          builder.addAll(ordered);
          break;
        case 1:
          builder.addAll(BTreeSet.of(ordered));
          break;
        case 2:
          for (Integer i : ordered) builder.add(i);
        case 3:
          builder.addAll(shuffled);
          break;
        case 4:
          for (Integer i : shuffled) builder.add(i);
      }

      curSize += nextSize;
      maxModificationSize = Math.min(maxModificationSize, targetSize - curSize);
    }

    BTreeSet<Integer> btree = BTreeSet.<Integer>wrap(builder.build(), naturalOrder());
    Assert.assertEquals(canonical.size(), btree.size());
    return new RandomTree(canonical, btree);
  }
  public static void IA() {
    while (true) {
      if (!(remplis(TabManager.horizontale))) {
        System.out.println("IA H");

        int cooxH = ThreadLocalRandom.current().nextInt(0, l);
        int cooyH = ThreadLocalRandom.current().nextInt(0, c - 1);

        while (TabManager.horizontale[cooxH][cooyH] == 1) {
          cooxH = ThreadLocalRandom.current().nextInt(0, l);
          cooyH = ThreadLocalRandom.current().nextInt(0, c - 1);
        }
        TabManager.horizontale[cooxH][cooyH] = 1;
        Test1.b = true;
        break;
      }

      if (!(remplis(TabManager.verticale))) {
        System.out.println("IA V");
        int cooxV = ThreadLocalRandom.current().nextInt(0, l - 1);
        int cooyV = ThreadLocalRandom.current().nextInt(0, c);

        while (TabManager.verticale[cooxV][cooyV] == 1) {
          cooxV = ThreadLocalRandom.current().nextInt(0, l - 1);
          cooyV = ThreadLocalRandom.current().nextInt(0, c);
        }
        TabManager.verticale[cooxV][cooyV] = 1;
        Test1.b = true;
        break;
      }
    }
  }
Exemplo n.º 9
0
  /**
   * Erzeugt eine Datei mit der angegebenen Anzahl in sortierter Reihenfolge. Die Zahlen werden
   * hintereinander weg geschrieben und durch ein Leerzeichen getrennt. Die Range der zufaellig
   * generierten Zahlen ist 1..(quantity * 5)
   *
   * @param filename, Dateiname (Endung *.dat wird automatisch ergaenzt)
   * @param quantity, die Anzahl der zufaellig generierten Zahlen
   * @param desc, true = absteigend sortiert; false = aufsteigend sortiert
   */
  public static void sortNum(String filename, int quantity, boolean desc) {

    File file = new File(filename + ".dat");
    if (file.exists()) {
      System.err.println("Die Datei existiert bereits");
    } else {
      try {
        file.createNewFile();
      } catch (IOException e) {
        e.printStackTrace();
      }
      BufferedWriter bw = null;
      try {
        FileWriter fw = new FileWriter(file);
        bw = new BufferedWriter(fw);

        ThreadLocalRandom random = ThreadLocalRandom.current();
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 1; i <= quantity; i++) {
          list.add(random.nextInt(1, quantity * 5));
        }

        Collections.sort(list);

        if (desc) {
          Collections.reverse(list);
          for (int i = 1; i < list.size(); i++) {
            bw.write(String.valueOf(list.get(i)) + " ");
          }
          bw.write(String.valueOf(list.get(list.size() - 1)));
        } else {
          for (int i = 1; i < list.size(); i++) {
            bw.write(String.valueOf(list.get(i)) + " ");
          }
          bw.write(String.valueOf(list.get(list.size() - 1)));
        }

        System.err.println("Die Datei " + filename + ".dat wurde erfolgreich erstellt");
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        try {
          bw.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
 /** Store data to StorageNode with the Node is selected randomly */
 public void bindReplicasToStorageNodeRand_Net() {
   int replicaNum = replicaList.size();
   int nodeSize = nodeList.size();
   for (int i = 0; i < replicaNum; i++) {
     BlockReplica replica = replicaList.get(i);
     StorageNode node =
         nodeList.get(java.util.concurrent.ThreadLocalRandom.current().nextInt(nodeSize));
     double replicaSize = replica.getSize();
     if (node.getAvailableSpace() - replicaSize >= 0.000000000000000000000001
         && !node.contains(replica.getName())) {
       double time = node.addFile(replica);
       double accrossLatency = NetworkTopology.getDelay(getId(), node.getDatacenter().getId());
       time += accrossLatency;
       /*Log.printLine("it take " + time
       + " seconds to write the replica #" + replica.getId()
       + " to be stored in datacenter "
       + node.getDatacenter().getName() + " node #"
       + node.getId());*/
       Log.printLine(
           "replica #"
               + replica.getId()
               + "    			"
               + node.getDatacenter().getName()
               + " node #"
               + node.getId()
               + " 			"
               + time);
     } else {
       i--;
     }
   }
 }
Exemplo n.º 11
0
  public static String generateHallmark(String secretPhrase, String host, int weight, int date) {

    if (host.length() == 0 || host.length() > 100) {
      throw new IllegalArgumentException("Hostname length should be between 1 and 100");
    }
    if (weight <= 0 || weight > Constants.MAX_BALANCE_NXT) {
      throw new IllegalArgumentException(
          "Weight should be between 1 and " + Constants.MAX_BALANCE_NXT);
    }

    byte[] publicKey = Crypto.getPublicKey(secretPhrase);
    byte[] hostBytes = Convert.toBytes(host);

    ByteBuffer buffer = ByteBuffer.allocate(32 + 2 + hostBytes.length + 4 + 4 + 1);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.put(publicKey);
    buffer.putShort((short) hostBytes.length);
    buffer.put(hostBytes);
    buffer.putInt(weight);
    buffer.putInt(date);

    byte[] data = buffer.array();
    data[data.length - 1] = (byte) ThreadLocalRandom.current().nextInt();
    byte[] signature = Crypto.sign(data, secretPhrase);

    return Convert.toHexString(data) + Convert.toHexString(signature);
  }
Exemplo n.º 12
0
  @Override
  public CharSequence process(final Message message) throws MessageProcessingException {

    if (!enabled) {
      return null;
    }

    final Matcher m = COMMAND_PATTERN.matcher(message.getBody());
    if (!m.matches()) {
      return null;
    }

    final String userNick = MessageProcessorUtils.getUserNick(message);

    final String dcString = m.group(1);
    final String dsString = m.group(2);
    if (dcString.length() > 4 || dsString.length() > 5) {
      return userNick + ": я не настолько умная же! >_<\"";
    }

    final int diceCount = Integer.parseInt(dcString);
    final int dieSides = Integer.parseInt(dsString);
    final Random random = ThreadLocalRandom.current();
    int result = 0;
    for (int i = 0; i < diceCount; i++) {
      result += random.nextInt(dieSides) + 1;
    }
    return userNick + ": Выпало " + result + ", такие дела, нян!";
  }
  @Test
  public void testManyClusterings() throws Throwable {
    StringBuilder table = new StringBuilder("CREATE TABLE %s (a TEXT");
    StringBuilder cols = new StringBuilder();
    StringBuilder args = new StringBuilder("?");
    List<Object> vals = new ArrayList<>();
    vals.add("a");
    for (int i = 0; i < 40; i++) {
      table.append(", c").append(i).append(" text");
      cols.append(", c").append(i);
      if (ThreadLocalRandom.current().nextBoolean()) vals.add(Integer.toString(i));
      else vals.add("");
      args.append(",?");
    }
    args.append(",?");
    vals.add("value");
    table.append(", v text, PRIMARY KEY ((a)").append(cols).append("))");
    createTable(table.toString());

    execute("INSERT INTO %s (a" + cols + ", v) VALUES (" + args + ")", vals.toArray());
    flush();
    UntypedResultSet.Row row = execute("SELECT * FROM %s").one();
    for (int i = 0; i < row.getColumns().size(); i++)
      Assert.assertEquals(vals.get(i), row.getString(i == 0 ? "a" : i < 41 ? "c" + (i - 1) : "v"));
  }
  /** @throws Exception If failed. */
  public void testLockSerialization() throws Exception {
    final IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);

    info("Lock created: " + lock);

    lock.isFailoverSafe();
    lock.isFair();

    grid(ThreadLocalRandom.current().nextInt(G.allGrids().size()))
        .compute()
        .broadcast(
            new IgniteCallable<Object>() {
              @Nullable
              @Override
              public Object call() throws Exception {
                Thread.sleep(1000);

                lock.lock();

                try {
                  info("Inside lock: " + lock.getHoldCount());
                } finally {
                  lock.unlock();
                }

                return null;
              }
            });
  }
Exemplo n.º 15
0
  public PoolBagEntry(final Connection connection, final HikariPool pool) {
    this.connection = connection;
    this.parentPool = pool;
    this.creationTime = System.currentTimeMillis();
    this.poolElf = pool.poolElf;
    this.state = new AtomicInteger(STATE_NOT_IN_USE);
    this.lastAccess = ClockSource.INSTANCE.currentTime();
    this.openStatements = new FastList<>(Statement.class, 16);

    poolElf.resetPoolEntry(this);

    final long maxLifetime = pool.config.getMaxLifetime();
    final long variance = maxLifetime > 60_000 ? ThreadLocalRandom.current().nextLong(10_000) : 0;
    final long lifetime = maxLifetime - variance;
    if (lifetime > 0) {
      endOfLife =
          pool.houseKeepingExecutorService.schedule(
              new Runnable() {
                @Override
                public void run() {
                  // If we can reserve it, close it
                  if (pool.connectionBag.reserve(PoolBagEntry.this)) {
                    pool.closeConnection(PoolBagEntry.this, "(connection reached maxLifetime)");
                  } else {
                    // else the connection is "in-use" and we mark it for eviction by
                    // pool.releaseConnection() or the housekeeper
                    PoolBagEntry.this.evicted = true;
                  }
                }
              },
              lifetime,
              TimeUnit.MILLISECONDS);
    }
  }
  public Observable<List<TwitterUser>> searchUsers(String prefix) {
    if (ThreadLocalRandom.current().nextDouble() < failureProbability) {
      return Observable.error(new IOException("Broken pipe"));
    }

    return Observable.from(users).skip(1).toList().subscribeOn(Schedulers.newThread());
  }
Exemplo n.º 17
0
 /**
  * 产生len个[min,max)随机数(jdk7)
  *
  * @param min
  * @param max
  * @param len
  * @return
  */
 public static int[] generateRandomArrayWithJava7(int min, int max, int len) {
   int[] randomArray = new int[len];
   for (int i = 0; i < len; i++) {
     randomArray[i] = ThreadLocalRandom.current().nextInt(min, max);
   }
   return randomArray;
 }
Exemplo n.º 18
0
 @Test
 @Ignore(
     "Very simple microbenchmark to compare different writeTo implementations. Only for development thus "
         + "ignored.")
 public void testWriteToMicrobenchmark() throws IOException {
   int capacity = 1024 * 128;
   int iterations = 100;
   int testRuns = 10;
   byte[] bytes = new byte[capacity];
   ThreadLocalRandom.current().nextBytes(bytes);
   ByteBuffer buffer = BufferUtil.allocate(capacity);
   BufferUtil.append(buffer, bytes, 0, capacity);
   long startTest = System.nanoTime();
   for (int i = 0; i < testRuns; i++) {
     long start = System.nanoTime();
     for (int j = 0; j < iterations; j++) {
       ByteArrayOutputStream out = new ByteArrayOutputStream();
       long startRun = System.nanoTime();
       BufferUtil.writeTo(buffer.asReadOnlyBuffer(), out);
       long elapsedRun = System.nanoTime() - startRun;
       //                LOG.warn("run elapsed={}ms", elapsedRun / 1000);
       assertThat(
           "Bytes in out equal bytes in buffer",
           Arrays.equals(bytes, out.toByteArray()),
           is(true));
     }
     long elapsed = System.nanoTime() - start;
     LOG.warn("elapsed={}ms average={}ms", elapsed / 1000, elapsed / iterations / 1000);
   }
   LOG.warn(
       "overall average: {}ms", (System.nanoTime() - startTest) / testRuns / iterations / 1000);
 }
Exemplo n.º 19
0
public class DutchNationalFlagTest {
  private ThreadLocalRandom random = ThreadLocalRandom.current();

  @Rule public MockitoRule mrule = MockitoJUnit.rule();

  private int[] createRandomItems(int size) {
    return IntStream.range(0, size).mapToObj(i -> random.nextInt(3)).mapToInt(i -> i).toArray();
  }

  @Test
  public void sort() throws Exception {
    int size = 100;
    int[] items = createRandomItems(size);
    DutchNationalFlag service = spy(new DutchNationalFlag(items));
    service.sort();
    int i = 0;
    while (i < size && items[i++] == 0) ;
    assertTrue(items[i] == 1);
    while (i < size && items[i++] == 1) ;
    assertTrue(items[i] == 2);
    while (i < size && items[i++] == 2) ;
    assertEquals(i, size);
    verify(service, atMost(size)).getColor(anyInt());
    verify(service, atMost(size)).swap(anyInt(), anyInt());
  }
}
Exemplo n.º 20
0
  public static void timeLookup(TreeSet<Integer> tree, long size) {
    tree.contains(7);
    tree.contains(4038);
    tree.contains(2898833);

    int limit = 50000000;
    int randomSize = 1000000;

    // Generate a list of random numbers to get rid of the time it takes
    // to generate the numbers
    ArrayList<Integer> randomNums = new ArrayList<>();
    for (int i = 0; i < randomSize; i++)
      randomNums.add(ThreadLocalRandom.current().nextInt(0, (int) size));

    // Store the overhead of a for loop
    long start = System.nanoTime();
    for (int i = 0; i < limit; i++) ;
    long stop = System.nanoTime();
    long overheadTime = stop - start;

    // Time the lookups
    start = System.nanoTime();
    for (int i = 0; i < limit; i++) tree.contains(randomNums.get(i % randomSize));
    stop = System.nanoTime();

    System.out.println((stop - start - overheadTime) / 1000000);
  }
Exemplo n.º 21
0
 protected int generateRandomIndex() {
   if (tickets.size() == 1) {
     return 0;
   }
   int index = ThreadLocalRandom.current().nextInt(1, tickets.size());
   return index;
 }
Exemplo n.º 22
0
 private void generaCodice() {
   Object[] colori = ColoriDisponibili.disponibili.getColori().keySet().toArray();
   for (int i = 0; i < 4; i++) {
     int indice = ThreadLocalRandom.current().nextInt(0, colori.length);
     codice.aggiungiNumero((Color) colori[indice]);
   }
 }
Exemplo n.º 23
0
  @Override
  public List<FSM> apply(List<FSM> parents) {
    int numberOfStates = parents.get(0).getNumberOfStates();
    int numberOfEvents = parents.get(0).getNumberOfEvents();
    List<String> events = parents.get(0).getEvents();

    int point = ThreadLocalRandom.current().nextInt(parents.get(0).getNumberOfStates());
    FSM.Transition[][] tr0 = new FSM.Transition[numberOfStates][numberOfEvents];
    FSM.Transition[][] tr1 = new FSM.Transition[numberOfStates][numberOfEvents];

    for (int state = 0; state < numberOfStates; state++) {
      if (state < point) {
        tr0[state] =
            Arrays.copyOf(
                parents.get(0).transitions[state], parents.get(0).transitions[state].length);
        tr1[state] =
            Arrays.copyOf(
                parents.get(1).transitions[state], parents.get(1).transitions[state].length);
      } else {
        tr0[state] =
            Arrays.copyOf(
                parents.get(1).transitions[state], parents.get(1).transitions[state].length);
        tr1[state] =
            Arrays.copyOf(
                parents.get(0).transitions[state], parents.get(0).transitions[state].length);
      }
    }

    List<FSM> offspring = new ArrayList<FSM>();
    offspring.add(new FSM(numberOfStates, tr0));
    offspring.add(new FSM(numberOfStates, tr1));
    return offspring;
  }
Exemplo n.º 24
0
  /** ************************ TEST ACCESS ******************************************* */
  @Test
  public void testSearchIterator() throws InterruptedException {
    final int perTreeSelections = 100;
    testRandomSelection(
        perThreadTrees,
        perTreeSelections,
        (test) -> {
          IndexedSearchIterator<Integer, Integer> iter1 = test.testAsSet.iterator();
          IndexedSearchIterator<Integer, Integer> iter2 = test.testAsList.iterator();
          return (key) -> {
            Integer found1 = iter1.hasNext() ? iter1.next(key) : null;
            Integer found2 = iter2.hasNext() ? iter2.next(key) : null;
            Assert.assertSame(found1, found2);
            if (found1 != null) Assert.assertEquals(iter1.indexOfCurrent(), iter2.indexOfCurrent());

            int index = Collections.binarySearch(test.canonicalList, key, test.comparator);
            if (index < 0) {
              Assert.assertNull(found1);
            } else {
              Assert.assertEquals(key, found1);
              Assert.assertEquals(index, iter1.indexOfCurrent());
            }

            // check that by advancing the same key again we get null, but only do it on one of the
            // two iterators
            // to ensure they both advance differently
            if (ThreadLocalRandom.current().nextBoolean()) Assert.assertNull(iter1.next(key));
            else Assert.assertNull(iter2.next(key));
          };
        });
  }
Exemplo n.º 25
0
  @Test
  public void testSpeed() {

    Random rnd = ThreadLocalRandom.current();

    final int IMAGE_SIZE = 28;
    final int BLOCK_COUNT = 10;
    final int FEATURE_SIZE = 9;
    final int FEATURE_COUNT = 10;

    Feature[] features = new Feature[FEATURE_COUNT];
    for (int f = 0; f < features.length; f++) {
      final double mean = f < features.length / 2 ? 0.25 : 0.75;
      features[f] = new Feature(FEATURE_SIZE, mean, 1, Math.pow(0.1, 2), 1);
    }

    byte[][] data = new byte[IMAGE_SIZE][IMAGE_SIZE];
    for (int i = 0; i < data.length; i++) {
      rnd.nextBytes(data[i]);
      if (i < data.length / 2) {
        for (int j = 0; j < data[i].length; j++) {
          data[i][j] = (byte) (+Math.abs(data[i][j]));
        }
      } else {
        for (int j = 0; j < data[i].length; j++) {
          data[i][j] = (byte) (-Math.abs(data[i][j]));
        }
      }
    }

    ByteImage image = new ByteImage(data);
    InferBlocks inferBlocks = new InferBlocks(IMAGE_SIZE, BLOCK_COUNT, features);

    System.out.println("Calculating time...");
    long ms = System.currentTimeMillis();

    for (int s = 1; s <= 10; s++) {

      inferBlocks.infer(image);

      if (s % 10 == 0) {
        System.out.println(
            "Average time (" + s + "): " + (System.currentTimeMillis() - ms) / (double) s);
      }
    }

    System.out.println(
        "Block probs: " + StringUtils.arrayToString(inferBlocks.getBlockProbs(), ", "));
    System.out.println("          X: " + StringUtils.arrayToString(inferBlocks.getBlockX(), ", "));
    System.out.println("          Y: " + StringUtils.arrayToString(inferBlocks.getBlockY(), ", "));

    for (int b = 0; b < BLOCK_COUNT; b++) {
      System.out.println(
          "Block #"
              + (b + 1)
              + " feature probs: "
              + StringUtils.arrayToString(inferBlocks.getBlockFeatureProbs()[b], ", "));
    }
  }
Exemplo n.º 26
0
 private static Block createFixWidthValueBlock(int positionCount, int mapSize) {
   BlockBuilder valueBlockBuilder =
       DOUBLE.createBlockBuilder(new BlockBuilderStatus(), positionCount * mapSize);
   for (int i = 0; i < positionCount * mapSize; i++) {
     DOUBLE.writeDouble(valueBlockBuilder, ThreadLocalRandom.current().nextDouble());
   }
   return valueBlockBuilder.build();
 }
Exemplo n.º 27
0
 @Override
 public void offerSolution() {
   FitInstance<Instance> solution = task.getFitInstance(stats.getBestInstance());
   System.out.println("Offering solution with f = " + solution.getFitness());
   otherAlgorithms
       .get(ThreadLocalRandom.current().nextInt(otherAlgorithms.size()))
       .acceptSolution(solution);
 }
Exemplo n.º 28
0
 private static String randomString(int length) {
   String symbols = "abcdefghijklmnopqrstuvwxyz";
   char[] chars = new char[length];
   for (int i = 0; i < length; i++) {
     chars[i] = symbols.charAt(ThreadLocalRandom.current().nextInt(symbols.length()));
   }
   return new String(chars);
 }
Exemplo n.º 29
0
 private static RandomTree randomTree(int minSize, int maxSize) {
   // perform most of our tree constructions via update, as this is more efficient; since every run
   // uses this
   // we test builder disproportionately more often than if it had its own test anyway
   return ThreadLocalRandom.current().nextFloat() < 0.95
       ? randomTreeByUpdate(minSize, maxSize)
       : randomTreeByBuilder(minSize, maxSize);
 }
  @Test
  public void test() throws Exception {
    MmsClient c = createAndConnect();

    new Thread(
            () -> {
              while (received.size() < NUMBER_OF_MESSAGES) {
                rndSleep(300, TimeUnit.MILLISECONDS);
                t.closeIt();
              }
            })
        .start();

    final AtomicInteger ack = new AtomicInteger();

    Runnable server =
        new Runnable() {
          public void run() {
            int latestId = 0;
            Integer ackIt = null;
            while (received.size() < NUMBER_OF_MESSAGES) {
              Message tm = t.take(Message.class);

              if (tm instanceof Broadcast) {
                Broadcast bs = (Broadcast) tm;
                try {
                  BroadcastTestMessage hw = (BroadcastTestMessage) MmsMessage.tryRead(bs);
                  int id = hw.getId();
                  assertEquals(latestId++, id);
                  received.add(id);
                } catch (Exception e) {
                  e.printStackTrace();
                }
                ackIt = null;
              } else {
                if (ackIt == null) {
                  ackIt = ThreadLocalRandom.current().nextInt(ack.get(), latestId + 1);
                }
                ack.set(ackIt);
                latestId = ackIt;
                t.send(new Connected().setSessionId(BIN1).setLastReceivedMessageId((long) ackIt));
              }
            }
          }
        };
    Thread t = new Thread(server);
    t.setUncaughtExceptionHandler((a, b) -> b.printStackTrace());
    t.start();

    for (int i = 0; i < NUMBER_OF_MESSAGES; i++) {
      Thread.sleep(ThreadLocalRandom.current().nextLong(10));
      c.broadcast(new BroadcastTestMessage().setId(i));
    }

    while (received.size() < NUMBER_OF_MESSAGES) {
      Thread.sleep(10);
    }
  }