Esempio n. 1
1
 @Test
 public void testPutRemoveGet() {
   Map<Integer, Integer> myMap = new MyMap<>();
   Map<Integer, Integer> control = new HashMap<>();
   for (int i = 0; i < N; i++) {
     int k = random.nextInt();
     int v = random.nextInt();
     myMap.put(k, v);
     control.put(k, v);
   }
   Set<Integer> keysToRemove = new HashSet<>();
   for (int k : control.keySet()) {
     if (random.nextBoolean()) {
       keysToRemove.add(k);
     }
   }
   for (int k : keysToRemove) {
     control.remove(k);
     myMap.remove(k);
   }
   assertEquals(myMap.size(), control.size());
   for (int k : control.keySet()) {
     assertEquals(myMap.get(k), control.get(k));
     int r = random.nextInt();
     assertEquals(myMap.get(r), control.get(r));
   }
 }
  @Test
  public void testReverseOrderRandomIntegers() {
    Comparator<Integer> naturalOrder = new NaturalOrder<Integer>();
    Comparator<Integer> reverse = CollectionUtil.reverseOrder(naturalOrder);

    Random random = new Random(243249878l); // Stable "random" sequence

    for (int i = 0; i < 65536; i++) {
      // Verified to be ~ 50/50 lt/gt
      int integer = random.nextInt();
      int integerToo = random.nextInt();

      assertEquals(0, reverse.compare(integer, integer));
      assertEquals(0, reverse.compare(integerToo, integerToo));

      int natural = naturalOrder.compare(integer, integerToo);

      if (natural == 0) {
        // Actually never hits, but eq case is tested above
        assertEquals(0, reverse.compare(integer, integerToo));
      } else if (natural < 0) {
        assertTrue(reverse.compare(integer, integerToo) > 0);
      } else {
        assertTrue(reverse.compare(integer, integerToo) < 0);
      }
    }
  }
Esempio n. 3
0
  @Test
  public void testNoOpUpdater() {
    Random r = new Random(12345L);
    double lr = 0.5;

    NeuralNetConfiguration conf =
        new NeuralNetConfiguration.Builder()
            .learningRate(lr)
            .layer(
                new DenseLayer.Builder()
                    .nIn(nIn)
                    .nOut(nOut)
                    .updater(org.deeplearning4j.nn.conf.Updater.NONE)
                    .build())
            .build();

    int numParams = LayerFactories.getFactory(conf).initializer().numParams(conf, true);
    INDArray params = Nd4j.create(1, numParams);
    Layer layer = LayerFactories.getFactory(conf).create(conf, null, 0, params, true);
    Updater updater = UpdaterCreator.getUpdater(layer);

    for (int i = 0; i < weightGradient.length(); i++) weightGradient.putScalar(i, r.nextDouble());
    for (int i = 0; i < biasGradient.length(); i++) biasGradient.putScalar(i, r.nextDouble());

    gradient.gradientForVariable().put(DefaultParamInitializer.WEIGHT_KEY, weightGradient);
    gradient.gradientForVariable().put(DefaultParamInitializer.BIAS_KEY, biasGradient);

    updater.update(layer, gradient, -1, 1);

    INDArray weightGradActual = gradient.getGradientFor(DefaultParamInitializer.WEIGHT_KEY);
    INDArray biasGradActual = gradient.getGradientFor(DefaultParamInitializer.BIAS_KEY);

    assertEquals(weightGradient, weightGradActual);
    assertEquals(biasGradient, biasGradActual);
  }
Esempio n. 4
0
  @Test
  public void insert_many_reopen_check() throws InterruptedException {
    e = openEngine();
    int max = 1000;
    int size = 100000;
    Random r = new Random(0);
    List<Long> recids = new ArrayList<Long>();
    for (int j = 0; j < max; j++) {
      byte[] b = new byte[r.nextInt(size)];
      r.nextBytes(b);
      long recid = e.put(b, Serializer.BYTE_ARRAY_NOSIZE);
      recids.add(recid);
    }
    e.commit();

    reopen();

    r = new Random(0);
    for (long recid : recids) {
      byte[] b = new byte[r.nextInt(size)];
      r.nextBytes(b);
      byte[] b2 = e.get(recid, Serializer.BYTE_ARRAY_NOSIZE);
      assertTrue("Data were not commited recid=" + recid, Arrays.equals(b, b2));
    }
  }
  @Test(timeout = TIMEOUT)
  public void testQuickSort() {
    DValue[] arrZero = new DValue[0];
    Sorting.quickSort(arrZero, new BasicComparator(), new Random());
    assertEquals(0, arrZero.length);
    DValue[] arrOne = new DValue[1];
    arrOne[0] = new DValue(4, 0);
    Sorting.quickSort(arrOne, new BasicComparator(), new Random());
    assertEquals(1, arrOne.length);
    assertEquals(4, arrOne[0].val.intValue());

    Random rand = new Random();
    HashMap<Integer, Integer> values = new HashMap<Integer, Integer>();
    for (int i = 0; i < 50; i++) {
      int arrlen = rand.nextInt(1000) + 2;
      DValue[] arrMany = new DValue[arrlen];
      DValue[] arrManySorted = new DValue[arrlen];
      for (int j = 0; j < arrlen; j++) {
        arrMany[j] = new DValue(rand.nextInt(200) - 90, 0);
        if (values.containsKey(arrMany[j].val)) {
          arrMany[j].count = values.get(arrMany[j].val) + 1;
          values.put(arrMany[j].val, arrMany[j].count);
        } else {
          values.put(arrMany[j].val, 0);
        }
      }
      System.arraycopy(arrMany, 0, arrManySorted, 0, arrlen);
      Arrays.sort(arrManySorted);
      Sorting.quickSort(arrMany, new BasicComparator(), new Random());
      assertArrayEquals(arrManySorted, arrMany);
    }
  }
  /** RG-1: Tests if a all matchings are correct (on some random graphs). */
  @Test
  public void testRandomGraphs() {
    Random rnd = new Random();
    rnd.setSeed(54321);

    for (int i = 1; i < 50; i++) {
      int vertexCount = 2 + rnd.nextInt(i),
          edgeCount = vertexCount + rnd.nextInt(vertexCount * (vertexCount - 1)) / 2,
          subVertexCount = 1 + rnd.nextInt(vertexCount);

      DirectedGraph<Integer, DefaultEdge>
          g1 = SubgraphIsomorphismTestUtils.randomGraph(vertexCount, edgeCount, i),
          g2 = SubgraphIsomorphismTestUtils.randomSubgraph(g1, subVertexCount, i);

      VF2SubgraphIsomorphismInspector<Integer, DefaultEdge> vf2 =
          new VF2SubgraphIsomorphismInspector<>(g1, g2);

      SubgraphIsomorphismTestUtils.showLog(i + ": " + vertexCount + "v, " + edgeCount + "e ");

      for (Iterator<GraphMapping<Integer, DefaultEdge>> mappings = vf2.getMappings();
          mappings.hasNext(); ) {
        assertEquals(true, SubgraphIsomorphismTestUtils.isCorrectMatching(mappings.next(), g1, g2));
        SubgraphIsomorphismTestUtils.showLog(".");
      }
      SubgraphIsomorphismTestUtils.showLog("\n");
    }
  }
  @Test(timeout = TIMEOUT)
  public void testRadixSort() {
    int[] arrZero = new int[0];
    arrZero = Sorting.radixSort(arrZero);
    assertEquals(0, arrZero.length);
    int[] arrOne = new int[1];
    arrOne[0] = 4;
    arrOne = Sorting.radixSort(arrOne);
    assertEquals(1, arrOne.length);
    assertEquals(4, arrOne[0]);

    Random rand = new Random();
    for (int i = 0; i < 50; i++) {
      int arrlen = rand.nextInt(1000) + 2;
      int[] arrMany = new int[arrlen];
      int[] arrManySorted = new int[arrlen];
      for (int j = 0; j < arrlen; j++) {
        arrMany[j] = rand.nextInt(200) - 90;
      }
      System.arraycopy(arrMany, 0, arrManySorted, 0, arrlen);
      Arrays.sort(arrManySorted);
      arrMany = Sorting.radixSort(arrMany);
      assertArrayEquals(arrManySorted, arrMany);
    }
  }
  @Test
  public void testSendAndReceive() throws Exception {

    // Run the main controller
    ControllerRunner controllerRunner =
        new ControllerRunner(10, 9090, InetAddress.getLocalHost(), "127.0.0.1", 8008);
    controllerRunner.run();
    System.out.println("Controller running");

    Random random = new Random();
    int player = random.nextInt();

    // Connect a new controller and send test alarm
    Controller controller = new Controller(10);
    Socket connection1 = controller.connectTo(InetAddress.getLocalHost().getHostAddress(), 9090);
    Alarm alarm = new Alarm(player, System.currentTimeMillis(), new PlayerCause(player));
    controller.send(alarm, connection1);

    Controller controller2 = new Controller(10);
    Socket connection2 = controller2.connectTo(InetAddress.getLocalHost().getHostAddress(), 9090);
    long alarmtime = System.currentTimeMillis() + 500;
    Position position1 = new Position(player, System.currentTimeMillis(), 1, 2, 3);
    Position position2 = new Position(player, alarmtime, 100, 200, 300);
    controller2.send(position1, connection2);
    controller2.send(position2, connection2);
    controller2.send(new Request(player, DataType.ACCEL, -1, -1), connection2);
    controller2.send(new Request(player, DataType.POS, -1, -1), connection2);

    Thread.sleep(15000);
    List<Sendable> received = controller2.receive(connection2);
    List<Alarm> alarms = new ArrayList<Alarm>();
    List<Acceleration> accelerations = new ArrayList<Acceleration>();
    List<Position> positions = new ArrayList<Position>();

    // Distribute the sendable objects
    for (Sendable sendable : received) {
      if (sendable instanceof Alarm) {
        alarms.add((Alarm) sendable);

      } else if (sendable instanceof Service) {
        Service service = (Service) sendable;
        List<?> data = service.getData();
        for (Object o : data) {
          if (o instanceof Acceleration) {
            accelerations.add((Acceleration) o);
          } else if (o instanceof Position) {
            positions.add((Position) o);
          }
        }
      }
    }

    controller.disconnectFromClient(connection1);
    controller2.disconnectFromClient(connection2);

    assertTrue("Alarm was not sent from controller", alarms.size() >= 1);
    assertTrue("Acceleration not received from controller", accelerations.size() >= 1);
    assertTrue("Position 1 not contained in received positions", positions.contains(position1));
    assertTrue("Position 2 not contained in received positions", positions.contains(position2));
  }
Esempio n. 9
0
 public Object call() throws Exception {
   _barrier.await(); // barrier, to force racing start
   for (long j = 0; j < _count; j++)
     _map.put(
         j + _offset,
         new TestKey(_rand.nextLong(), _rand.nextInt(), (short) _rand.nextInt(Short.MAX_VALUE)));
   return null;
 }
Esempio n. 10
0
 @Before
 public void setUp() throws Exception {
   testProject_1 = new Project("Test The Project of the First Non-Sense");
   s = new Student("test student");
   testProject_rest = new ArrayList<Project>();
   Random r = new Random();
   for (int i = 0; i < 50; i++)
     testProject_rest.add(new Project("test project another " + r.nextInt()));
   preped_s = new Student("I'm prepared");
   for (Project p : testProject_rest) {
     preped_s.addProject(p);
   }
 }
Esempio n. 11
0
  /** Test that new records can be continuously added without hitting {@link OutOfMemoryError}. */
  @Test
  @Ignore("Start this test with a small heap size (e.g. -Xmx64m)")
  public void testPerformance() {
    final Random random = new Random(System.nanoTime());

    while (true) {
      final byte[] key = new byte[100];
      random.nextBytes(key);
      final int size = random.nextInt();
      final long pointer = random.nextLong();

      cache.add(key, size, pointer);
    }
  }
Esempio n. 12
0
  @Test
  public void cas_uses_serializer() {
    Random r = new Random();
    byte[] data = new byte[1024];
    r.nextBytes(data);

    e = openEngine();
    long recid = e.put(data, Serializer.BYTE_ARRAY);

    byte[] data2 = new byte[100];
    r.nextBytes(data2);
    assertTrue(e.compareAndSwap(recid, data.clone(), data2.clone(), Serializer.BYTE_ARRAY));

    assertTrue(Serializer.BYTE_ARRAY.equals(data2, e.get(recid, Serializer.BYTE_ARRAY)));
    e.close();
  }
Esempio n. 13
0
 private long[] randomArray(int n) {
   long[] A = new long[n];
   for (int i = 0; i < A.length; i++) {
     A[i] = random.nextInt(1000);
   }
   return A;
 }
Esempio n. 14
0
 @Test
 public void testPutGet() {
   Map<Integer, Integer> myMap = new MyMap<>();
   Map<Integer, Integer> control = new HashMap<>();
   for (int i = 0; i < N; i++) {
     int k = random.nextInt();
     int v = random.nextInt();
     myMap.put(k, v);
     control.put(k, v);
   }
   for (int k : control.keySet()) {
     assertEquals(myMap.get(k), control.get(k));
     int r = random.nextInt();
     assertEquals(myMap.get(r), control.get(r));
   }
 }
Esempio n. 15
0
  private void closeDoc(XInterface xDoc) {
    m_aLog.log(Protocol.TYPE_SCOPE_OPEN, "closeDoc() started ...");

    try {
      Random aRandom = new Random();
      int nRetry = 5;
      while (nRetry > 0) {
        try {
          XCloseable xClose = UnoRuntime.queryInterface(XCloseable.class, xDoc);
          if (xClose != null) {
            xClose.close(false);
            m_aLog.log(Protocol.TYPE_OK, "closeDoc() = OK.");
            nRetry = 0;
          } else {
            m_aLog.log(
                Protocol.TYPE_ERROR, "closeDoc() = ERROR. Doc doesn't provide needed interface!");
          }
        } catch (com.sun.star.util.CloseVetoException exVeto) {
          m_aLog.log(Protocol.TYPE_WARNING, "got CloseVetoException on calling doc.close().");
          m_aLog.log(
              Protocol.TYPE_WARNING_INFO, "Please check the reason for that more in detail.");
          m_aLog.log(
              Protocol.TYPE_WARNING_INFO,
              "A message like \"Can not close while saving.\" was intended and doesn't show an error!");
          m_aLog.log(Protocol.TYPE_WARNING_INFO, exVeto.getMessage());
        }

        if (nRetry > 0) {
          --nRetry;
          long nWait = aRandom.nextInt(30000); // 30 sec.
          try {
            m_aLog.log(Protocol.TYPE_INFO, "sleep for " + nWait + " ms");
            synchronized (this) {
              wait(nWait);
            }
          } catch (Throwable ex) {
            m_aLog.log(Protocol.TYPE_WARNING, "got exception for wait() !?");
            m_aLog.log(Protocol.TYPE_WARNING_INFO, ex.getMessage());
          }
        }
      }
    } catch (Throwable ex) {
      m_aLog.log(ex);
    }

    m_aLog.log(Protocol.TYPE_SCOPE_CLOSE, "closeDoc() finished.");
  }
  @Test
  public void testHashRandom() {
    int max = 1000000;
    TOKEN_SCALE = new BigInteger("" + max);

    mts = new MerkleTrees(partitioner);
    mts.addMerkleTree(32, fullRange());

    Random random = new Random();
    while (true) {
      if (!mts.split(tok(random.nextInt(max)))) break;
    }

    // validate the tree
    TreeRangeIterator ranges = mts.invalids();
    for (TreeRange range : ranges) range.addHash(new RowHash(range.right, new byte[0], 0));

    assert mts.hash(new Range<>(tok(-1), tok(-1))) != null : "Could not hash tree " + mts;
  }
Esempio n. 17
0
  @Test
  public void randomStructuralCheck() {
    Random r = new Random();
    BTreeMap map =
        DBMaker.memoryDB()
            .transactionDisable()
            .make()
            .treeMapCreate("aa")
            .keySerializer(BTreeKeySerializer.INTEGER)
            .valueSerializer(Serializer.INTEGER)
            .make();

    int max = 100000 * TT.scale();

    for (int i = 0; i < max * 10; i++) {
      map.put(r.nextInt(max), r.nextInt());
    }

    map.checkStructure();
  }
Esempio n. 18
0
  public void impl_checkConcurrentAutoSaveToNormalUISave() {
    Random aRandom = new Random();

    int i = 0;
    int c = 5;
    for (i = 0; i < c; ++i) {
      XInterface xDoc = createBigCalcDoc();
      try {
        long nWait = aRandom.nextInt(120000);
        m_aLog.log(Protocol.TYPE_INFO, "sleep for " + nWait + " ms");
        synchronized (this) {
          wait(nWait);
        }
      } catch (Throwable ex) {
        m_aLog.log(Protocol.TYPE_WARNING, "got exception for wait() !?");
        m_aLog.log(Protocol.TYPE_WARNING_INFO, ex.getMessage());
      }
      saveDoc(xDoc, utils.getOfficeTemp(m_xSMGR) + "/test_calc.ods");
      closeDoc(xDoc);
    }
  }
Esempio n. 19
0
  public static void benchIO(LargeByteList target, String name, int unit, int iteration) {
    Random ra = new Random();
    byte[] buf_set = new byte[unit];
    byte[] buf_get = new byte[unit];
    long start, elapse_set, elapse_get;
    int i;

    elapse_set = 0;
    elapse_get = 0;
    for (i = 0; i < iteration; i++) {
      // init
      for (int j = 0; j < buf_set.length; j++) {
        buf_set[j] = (byte) ra.nextInt(255);
      }

      // set
      start = System.nanoTime();
      for (int j = 0; j < target.length(); j += buf_set.length) {
        target.set(j, buf_set, 0, buf_set.length);
      }
      elapse_set += (System.nanoTime() - start);

      // get
      start = System.nanoTime();
      for (int j = 0; j < target.length(); j += buf_get.length) {
        target.get(j, buf_get, 0, buf_get.length);
      }
      elapse_get += (System.nanoTime() - start);

      // verify
      for (int j = 0; j < buf_get.length; j++) {
        if (buf_get[j] != buf_set[j]) {
          assertEquals("failed to verify at " + j, buf_set[j], buf_get[j]);
        }
      }
    }

    LargeByteListTest.printBenchResult(name + "(rd)", iteration * target.length(), elapse_get);
    LargeByteListTest.printBenchResult(name + "(wr)", iteration * target.length(), elapse_set);
  }
Esempio n. 20
0
 @Test
 public void testAddValueToRange() {
   int n = 500;
   long[] A = randomArray(n);
   FenwickTree fw = fenwickTree(A);
   for (int i = 0; i < A.length; i++) {
     for (int j = i; j < A.length; j++) {
       long value = random.nextInt(100);
       addValueToRange(A, i, j, value);
       fw.addValueToRange(i + 1, j + 1, value);
     }
   }
   long[] B = fw.toArray();
   assertArrayEquals(A, B);
 }
  /** RG-2: Tests if all matchings are correct and if every matching is found (on random graphs). */
  @Test
  public void testRandomGraphsExhaustive() {
    Random rnd = new Random();
    rnd.setSeed(12345);

    for (int i = 1; i < 100; i++) {
      int vertexCount = 3 + rnd.nextInt(5),
          edgeCount = rnd.nextInt(vertexCount * (vertexCount - 1)),
          subVertexCount = 2 + rnd.nextInt(vertexCount),
          subEdgeCount = rnd.nextInt(subVertexCount * (subVertexCount - 1));

      DirectedGraph<Integer, DefaultEdge>
          g1 = SubgraphIsomorphismTestUtils.randomGraph(vertexCount, edgeCount, i),
          g2 = SubgraphIsomorphismTestUtils.randomGraph(subVertexCount, subEdgeCount, i);

      VF2SubgraphIsomorphismInspector<Integer, DefaultEdge> vf2 =
          new VF2SubgraphIsomorphismInspector<>(g1, g2);

      SubgraphIsomorphismTestUtils.showLog(i + ": " + vertexCount + "v, " + edgeCount + "e ....\n");

      assertEquals(true, SubgraphIsomorphismTestUtils.containsAllMatchings(vf2, g1, g2));
    }
  }
 private static List<Integer> makeRandomNumberList(int size) {
   List<Integer> r = new ArrayList<>();
   Random random = new Random();
   while (--size > 0) r.add(random.nextInt());
   return r;
 }
Esempio n. 23
0
  @Test
  public void recover_with_interrupt() throws InterruptedException {
    int scale = TT.scale();
    if (scale == 0) return;
    e = openEngine();
    if (!e.canRollback()
        || e instanceof StoreHeap) // TODO engine might have crash recovery, but no rollbacks
    return;

    // fill recids
    final int max = scale * 1000;
    final ArrayList<Long> recids = new ArrayList<Long>();
    final AtomicLong a = new AtomicLong(10);
    final long counterRecid = e.put(a.get(), Serializer.LONG);
    Random r = new Random(a.get());
    for (int j = 0; j < max; j++) {
      byte[] b = new byte[r.nextInt(100000)];
      r.nextBytes(b);
      long recid = e.put(b, Serializer.BYTE_ARRAY_NOSIZE);
      recids.add(recid);
    }

    e.commit();

    long endTime = TT.nowPlusMinutes(10);

    while (endTime > System.currentTimeMillis()) {

      final CountDownLatch latch = new CountDownLatch(1);
      Thread t =
          new Thread() {
            @Override
            public void run() {
              try {
                for (; ; ) {
                  long A = a.incrementAndGet();
                  Random r = new Random(A);
                  e.update(counterRecid, A, Serializer.LONG);

                  for (long recid : recids) {
                    byte[] b = new byte[r.nextInt(100000)];
                    r.nextBytes(b);
                    e.update(recid, b, Serializer.BYTE_ARRAY_NOSIZE);
                  }
                  e.commit();
                }
              } finally {
                latch.countDown();
              }
            }
          };
      t.start();
      Thread.sleep(5000);
      t.stop();
      latch.await();
      if (!e.isClosed()) {
        close();
      }

      // reopen and check the content
      e = openEngine();

      // check if A-1 was commited
      long A = e.get(counterRecid, Serializer.LONG);
      assertTrue("" + A + " - " + a.get(), A == a.get() || A == a.get() - 1);
      r = new Random(A);
      for (long recid : recids) {
        byte[] b = new byte[r.nextInt(100000)];
        r.nextBytes(b);
        byte[] b2 = e.get(recid, Serializer.BYTE_ARRAY_NOSIZE);
        assertTrue("Data were not commited recid=" + recid, Arrays.equals(b, b2));
      }
      a.set(A);
    }
    e.close();
  }