Esempio n. 1
0
  // Note this is a bit of a integration test not a strict unit test
  @Test
  public void testFillingAMoreComplicatedBoundingRectangle() throws Exception {
    double xStart = 0.0;
    double xStop = 25.5;
    double yStart = 0.0;
    double yStop = 33.33;

    double xStep = 0.4;
    double yStep = 0.6;

    RectangularROI roi = new RectangularROI();
    roi.setPoint(Math.min(xStart, xStop), Math.min(yStart, yStop));
    roi.setLengths(Math.abs(xStop - xStart), Math.abs(yStop - yStart));

    RasterModel model = new RasterModel();
    model.setxStep(xStep);
    model.setyStep(yStep);

    // Get the point list
    IPointGenerator<RasterModel, Point> gen = service.createGenerator(model, roi);
    List<Point> pointList = gen.createPoints();

    int rows = (int) (Math.floor((xStop - xStart) / xStep) + 1);
    int cols = (int) (Math.floor((yStop - yStart) / yStep) + 1);
    // Check the list size
    assertEquals("Point list size should be correct", rows * cols, pointList.size());

    // Check some points
    assertEquals(new Point(0, xStart, 0, yStart), pointList.get(0));
    assertEquals(xStart + 3 * xStep, pointList.get(3).getX(), 1e-8);
    // TODO more

    GeneratorUtil.testGeneratorPoints(gen);
  }
  private static List<double[]> findNeighbors(
      List<double[]> data, double[] target, double maxDistance, int maxN) {
    List<double[]> ret = new ArrayList<double[]>();

    List<double[]> found = new ArrayList<double[]>();
    GrowQueue_F64 distances = new GrowQueue_F64();
    GrowQueue_I32 indexes = new GrowQueue_I32();

    for (int i = 0; i < data.size(); i++) {
      double[] d = data.get(i);

      double dx = d[0] - target[0];
      double dy = d[1] - target[1];

      double dist = dx * dx + dy * dy;
      if (dist <= maxDistance) {
        distances.add(dist);
        found.add(d);
      }
    }

    indexes.resize(distances.size);

    maxN = Math.min(maxN, distances.size);

    QuickSelectArray.selectIndex(distances.data, maxN, distances.size, indexes.data);

    for (int i = 0; i < maxN; i++) {
      ret.add(found.get(indexes.data[i]));
    }

    return ret;
  }
  @Test
  public void candidatesCountDuplicatesTest() {
    for (int parameters : new int[] {1, 2, 5}) {
      for (int choices : new int[] {1, 2, 5}) {
        for (int candidatesCount : new int[] {10, 100}) {
          for (int steps : new int[] {0, 1, 10, 100}) {
            try {
              //				System.out.println("parameters: " + parameters + ", choices: " + choices + ",
              // candidatesCount: " + candidatesCount + ", steps: " + steps);
              List<List<String>> input = GeneratorTestUtils.prepareInput(parameters, choices);
              AdaptiveRandomAlgorithm<String> algorithm =
                  new AdaptiveRandomAlgorithm<String>(0, candidatesCount, Integer.MAX_VALUE, true);
              algorithm.initialize(input, EMPTY_CONSTRAINTS);
              for (int i = 0; i < steps; i++) {
                algorithm.getNext();
              }

              List<List<String>> candidates = algorithm.getCandidates();
              assertEquals(Math.min(candidatesCount, productSize(input)), candidates.size());
            } catch (GeneratorException e) {
              fail("Unexpected GeneratorException: " + e.getMessage());
            }
          }
        }
      }
    }
  }
Esempio n. 4
0
 private long getMin(long[] A, int high) {
   long min = A[0];
   for (int i = 1; i <= high; i++) {
     min = Math.min(min, A[i]);
   }
   return min;
 }
Esempio n. 5
0
  @Test
  public void test_find_children_2() {
    for (boolean left : new boolean[] {true, false}) {
      for (boolean right : new boolean[] {true, false}) {
        List keys = new ArrayList();
        for (int i = 0; i < 100; i += 10) {
          keys.add(i);
        }

        int[] child = new int[keys.size() + (right ? 1 : 0) + (left ? 1 : 0)];
        Arrays.fill(child, 11);
        if (right) child[child.length - 1] = 0;

        BTreeMap.BNode n = new BTreeMap.DirNode(keys.toArray(), left, right, false, mkchild(child));

        for (int i = -10; i < 110; i++) {
          int pos = BTreeKeySerializer.BASIC.findChildren(n, i);
          int expected = (i + (left ? 19 : 9)) / 10;
          expected = Math.max(left ? 1 : 0, expected);
          expected = Math.min(left ? 11 : 10, expected);
          assertEquals("i:" + i + " - l:" + left + " - r:" + right, expected, pos);
        }
      }
    }
  }
Esempio n. 6
0
 private static void compareContent(String name, String expectedFile, String actualFile) {
   String[] expectedLines = expectedFile.split("(\\r?\\n)");
   String[] actualLines = actualFile.split("(\\r?\\n)");
   if (expectedLines[0].startsWith("// Generated by delombok at ")) {
     expectedLines[0] = "";
   }
   if (actualLines[0].startsWith("// Generated by delombok at ")) {
     actualLines[0] = "";
   }
   expectedLines = removeBlanks(expectedLines);
   actualLines = removeBlanks(actualLines);
   int size = Math.min(expectedLines.length, actualLines.length);
   for (int i = 0; i < size; i++) {
     String expected = expectedLines[i];
     String actual = actualLines[i];
     assertEquals(String.format("Difference in %s on line %d", name, i + 1), expected, actual);
   }
   if (expectedLines.length > actualLines.length) {
     fail(
         String.format(
             "Missing line %d in generated %s: %s", size + 1, name, expectedLines[size]));
   }
   if (expectedLines.length < actualLines.length) {
     fail(String.format("Extra line %d in generated %s: %s", size + 1, name, actualLines[size]));
   }
 }
Esempio n. 7
0
  private static void compareContent(String name, String expectedFile, String actualFile) {
    String[] expectedLines = expectedFile.split("(\\r?\\n)");
    String[] actualLines = actualFile.split("(\\r?\\n)");

    for (int i = 0; i < expectedLines.length; i++) {
      if (expectedLines[i].isEmpty() || expectedLines[i].startsWith("//")) expectedLines[i] = "";
      else break;
    }
    for (int i = 0; i < actualLines.length; i++) {
      if (actualLines[i].isEmpty() || actualLines[i].startsWith("//")) actualLines[i] = "";
      else break;
    }
    expectedLines = removeBlanks(expectedLines);
    actualLines = removeBlanks(actualLines);

    int size = Math.min(expectedLines.length, actualLines.length);
    if (size == 0 && expectedLines.length + actualLines.length > 0) {
      Assert.fail("Missing / empty expected file.");
    }

    for (int i = 0; i < size; i++) {
      String expected = trimRight(expectedLines[i]);
      String actual = trimRight(actualLines[i]);
      assertEquals(String.format("Difference in %s on line %d", name, i + 1), expected, actual);
    }
    if (expectedLines.length > actualLines.length) {
      fail(
          String.format(
              "Missing line %d in generated %s: %s", size + 1, name, expectedLines[size]));
    }
    if (expectedLines.length < actualLines.length) {
      fail(String.format("Extra line %d in generated %s: %s", size + 1, name, actualLines[size]));
    }
  }
  @Test
  public void optimalCandidateTest() {
    for (int historySize : new int[] {0, 1, 5, Integer.MAX_VALUE}) {
      for (int candidatesSize : new int[] {1, 10, 100}) {
        for (int length : new int[] {10000}) {
          for (boolean duplicates : new boolean[] {true, false}) {
            for (int parameters : new int[] {1, 2, 5}) {
              for (int choices : new int[] {1, 2, 5}) {
                try {
                  AdaptiveRandomAlgorithm<String> algorithm =
                      new AdaptiveRandomAlgorithm<String>(
                          historySize, candidatesSize, length, duplicates);
                  algorithm.initialize(
                      GeneratorTestUtils.prepareInput(parameters, choices), EMPTY_CONSTRAINTS);

                  List<List<String>> candidates = algorithm.getCandidates();
                  List<List<String>> history = algorithm.getCandidates();
                  List<String> optimalCandidate =
                      algorithm.getOptimalCandidate(candidates, history);

                  int optimalCandidateDistance = Integer.MAX_VALUE;
                  for (List<String> event : history) {
                    optimalCandidateDistance =
                        Math.min(
                            algorithm.distance(event, optimalCandidate), optimalCandidateDistance);
                  }
                  for (List<String> candidate : candidates) {
                    int candidateDistance = Integer.MAX_VALUE;
                    for (List<String> event : history) {
                      int eventDistance = algorithm.distance(candidate, event);
                      candidateDistance = Math.min(candidateDistance, eventDistance);
                    }
                    assertTrue(candidateDistance <= optimalCandidateDistance);
                  }
                } catch (GeneratorException e) {
                  fail("Unexpected GeneratorException: " + e.getMessage());
                }
              }
            }
          }
        }
      }
    }
  }
Esempio n. 9
0
  @Test
  public void par_update_get_compact() throws InterruptedException {
    int scale = TT.scale();
    if (scale == 0) return;
    int threadNum = Math.min(4, scale * 4);
    final long end = TT.nowPlusMinutes(10);
    e = openEngine();
    final BlockingQueue<Fun.Pair<Long, byte[]>> q = new ArrayBlockingQueue(threadNum * 10);
    for (int i = 0; i < threadNum; i++) {
      byte[] b = TT.randomByteArray(new Random().nextInt(10000));
      long recid = e.put(b, BYTE_ARRAY_NOSIZE);
      q.put(new Fun.Pair(recid, b));
    }

    final CountDownLatch l = new CountDownLatch(2);
    Thread tt =
        new Thread() {
          @Override
          public void run() {
            try {
              while (l.getCount() > 1) e.compact();
            } finally {
              l.countDown();
            }
          }
        };
    tt.setDaemon(true);
    tt.run();

    Exec.execNTimes(
        threadNum,
        new Callable() {
          @Override
          public Object call() throws Exception {
            Random r = new Random();
            while (System.currentTimeMillis() < end) {
              Fun.Pair<Long, byte[]> t = q.take();
              assertTrue(
                  Serializer.BYTE_ARRAY.equals(t.b, e.get(t.a, Serializer.BYTE_ARRAY_NOSIZE)));
              int size = r.nextInt(1000);
              if (r.nextInt(10) == 1) size = size * 100;
              byte[] b = TT.randomByteArray(size);
              e.update(t.a, b, Serializer.BYTE_ARRAY_NOSIZE);
              q.put(new Fun.Pair<Long, byte[]>(t.a, b));
            }
            return null;
          }
        });
    l.countDown();
    l.await();

    for (Fun.Pair<Long, byte[]> t : q) {
      assertTrue(Serializer.BYTE_ARRAY.equals(t.b, e.get(t.a, Serializer.BYTE_ARRAY_NOSIZE)));
    }
    e.close();
  }
  @Test
  @Ignore
  public void testCHMAcquirePerf()
      throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException,
          InterruptedException {
    for (int runs : new int[] {10, 50, 250, 1000, 2500}) {
      System.out.println("Testing " + runs + " million entries");
      final long entries = runs * 1000 * 1000L;
      final ConcurrentMap<String, AtomicInteger> map =
          new ConcurrentHashMap<String, AtomicInteger>((int) (entries * 5 / 4), 1.0f, 1024);

      int procs = Runtime.getRuntime().availableProcessors();
      int threads = procs * 2;
      int count = runs > 500 ? runs > 1200 ? 1 : 2 : 3;
      final int independence = Math.min(procs, runs > 500 ? 8 : 4);
      for (int j = 0; j < count; j++) {
        long start = System.currentTimeMillis();
        ExecutorService es = Executors.newFixedThreadPool(procs);
        for (int i = 0; i < threads; i++) {
          final int t = i;
          es.submit(
              new Runnable() {
                @Override
                public void run() {
                  StringBuilder sb = new StringBuilder();
                  int next = 50 * 1000 * 1000;
                  // use a factor to give up to 10 digit numbers.
                  int factor = Math.max(1, (int) ((10 * 1000 * 1000 * 1000L - 1) / entries));
                  for (long i = t % independence; i < entries; i += independence) {
                    sb.setLength(0);
                    sb.append("u:");
                    sb.append(i * factor);
                    String key = sb.toString();
                    AtomicInteger count = map.get(key);
                    if (count == null) {
                      map.put(key, new AtomicInteger());
                      count = map.get(key);
                    }
                    count.getAndIncrement();
                    if (t == 0 && i == next) {
                      System.out.println(i);
                      next += 50 * 1000 * 1000;
                    }
                  }
                }
              });
        }
        es.shutdown();
        es.awaitTermination(10, TimeUnit.MINUTES);
        printStatus();
        long time = System.currentTimeMillis() - start;
        System.out.printf("Throughput %.1f M ops/sec%n", threads * entries / 1000.0 / time);
      }
    }
  }
Esempio n. 11
0
 private void testRecoveryWithBadMessageSize(List<Record> records, int size) throws IOException {
   LogSegment seg = this.store.log().lastSegment();
   writeToOffset(seg.file(), seg.file().length(), ByteBuffer.allocate(4).putInt(size).array());
   // now add some message bytes, but not enough
   if (size > 0)
     writeToOffset(
         seg.file(), seg.file().length(), ByteBuffer.allocate(Math.min(size - 1, 256)).array());
   this.store.close();
   this.store = new HashStore(config);
   assertEquals("Same records should be present after close and re-open", records, records(store));
 }
  @Test
  @Ignore
  public void testAcquirePerf()
      throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException,
          InterruptedException {
    //        int runs = Integer.getInteger("runs", 10);
    for (int runs : new int[] {10, 50, 250, 1000, 2500}) {
      final long entries = runs * 1000 * 1000L;
      final SharedHashMap<CharSequence, LongValue> map = getSharedMap(entries * 4 / 3, 1024, 24);

      int procs = Runtime.getRuntime().availableProcessors();
      int threads = procs * 2;
      int count = runs > 500 ? runs > 1200 ? 1 : 2 : 3;
      final int independence = Math.min(procs, runs > 500 ? 8 : 4);
      for (int j = 0; j < count; j++) {
        long start = System.currentTimeMillis();
        ExecutorService es = Executors.newFixedThreadPool(procs);
        for (int i = 0; i < threads; i++) {
          final int t = i;
          es.submit(
              new Runnable() {
                @Override
                public void run() {
                  LongValue value = nativeLongValue();
                  StringBuilder sb = new StringBuilder();
                  int next = 50 * 1000 * 1000;
                  // use a factor to give up to 10 digit numbers.
                  int factor = Math.max(1, (int) ((10 * 1000 * 1000 * 1000L - 1) / entries));
                  for (long i = t % independence; i < entries; i += independence) {
                    sb.setLength(0);
                    sb.append("u:");
                    sb.append(i * factor);
                    map.acquireUsing(sb, value);
                    long n = value.addAtomicValue(1);
                    assert n >= 0 && n < 1000 : "Counter corrupted " + n;
                    if (t == 0 && i == next) {
                      System.out.println(i);
                      next += 50 * 1000 * 1000;
                    }
                  }
                }
              });
        }
        es.shutdown();
        es.awaitTermination(runs / 10 + 1, TimeUnit.MINUTES);
        long time = System.currentTimeMillis() - start;
        System.out.printf(
            "Throughput %.1f M ops/sec%n", threads * entries / independence / 1000.0 / time);
      }
      printStatus();
      map.close();
    }
  }
Esempio n. 13
0
    public int read(ByteBuffer dst) throws IOException {
      if (readIndex >= writeIndex) {
        return -1;
      }

      int actualLengthToRead = Math.min(dst.limit(), writeIndex - readIndex);
      try {
        dst.put(bytes, readIndex, actualLengthToRead);
        return actualLengthToRead;
      } finally {
        readIndex += actualLengthToRead;
      }
    }
Esempio n. 14
0
 @Test
 @PerfTest(
     duration = 3000,
     threads = 2,
     timer = ConstantTimer.class,
     timerParams = {700})
 public void test2() throws Exception {
   long currentTime = System.currentTimeMillis();
   if (test2First == -1) test2First = currentTime;
   test2Last = currentTime;
   System.out.println(
       "test2 - "
           + Thread.currentThread()
           + " - "
           + (currentTime - Math.min(test1First, test2First)));
 }
Esempio n. 15
0
  // ==========================================================================
  /*@Test*/ public void testBasicCRUD() {
    // Parse a file with many broken enum/string columns
    Key k = Key.make("zip.hex");
    try {
      Frame fr = TestUtil.parseFrame(k, "smalldata/zip_code/zip_code_database.csv.gz");
      System.out.println(fr);

      StringBuilder sb = new StringBuilder();
      String[] fs = fr.toStringHdr(sb);
      int lim = Math.min(40, (int) fr.numRows());
      for (int i = 0; i < lim; i++) fr.toString(sb, fs, i);
      System.out.println(sb.toString());
    } finally {
      UKV.remove(k);
    }
  }
  public void testSearch(String[] record, int topDocLimit, int resultLimit) {
    SynonymRecordSearcher recSearcher = new SynonymRecordSearcher(record.length);
    for (int i = 0; i < record.length; i++) {
      initIdx(
          PluginUtil.getPluginInstallPath(HandLuceneImplTest.PLUGIN_ID).concat("data/idx")
              + (i + 1));
      SynonymIndexSearcher searcher =
          new SynonymIndexSearcher(
              PluginUtil.getPluginInstallPath(HandLuceneImplTest.PLUGIN_ID).concat("data/idx")
                  + (i + 1));
      searcher.setTopDocLimit(topDocLimit);
      recSearcher.addSearcher(searcher, i);
    }

    try {
      TopDocs topDocs;
      int hits = 1;
      for (int i = 0; i < record.length; i++) {
        topDocs = recSearcher.getSearcher(i).searchDocumentBySynonym(record[i]);
        hits *= topDocs.totalHits;
      }

      List<OutputRecord> results = recSearcher.search(resultLimit, record);
      Assert.assertNotNull(results);
      Assert.assertFalse(results.isEmpty());
      for (OutputRecord outputRecord : results) {
        Assert.assertNotNull(outputRecord);
        String[] resultingRecord = outputRecord.getRecord();
        Assert.assertEquals(record.length, resultingRecord.length);
        System.out.println(StringUtils.join(resultingRecord, '|'));
        System.out.println("\t" + outputRecord.getScore());
      }
      Assert.assertEquals(Math.min(hits, resultLimit), results.size());

      for (int i = 0; i < record.length; i++) {
        recSearcher.getSearcher(i).close();
      }
    } catch (ParseException e) {
      e.printStackTrace();
      fail("should not get an exception here");
    } catch (IOException e) {
      e.printStackTrace();
      fail("should not get an exception here");
    }
    System.out.println("");
  }
 private void put(File target, long size) throws IOException {
   byte[] buf = "Hello, world\n".getBytes();
   long rest = size;
   target.getParentFile().mkdirs();
   OutputStream out = new FileOutputStream(target);
   try {
     OutputStream bufferred = new BufferedOutputStream(out);
     while (rest > 0) {
       int count = (int) Math.min(buf.length, rest);
       bufferred.write(buf, 0, count);
       rest -= count;
     }
     bufferred.close();
   } finally {
     out.close();
   }
 }
Esempio n. 18
0
  @Test
  public void testGrafo() {
    for (int i = 0; i < 100000000; i++) {
      Math.random();
    }

    GrafoPredicados grafo = generateStar(10, 10, 8);
    ArrayList<Tuple<Integer, Integer>> aristas = generateAristas(10, 10);
    int cantAristas = aristas.size();

    for (int i = 0; i < cantAristas; i++) {
      for (int j = 0; j < 100; j++) {
        Tuple<Integer, Integer> tuple = aristas.get(0);
        aristas.remove(0);
        grafo.connectMateria(tuple.getX(), tuple.getY());
      }

      double tiempoFinal = 0;
      Ejercicio3 ej;
      int conflictos1 = Integer.MAX_VALUE;
      for (int j = 0; j < 3; j++) {
        ej = new Ejercicio3(grafo);
        double tiempo = System.nanoTime();
        conflictos1 = Math.min(conflictos1, ej.checkColoreoFinal());
        tiempoFinal += (System.nanoTime() - tiempo) / 1000;
      }
      System.out.print(tiempoFinal + ";" + conflictos1 + ";");

      conflictos1 = 0;
      for (int j = 0; j < 3; j++) {
        Ejercicio2 ej2 = new Ejercicio2(grafo);
        double tiempo = System.nanoTime();
        if (ej2.solverWithBacktrack()) {
          conflictos1 = 0;
        } else {
          conflictos1 = 1;
        }
        tiempoFinal += (System.nanoTime() - tiempo) / 1000;
      }
      System.out.print(tiempoFinal + ";" + conflictos1 + ";");

      System.out.println();
    }
  }
Esempio n. 19
0
  //	@Test
  public void testEstrella() {
    for (int i = 0; i < 100000000; i++) {
      Math.random();
    }

    for (int i = 0; i < 1000; i++) {
      double tiempoFinal = 0;
      Ejercicio3 ej;
      GrafoPredicados grafo = generateStar(i, i, 100);
      int conflictos1 = Integer.MAX_VALUE;
      for (int j = 0; j < 3; j++) {
        ej = new Ejercicio3(grafo);
        double tiempo = System.nanoTime();
        conflictos1 = Math.min(conflictos1, ej.checkColoreo());
        tiempoFinal += (System.nanoTime() - tiempo) / 1000;
      }
      System.out.println(tiempoFinal + ";" + conflictos1);
    }
  }
Esempio n. 20
0
  /**
   * Utility to test blob POST, GET, HEAD and DELETE operations for a specified size
   *
   * @param contentSize the size of the blob to be tested
   * @param multipartPost {@code true} if multipart POST is desired, {@code false} otherwise.
   * @throws Exception
   */
  private void doPostGetHeadDeleteTest(int contentSize, boolean multipartPost) throws Exception {
    ByteBuffer content = ByteBuffer.wrap(RestTestUtils.getRandomBytes(contentSize));
    String serviceId = "postGetHeadDeleteServiceID";
    String contentType = "application/octet-stream";
    String ownerId = "postGetHeadDeleteOwnerID";
    HttpHeaders headers = new DefaultHttpHeaders();
    setAmbryHeaders(headers, content.capacity(), 7200, false, serviceId, contentType, ownerId);
    headers.set(HttpHeaders.Names.CONTENT_LENGTH, content.capacity());
    String blobId;
    byte[] usermetadata = null;
    if (multipartPost) {
      usermetadata = UtilsTest.getRandomString(32).getBytes();
      blobId = multipartPostBlobAndVerify(headers, content, ByteBuffer.wrap(usermetadata));
    } else {
      headers.add(RestUtils.Headers.USER_META_DATA_HEADER_PREFIX + "key1", "value1");
      headers.add(RestUtils.Headers.USER_META_DATA_HEADER_PREFIX + "key2", "value2");
      blobId = postBlobAndVerify(headers, content);
    }
    getBlobAndVerify(blobId, null, headers, content);
    getHeadAndVerify(blobId, null, headers);
    ByteRange range =
        ByteRange.fromLastNBytes(ThreadLocalRandom.current().nextLong(content.capacity() + 1));
    getBlobAndVerify(blobId, range, headers, content);
    getHeadAndVerify(blobId, range, headers);
    if (contentSize > 0) {
      range = ByteRange.fromStartOffset(ThreadLocalRandom.current().nextLong(content.capacity()));
      getBlobAndVerify(blobId, range, headers, content);
      getHeadAndVerify(blobId, range, headers);
      long random1 = ThreadLocalRandom.current().nextLong(content.capacity());
      long random2 = ThreadLocalRandom.current().nextLong(content.capacity());
      range = ByteRange.fromOffsetRange(Math.min(random1, random2), Math.max(random1, random2));
      getBlobAndVerify(blobId, range, headers, content);
      getHeadAndVerify(blobId, range, headers);
    }
    getNotModifiedBlobAndVerify(blobId);
    getUserMetadataAndVerify(blobId, headers, usermetadata);
    getBlobInfoAndVerify(blobId, headers, usermetadata);
    deleteBlobAndVerify(blobId);

    // check GET, HEAD and DELETE after delete.
    verifyOperationsAfterDelete(blobId);
  }
  @Test
  public void candidatesDuplicatesTest() {
    for (int parameters : new int[] {1, 2, 5}) {
      for (int choices : new int[] {1, 2, 5}) {
        for (int candidatesCount : new int[] {1, 10, 100, 1000}) {
          try {
            List<List<String>> input = GeneratorTestUtils.prepareInput(parameters, choices);
            AdaptiveRandomAlgorithm<String> algorithm =
                new AdaptiveRandomAlgorithm<String>(0, candidatesCount, Integer.MAX_VALUE, true);
            algorithm.initialize(input, EMPTY_CONSTRAINTS);

            List<List<String>> candidates = algorithm.getCandidates();
            assertEquals(candidates.size(), Math.min(candidatesCount, productSize(input)));
          } catch (GeneratorException e) {
            fail("Unexpected GeneratorException: " + e.getMessage());
          }
        }
      }
    }
  }
Esempio n. 22
0
  @Test
  public void PennTreeAnnotation() throws Exception {

    repository.addAnnotator(new PennTreeAnnotator());
    Thread th = repository.annotateDocuments();
    th.run();
    th.join();

    assertNotNull(th);

    assertNotNull(repository.getAnnotations("s1d0100.a1", "penntree"));

    String[] lines = repository.getAnnotations("s3d0100.a1", "penntree").split("\r\n");
    String[] expectedLines = sentence3pennstring.split("\r\n");

    assertEquals(lines.length, expectedLines.length);

    for (int i = 0; i < Math.min(lines.length, expectedLines.length); i++) {
      assertEquals(expectedLines[i].trim(), lines[i].trim());
    }
  }
 @Override
 public void describeTo(Description desc) {
   if (expected == null || actual == null) {
     desc.appendValue(expected);
   } else {
     int lines = Math.min(expectedLines.size(), actualLines.size());
     for (int idx = 0; idx < lines; idx++) {
       String expectedLine = expectedLines.get(idx);
       String actualLine = actualLines.get(idx);
       if (!expectedLine.equals(actualLine)) {
         desc.appendValue(expectedLine);
         desc.appendText(", but actual is ");
         desc.appendValue(actualLine);
         desc.appendText(", line " + (idx + 1) + "\n");
         desc.appendValue(expected);
         return;
       }
     }
     desc.appendText("expected text is " + expectedLines.size() + " lines, ");
     desc.appendText("but actual text is " + actualLines.size() + " lines\n");
     desc.appendValue(expected);
   }
 }
Esempio n. 24
0
  @Test
  public void testGrafoBipartito() {
    for (int i = 0; i < 100000000; i++) {
      Math.random();
    }

    for (int i = 1; i < 1000; i++) {
      GrafoPredicados grafo = generateBiPartitoCompleto(i, i, 2);

      double tiempoFinal = 0;
      Ejercicio3 ej;
      int conflictos1 = Integer.MAX_VALUE;
      for (int j = 0; j < 3; j++) {
        ej = new Ejercicio3(grafo);
        double tiempo = System.nanoTime();
        conflictos1 = Math.min(conflictos1, ej.checkColoreoFinal());
        tiempoFinal += (System.nanoTime() - tiempo) / 1000;
      }
      System.out.print(tiempoFinal + ";" + conflictos1 + ";");

      conflictos1 = 0;
      for (int j = 0; j < 3; j++) {
        Ejercicio2 ej2 = new Ejercicio2(grafo);
        double tiempo = System.nanoTime();
        if (ej2.solverWithBacktrack()) {
          conflictos1 = 0;
        } else {
          conflictos1 = 1;
        }
        tiempoFinal += (System.nanoTime() - tiempo) / 1000;
      }
      System.out.print(tiempoFinal + ";" + conflictos1 + ";");

      System.out.println();
    }
  }
Esempio n. 25
0
  @org.junit.Test
  public void reduceTest() throws Exception {
    List<String> out_list = new ArrayList<String>();
    List<String> in_list = new ArrayList<String>();

    out_list.add(
        "13311361915;59;2015-10-30 13:44:21;2015-10-30 13:44:26;11985;150621;159;0;10.56.0.145");
    out_list.add(
        "13311361915;59;2015-10-30 13:17:27;2015-10-30 14:11:41;872979;2599118;3391;0;10.56.0.145");
    out_list.add("13311361915;59;2015-10-30 13:16:27;2015-10-30 13:18:41;2;3;4;0;10.56.0.145");
    out_list.add(
        "13311361915;59;2015-10-30 13:38:42;2015-10-30 13:39:16;2476;2016;5;0;10.56.0.145");
    out_list.add(
        "13311361915;59;2015-10-30 13:38:22;2015-10-30 13:44:19;10825;24953;35;0;10.56.0.145");

    in_list.add(
        "13311361915;59;2015-10-30 13:44:21;2015-10-30 13:44:26;11985;150621;159;0;10.56.0.145");
    in_list.add(
        "13311361915;59;2015-10-30 13:17:27;2015-10-30 14:11:41;872979;2599118;3391;0;10.56.0.145");
    in_list.add("13311361915;59;2015-10-30 13:16:27;2015-10-30 13:18:41;2;3;4;0;10.56.0.145");
    in_list.add("13311361915;59;2015-10-30 13:38:42;2015-10-30 13:39:16;2476;2016;5;0;10.56.0.145");
    in_list.add(
        "13311361915;59;2015-10-30 13:38:22;2015-10-30 13:44:19;10825;24953;35;0;10.56.0.145");

    // 对存储value值的两个list进行排序(按起始时间)
    Collections.sort(
        out_list,
        new Comparator<String>() {

          public int compare(String o1, String o2) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date date1 = null;
            Date date2 = null;
            try {
              date1 = sdf.parse(o1.substring(15, 34));
              date2 = sdf.parse(o2.substring(15, 34));
            } catch (ParseException e) {
              e.printStackTrace();
            }
            return date1.compareTo(date2);
          }
        });

    Collections.sort(
        in_list,
        new Comparator<String>() {

          public int compare(String o1, String o2) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date date1 = null;
            Date date2 = null;
            try {
              date1 = sdf.parse(o1.substring(15, 34));
              date2 = sdf.parse(o2.substring(15, 34));
            } catch (ParseException e) {
              e.printStackTrace();
            }
            return date1.compareTo(date2);
          }
        });

    // 合并后的记录
    Set<String> merged_set = new HashSet<String>();
    // 合并过的记录
    Set<String> repeat_set = new HashSet<String>();

    // 日期格式化相关
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    for (String whole_out : out_list) {

      if (!repeat_set.contains(whole_out)) {

        String[] split_out = whole_out.split(";");

        long start_out = 0L;
        long end_out = 0L;
        long flux_out = 0L;
        try {
          start_out = sdf.parse(split_out[2]).getTime();
          end_out = sdf.parse(split_out[3]).getTime();
          flux_out = Long.parseLong(split_out[6]);
        } catch (ParseException e) {
          e.printStackTrace();
        }

        // 合并后的流量
        long flux_total = flux_out;
        // 合并后的起始时间
        long start_merged = start_out;
        // 合并后的结束时间
        long end_merged = end_out;

        for (String whole_in : in_list) {

          String[] split_in = whole_in.split(";");

          long start_in = 0L;
          long end_in = 0L;
          long flux_in = 0L;
          try {
            start_in = sdf.parse(split_in[2]).getTime();
            end_in = sdf.parse(split_in[3]).getTime();
            flux_in = Long.parseLong(split_in[6]);
          } catch (ParseException e) {
            e.printStackTrace();
          }

          // 不是自己本身的那条记录
          if (!whole_in.equals(whole_out)) {
            // 两条记录相互比较
            if (start_merged >= start_in && start_merged <= end_in
                || start_in >= start_merged && start_in <= end_merged) {
              flux_total = flux_total + flux_in;
              start_merged = Math.min(start_in, start_merged);
              end_merged = Math.max(end_in, end_merged);
              // 把合并过的记录保存到repeat_set
              repeat_set.add(whole_in);
            }
          }
        }
        merged_set.add(
            split_out[0]
                + "\t"
                + sdf.format(new Date(start_merged))
                + "\t"
                + sdf.format(new Date(end_merged))
                + "\t"
                + flux_total
                + "\t"
                + split_out[8]);
      } else {
        continue;
      }
    }

    for (String record : merged_set) {
      System.out.println(record);
    }
  }
Esempio n. 26
0
  @Test
  public void movesWork3() {
    List<Move> list = round.findMoves();

    assertEquals(round.switchPieces(list.get(Math.min(0, 2))), true);
  }
Esempio n. 27
0
 public void writeRaw(ByteBuffer buf, int numBytes) throws IOException {
   int len = Math.min(numBytes, buf.remaining());
   byte arr[] = new byte[len];
   buf.get(arr, 0, len);
   out.write(arr);
 }
  @Test
  public void testSslEcho() throws Throwable {
    ServerBootstrap sb =
        new ServerBootstrap(newServerSocketChannelFactory(Executors.newCachedThreadPool()));
    ClientBootstrap cb =
        new ClientBootstrap(newClientSocketChannelFactory(Executors.newCachedThreadPool()));

    EchoHandler sh = new EchoHandler(true);
    EchoHandler ch = new EchoHandler(false);

    SSLEngine sse = SecureChatSslContextFactory.getServerContext().createSSLEngine();
    SSLEngine cse = SecureChatSslContextFactory.getClientContext().createSSLEngine();
    sse.setUseClientMode(false);
    cse.setUseClientMode(true);

    // Workaround for blocking I/O transport write-write dead lock.
    sb.setOption("receiveBufferSize", 1048576);
    sb.setOption("receiveBufferSize", 1048576);

    sb.getPipeline().addFirst("ssl", new SslHandler(sse));
    sb.getPipeline().addLast("handler", sh);
    cb.getPipeline().addFirst("ssl", new SslHandler(cse));
    cb.getPipeline().addLast("handler", ch);
    ExecutorService eventExecutor = null;
    if (isExecutorRequired()) {
      eventExecutor = new OrderedMemoryAwareThreadPoolExecutor(16, 0, 0);
      sb.getPipeline().addFirst("executor", new ExecutionHandler(eventExecutor));
      cb.getPipeline().addFirst("executor", new ExecutionHandler(eventExecutor));
    }

    Channel sc = sb.bind(new InetSocketAddress(0));
    int port = ((InetSocketAddress) sc.getLocalAddress()).getPort();

    ChannelFuture ccf = cb.connect(new InetSocketAddress(TestUtil.getLocalHost(), port));
    ccf.awaitUninterruptibly();
    if (!ccf.isSuccess()) {
      logger.error("Connection attempt failed", ccf.getCause());
      sc.close().awaitUninterruptibly();
    }
    assertTrue(ccf.isSuccess());

    Channel cc = ccf.getChannel();
    ChannelFuture hf = cc.getPipeline().get(SslHandler.class).handshake();
    hf.awaitUninterruptibly();
    if (!hf.isSuccess()) {
      logger.error("Handshake failed", hf.getCause());
      sh.channel.close().awaitUninterruptibly();
      ch.channel.close().awaitUninterruptibly();
      sc.close().awaitUninterruptibly();
    }

    assertTrue(hf.isSuccess());

    for (int i = 0; i < data.length; ) {
      int length = Math.min(random.nextInt(1024 * 64), data.length - i);
      cc.write(ChannelBuffers.wrappedBuffer(data, i, length));
      i += length;
    }

    while (ch.counter < data.length) {
      if (sh.exception.get() != null) {
        break;
      }
      if (ch.exception.get() != null) {
        break;
      }

      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {
        // Ignore.
      }
    }

    while (sh.counter < data.length) {
      if (sh.exception.get() != null) {
        break;
      }
      if (ch.exception.get() != null) {
        break;
      }

      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {
        // Ignore.
      }
    }

    sh.channel.close().awaitUninterruptibly();
    ch.channel.close().awaitUninterruptibly();
    sc.close().awaitUninterruptibly();
    cb.shutdown();
    sb.shutdown();
    cb.releaseExternalResources();
    sb.releaseExternalResources();

    if (eventExecutor != null) {
      eventExecutor.shutdown();
    }
    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
      throw sh.exception.get();
    }
    if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
      throw ch.exception.get();
    }
    if (sh.exception.get() != null) {
      throw sh.exception.get();
    }
    if (ch.exception.get() != null) {
      throw ch.exception.get();
    }
  }