private Grid generateTorusGrid(
        GL gl, int uSteps, int vSteps, float majorRadius, float minorRadius) {
      Grid grid = new Grid(uSteps + 1, vSteps + 1);
      for (int j = 0; j <= vSteps; j++) {
        double angleV = Math.PI * 2 * j / vSteps;
        float cosV = (float) Math.cos(angleV);
        float sinV = (float) Math.sin(angleV);
        for (int i = 0; i <= uSteps; i++) {
          double angleU = Math.PI * 2 * i / uSteps;
          float cosU = (float) Math.cos(angleU);
          float sinU = (float) Math.sin(angleU);
          float d = majorRadius + minorRadius * cosU;
          float x = d * cosV;
          float y = d * (-sinV);
          float z = minorRadius * sinU;

          float nx = cosV * cosU;
          float ny = -sinV * cosU;
          float nz = sinU;

          float length = (float) Math.sqrt(nx * nx + ny * ny + nz * nz);
          nx /= length;
          ny /= length;
          nz /= length;

          grid.set(i, j, x, y, z, nx, ny, nz);
        }
      }
      grid.createBufferObjects(gl);
      return grid;
    }
 public static void main(String[] args) {
   DataHandler dataHandler = new DataHandler();
   int[][] data;
   data = dataHandler.readFile();
   Grid test = new Grid(data[0][0]);
   test.populate(data);
 }
Exemple #3
0
  /** @throws Exception If failed. */
  @SuppressWarnings({"ObjectEquality"})
  public void testDifferentTasks() throws Exception {
    Grid grid1 = null;
    Grid grid2 = null;

    try {
      grid1 = startGrid(1, new GridSpringResourceContextImpl(new GenericApplicationContext()));
      grid2 = startGrid(2, new GridSpringResourceContextImpl(new GenericApplicationContext()));

      // Execute different tasks.
      grid1.compute().execute(SharedResourceTask1.class, null).get();
      grid1.compute().execute(SharedResourceTask2.class, null).get();

      // In ISOLATED_CLASSLOADER mode tasks should have the class
      // loaders because they have the same CL locally and thus the same
      // resources.
      // So 1 resource locally and 1 remotely
      assert task1Rsrc1 == task2Rsrc1;
      assert task1Rsrc2 == task2Rsrc2;
      assert task1Rsrc3 == task2Rsrc3;
      assert task1Rsrc4 == task2Rsrc4;

      checkUsageCount(createClss, UserResource1.class, 4);
      checkUsageCount(createClss, UserResource2.class, 4);

      checkUsageCount(deployClss, UserResource1.class, 4);
      checkUsageCount(deployClss, UserResource2.class, 4);
    } finally {
      GridTestUtils.close(grid1, log());
      GridTestUtils.close(grid2, log());
    }

    checkUsageCount(undeployClss, UserResource1.class, 4);
    checkUsageCount(undeployClss, UserResource2.class, 4);
  }
Exemple #4
0
  public void fire() {
    if (!canFire()) return;
    Enemy target = getTargetEnemy();

    if (target == null) return;

    if (this.towerType == TowerType.ArrowTower) {
      Effect effect =
          new Effect(
              1, TowerType.ArrowTower.getAttack(level), Effect.Target.SINGLE, Effect.Type.DAMAGE);
      effect.setTargetEnemy(target);
      grid.getLevel().getCurrentWave().addEffect(effect);
      grid.getLevel()
          .getCurrentWave()
          .addAmmoSprite(
              new AmmoSprite(
                  this.grid, target.getLastGrid(), Configuration.TOWER_ARROWTOWER_AMMOSPRITE_TYPE));
    } else if (this.towerType == TowerType.CannonTower) {
      Effect effect =
          new Effect(
              1, TowerType.CannonTower.getAttack(level), Effect.Target.SPLASH, Effect.Type.DAMAGE);
      effect.setTargetGrid(target.getGrid());
      grid.getLevel().getCurrentWave().addEffect(effect);
      grid.getLevel()
          .getCurrentWave()
          .addAmmoSprite(
              new AmmoSprite(
                  this.grid,
                  target.getLastGrid(),
                  Configuration.TOWER_CANNONTOWER_AMMOSPRITE_TYPE));
    } else throw new AssertionError();

    // setib turns to fire kuhugi
    // efekt vaja tekitada
  }
Exemple #5
0
  public void paintComponent(Graphics g) throws RuntimeException {
    int squarewidth = getSquareWidth();
    int squareheight = getSquareHeight();

    int hoffset = getHorizontalOffset();
    int voffset = getVerticalOffset();

    for (int x = 0; x < grid.maxX(); x++) {
      for (int y = 0; y < grid.maxY(); y++) {
        Cell tmp = grid.grabObjectAt(x, y);

        if (tmp == null) {
          g.setColor(Color.gray.darker());
        } else {
          g.setColor(tmp.getColor());
        }

        g.fillRect(
            hoffset + x * squarewidth,
            voffset + ((grid.maxY() - y) * squareheight),
            squarewidth - 1,
            squareheight - 1);
      }
    }
  }
Exemple #6
0
  /**
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {

    List<Grid> list = new GridDB().getGridList();

    List<SubPolygonTile> outlist = new ArrayList<SubPolygonTile>();
    int startLevel = 5;
    int endLevel = 16;
    for (int level = startLevel; level <= endLevel; level++) {

      for (Grid g : list) {
        String region = g.region();
        List<SubPolygonTile> tmps = new SegRegion(region, level).calc();

        if (tmps != null) {
          SubPolygonTile master = null;
          for (SubPolygonTile s : tmps) {
            s.id = g.id;
            s.area = BaseMath.ploygon_area(s.points);

            if (master == null) master = s;
            else if (master.area < s.area) master = s;
          }
          master.isMaster = true;
          outlist.addAll(tmps);
        }
      }
    }

    new GridDB().putGridTileDB(outlist);
  }
  /**
   * Returns a 2-valued array of Lines: 0: col, 1:row ; non-null lines if the parameter cells are
   * all contained on the same col/row. So don't be flippant in assessing the array as there are
   * likely null values.
   *
   * @param cells
   * @param g
   * @return
   */
  public static Line[] getCommonLines(ArrayList<Cell> cells, Grid g) {
    Line[] out = new Line[2];
    if (cells.isEmpty()) {
      return new Line[2];
    }

    int x = cells.get(0).x;
    int outlength = 0;
    boolean yes1 = true;
    for (Cell c : cells) {
      if (c.x != x) {
        yes1 = false;
        break;
      }
    }
    if (yes1) {
      out[0] = g.getColumn(x);
      outlength++;
    }
    int y = cells.get(0).y;
    boolean yes2 = true;
    for (Cell c : cells) {
      if (c.y != y) {
        yes2 = false;
        break;
      }
    }
    if (yes2) {
      out[1] = g.getRow(y);
    }
    return out;
  }
  /** @throws Exception If failed. */
  public void testInvalidateFlag() throws Exception {
    GridEx g0 = grid(0);

    GridCache<String, String> cache = g0.cache(PARTITIONED_CACHE_NAME);

    String key = null;

    for (int i = 0; i < 10_000; i++) {
      if (!cache.affinity().isPrimaryOrBackup(g0.localNode(), String.valueOf(i))) {
        key = String.valueOf(i);

        break;
      }
    }

    assertNotNull(key);

    cache.put(key, key); // Create entry in near cache, it is invalidated if INVALIDATE flag is set.

    assertNotNull(cache.peek(key));

    GridClientData d = client.data(PARTITIONED_CACHE_NAME);

    d.flagsOn(GridClientCacheFlag.INVALIDATE).put(key, "zzz");

    for (Grid g : G.allGrids()) {
      cache = g.cache(PARTITIONED_CACHE_NAME);

      if (cache.affinity().isPrimaryOrBackup(g.localNode(), key))
        assertEquals("zzz", cache.peek(key));
      else assertNull(cache.peek(key));
    }
  }
  /** @throws Exception If failed. */
  @SuppressWarnings("unchecked")
  public void testCancel() throws Exception {
    Grid grid = G.grid(getTestGridName());

    grid.compute()
        .localDeployTask(GridCancelTestTask.class, U.detectClassLoader(GridCancelTestTask.class));

    GridComputeTaskFuture<?> fut = grid.compute().execute(GridCancelTestTask.class.getName(), null);

    // Wait until jobs begin execution.
    boolean await = startSignal.await(WAIT_TIME, TimeUnit.MILLISECONDS);

    assert await : "Jobs did not start.";

    info("Test task result: " + fut);

    assert fut != null;

    // Only first job should successfully complete.
    Object res = fut.get();
    assert (Integer) res == 1;

    // Wait for all jobs to finish.
    await = stopSignal.await(WAIT_TIME, TimeUnit.MILLISECONDS);
    assert await : "Jobs did not stop.";

    // One is definitely processed. But there might be some more processed or cancelled or processed
    // and cancelled.
    // Thus total number should be at least SPLIT_COUNT and at most (SPLIT_COUNT - 1) *2 +1
    assert (cancelCnt + processedCnt) >= SPLIT_COUNT
            && (cancelCnt + processedCnt) <= (SPLIT_COUNT - 1) * 2 + 1
        : "Invalid cancel count value: " + cancelCnt;
  }
  /** @throws Exception If failed. */
  public void testDisabledRest() throws Exception {
    restEnabled = false;

    final Grid g = startGrid("disabled-rest");

    try {
      Thread.sleep(2 * TOP_REFRESH_FREQ);

      // As long as we have round robin load balancer this will cause every node to be queried.
      for (int i = 0; i < NODES_CNT + 1; i++)
        assertEquals(NODES_CNT + 1, client.compute().refreshTopology(false, false).size());

      final GridClientData data = client.data(PARTITIONED_CACHE_NAME);

      // Check rest-disabled node is unavailable.
      try {
        String affKey;

        do {
          affKey = UUID.randomUUID().toString();
        } while (!data.affinity(affKey).equals(g.localNode().id()));

        data.put(affKey, "asdf");

        assertEquals("asdf", cache(0, PARTITIONED_CACHE_NAME).get(affKey));
      } catch (GridServerUnreachableException e) {
        // Thrown for direct client-node connections.
        assertTrue(
            "Unexpected exception message: " + e.getMessage(),
            e.getMessage()
                .startsWith("No available endpoints to connect (is rest enabled for this node?)"));
      } catch (GridClientException e) {
        // Thrown for routed client-router-node connections.
        String msg = e.getMessage();

        assertTrue(
            "Unexpected exception message: " + msg,
            protocol() == GridClientProtocol.TCP
                ? msg.contains("No available endpoints to connect (is rest enabled for this node?)")
                : // TCP router.
                msg.startsWith(
                    "No available nodes on the router for destination node ID")); // HTTP router.
      }

      // Check rest-enabled nodes are available.
      String affKey;

      do {
        affKey = UUID.randomUUID().toString();
      } while (data.affinity(affKey).equals(g.localNode().id()));

      data.put(affKey, "fdsa");

      assertEquals("fdsa", cache(0, PARTITIONED_CACHE_NAME).get(affKey));
    } finally {
      restEnabled = true;

      G.stop(g.name(), true);
    }
  }
  private Grid<UserData> createGrid() {
    IdentityValueProvider<UserData> identityValueProvider =
        new IdentityValueProvider<UserData>("sm");
    CheckBoxSelectionModel<UserData> selectionModel =
        new CheckBoxSelectionModel<UserData>(identityValueProvider);
    selectionModel.setSelectionMode(Style.SelectionMode.MULTI);

    List<ColumnConfig<UserData, ?>> columnConfigList = new ArrayList<ColumnConfig<UserData, ?>>();

    columnConfigList.add(selectionModel.getColumn());
    columnConfigList.add(new ColumnConfig<UserData, Long>(userProperties.id(), 20, "ID"));
    columnConfigList.add(
        new ColumnConfig<UserData, String>(userProperties.username(), 100, "Username"));
    columnConfigList.add(
        new ColumnConfig<UserData, String>(userProperties.firstName(), 100, "First Name"));
    columnConfigList.add(
        new ColumnConfig<UserData, String>(userProperties.lastName(), 100, "Last Name"));
    columnConfigList.add(new ColumnConfig<UserData, String>(userProperties.email(), 100, "Email"));
    //    columnConfigList.add(new ColumnConfig<UserData, UserRoleTypes>(userProperties.role(), 100,
    // "Role"));

    ColumnModel<UserData> columnModel = new ColumnModel<UserData>(columnConfigList);
    ListStore<UserData> store = new ListStore<UserData>(userProperties.key());

    Grid<UserData> userDataGrid = new Grid<UserData>(store, columnModel);

    userDataGrid.setLoadMask(true);

    userDataGrid.setHideHeaders(false);
    userDataGrid.getView().setAutoFill(true);
    userDataGrid.setSelectionModel(selectionModel);

    return userDataGrid;
  }
  /** @throws Exception If failed. */
  public void testProjectionRun() throws Exception {
    GridClientCompute dflt = client.compute();

    Collection<? extends GridClientNode> nodes = dflt.nodes();

    assertEquals(NODES_CNT, nodes.size());

    for (int i = 0; i < NODES_CNT; i++) {
      Grid g = grid(i);

      assert g != null;

      GridClientNode clientNode = dflt.node(g.localNode().id());

      assertNotNull("Client node for " + g.localNode().id() + " was not found", clientNode);

      GridClientCompute prj = dflt.projection(clientNode);

      String res = prj.execute(TestTask.class.getName(), null);

      assertNotNull(res);

      assertEquals(g.localNode().id().toString(), res);
    }
  }
  /**
   * Ensure that {@link GridComputeJobMasterLeaveAware} callback is invoked on job which is
   * initiated by master and is currently running on it.
   *
   * @throws Exception If failed.
   */
  public void testLocalJobOnMaster() throws Exception {
    invokeLatch = new CountDownLatch(1);
    jobLatch = new CountDownLatch(1);

    Grid g = startGrid(0);

    g.compute().execute(new TestTask(1), null);

    jobLatch.await();

    // Count down the latch in a separate thread.
    new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  U.sleep(500);
                } catch (GridInterruptedException ignore) {
                  // No-op.
                }

                latch.countDown();
              }
            })
        .start();

    stopGrid(0, true);

    latch.countDown();

    assert invokeLatch.await(5000, MILLISECONDS);
  }
Exemple #14
0
  /**
   * Execute {@code HelloWorld} example on the grid.
   *
   * @param args Command line arguments, none required but if provided first one should point to the
   *     Spring XML configuration file. See {@code "examples/config/"} for configuration file
   *     examples.
   * @throws GridException If example execution failed.
   */
  public static void main(String[] args) throws GridException {
    if (args.length == 0) {
      G.start();
    } else {
      G.start(args[0]);
    }

    try {
      Grid grid = G.grid();

      // Execute Hello World task.
      GridTaskFuture<Integer> fut = grid.execute(GridHelloWorldTask.class, "Hello World");

      // Wait for task completion.
      int phraseLen = fut.get();

      X.println(">>>");
      X.println(">>> Finished executing Grid \"Hello World\" example with custom task.");
      X.println(">>> Total number of characters in the phrase is '" + phraseLen + "'.");
      X.println(">>> You should see print out of 'Hello' on one node and 'World' on another node.");
      X.println(">>> Check all nodes for output (this node is also part of the grid).");
      X.println(">>>");
    } finally {
      G.stop(true);
    }
  }
Exemple #15
0
  private static void solve(Grid grid, List<Grid> solutions) {
    // Return if there is already more than two solution
    if (solutions.size() >= 2) {
      return;
    }

    // Find first empty cell
    int loc = grid.findEmptyCell();

    // If no empty cells are found,a solution is found
    if (loc < 0) {
      solutions.add(grid.clone());
      return;
    }

    // Try each of the 9 digits in this empty cell
    for (int n = 1; n < 10; n++) {
      if (grid.set(loc, n)) {
        // With this cell set,work on the next cell
        solve(grid, solutions);

        // Clear the cell so that it can be filled with another digit
        grid.clear(loc);
      }
    }
  }
Exemple #16
0
 public int getol(Coord tc) {
   Grid g = getgridt(tc);
   int ol = g.getol(tc.sub(g.ul));
   for (Overlay lol : ols) {
     if (tc.isect(lol.c1, lol.c2.add(lol.c1.inv()).add(new Coord(1, 1)))) ol |= lol.mask;
   }
   return (ol);
 }
  /** Method declaration Adjust this method for large strings...ie multi megabtypes. */
  void execute() {

    String sCmd = null;

    if (4096 <= ifHuge.length()) {
      sCmd = ifHuge;
    } else {
      sCmd = txtCommand.getText();
    }

    if (sCmd.startsWith("-->>>TEST<<<--")) {
      testPerformance();

      return;
    }

    String g[] = new String[1];

    lTime = System.currentTimeMillis();

    try {
      sStatement.execute(sCmd);

      lTime = System.currentTimeMillis() - lTime;

      int r = sStatement.getUpdateCount();

      if (r == -1) {
        formatResultSet(sStatement.getResultSet());
      } else {
        g[0] = "update count";

        gResult.setHead(g);

        g[0] = String.valueOf(r);

        gResult.addRow(g);
      }

      addToRecent(txtCommand.getText());
    } catch (SQLException e) {
      lTime = System.currentTimeMillis() - lTime;
      g[0] = "SQL Error";

      gResult.setHead(g);

      String s = e.getMessage();

      s += " / Error Code: " + e.getErrorCode();
      s += " / State: " + e.getSQLState();
      g[0] = s;

      gResult.addRow(g);
    }

    updateResult();
    System.gc();
  }
 public void invalidateHardwareBuffers() {
   if (sSystemRegistry.contextParameters.supportsVBOs) {
     final int count = mGridList.getCount();
     for (int x = 0; x < count; x++) {
       Grid grid = mGridList.get(x);
       grid.invalidateHardwareBuffers();
     }
   }
 }
Exemple #19
0
 public boolean canMove() {
   Grid<Actor> gr = getGrid();
   if (gr == null) return false;
   Location loc = getLocation();
   Location next = loc.getAdjacentLocation(getDirection()).getAdjacentLocation(getDirection());
   if (!gr.isValid(next)) return false;
   Actor neighbor = gr.get(next);
   return (neighbor == null) || (neighbor instanceof Flower);
 }
Exemple #20
0
 public void printGrid(Grid grid) {
   for (int i = 0; i < grid.getHeight(); i++) {
     for (int j = 0; j < grid.getHeight(); j++) {
       char toPrint = (grid.isAlive(i, j)) ? symbole[0] : symbole[1];
       System.out.print(toPrint + " ");
     }
     System.out.print("\n");
   }
 }
Exemple #21
0
  // Tests the size of the grid(rows)
  @Test
  public void buildGridTest() {
    Grid T6 = new Grid();

    T6.buildGrid();
    int rows = T6.grid.length;
    int expectedSize = 10;
    assertEquals(expectedSize, rows);
  }
Exemple #22
0
  public Enemy getTargetEnemy() {

    for (Grid targetGrid : gridsList) {
      if (!targetGrid.getEnemyList().isEmpty()) {
        return targetGrid.getEnemyList().get(0);
      }
    }
    return null;
  }
  /**
   * Listen to events coming from all grid nodes.
   *
   * @throws GridException If failed.
   */
  private static void remoteListen() throws GridException {
    Grid g = GridGain.grid();

    GridCache<Integer, String> cache = g.cache(CACHE_NAME);

    // Register remote event listeners on all nodes running cache.
    GridFuture<?> fut =
        g.forCache(CACHE_NAME)
            .events()
            .remoteListen(
                // This optional local callback is called for each event notification
                // that passed remote predicate filter.
                new GridBiPredicate<UUID, GridCacheEvent>() {
                  @Override
                  public boolean apply(UUID nodeId, GridCacheEvent evt) {
                    System.out.println();
                    System.out.println(
                        "Received event [evt="
                            + evt.name()
                            + ", key="
                            + evt.key()
                            + ", oldVal="
                            + evt.oldValue()
                            + ", newVal="
                            + evt.newValue());

                    return true; // Return true to continue listening.
                  }
                },
                // Remote filter which only accepts events for keys that are
                // greater or equal than 10 and if local node is primary for this key.
                new GridPredicate<GridCacheEvent>() {
                  /** Auto-inject grid instance. */
                  @GridInstanceResource private Grid g;

                  @Override
                  public boolean apply(GridCacheEvent evt) {
                    Integer key = evt.key();

                    return key >= 10
                        && g.cache(CACHE_NAME).affinity().isPrimary(g.localNode(), key);
                  }
                },
                // Types of events for which listeners are registered.
                EVT_CACHE_OBJECT_PUT,
                EVT_CACHE_OBJECT_READ,
                EVT_CACHE_OBJECT_REMOVED);

    // Wait until event listeners are subscribed on all nodes.
    fut.get();

    int keyCnt = 20;

    // Generate cache events.
    for (int i = 0; i < keyCnt; i++) cache.putx(i, Integer.toString(i));
  }
Exemple #24
0
  @Test
  public void randomWithRangeTest() {
    Grid T9 = new Grid();
    int rand;

    for (int i = 0; i < 1000; i++) {
      rand = T9.randomWithRange(0, 10);
      assertTrue(11 > rand);
    }
  }
Exemple #25
0
 void advance() {
   StateTransition transition = rules.lookup(state, grid.cellAt(x, y));
   if (transition == null) {
     throw new IllegalStateException("Undefined state transition");
   }
   grid.setCellAt(x, y, transition.newCellState());
   state = transition.newHeadState();
   turn(transition.newDirection());
   moveForward();
 }
Exemple #26
0
  /** Paints the grid, the falling shape and the next shape */
  public void paintComponent(Graphics g) {

    super.paintComponent(g);

    grid.drawGrid(grid.getGrid(), g);
    game.getCurrentShape().drawShape(g);
    game.drawAllShapes(g, game.getAllShapes());

    repaint();
  }
  public SaveCloseToolbarDialogues(DataProvider dataProvider, Grid grid) {
    super(grid.getContext());
    this.input = new EditText(grid.getContext());
    this.dataProvider = dataProvider;
    this.grid = grid;
    this.savedToast = Toast.makeText(grid.getContext(), R.string.savedAlert, Toast.LENGTH_SHORT);
    this.savedToast.setGravity(Gravity.CENTER, 0, 0);

    this.alertDialog1 = this.createAlertDialogue();
  }
Exemple #28
0
 // Tests the number of mines that are hidden adjacent to
 // the current position
 @Test
 public void checkAroundMinesTest() {
   Grid T8 = new Grid();
   int mine = 50;
   T8.grid[2][2] = mine;
   T8.grid[3][3] = mine;
   T8.checkAroundMines();
   int expected = 2;
   assertEquals(expected, T8.grid[2][3]);
 }
Exemple #29
0
  @Test
  public void testIsFullOnX() throws Exception {
    Grid grid = new Grid();
    assertEquals(false, grid.isFullOnX(0));
    grid.setValue(1, 0, 0);
    grid.setValue(2, 0, 1);
    grid.setValue(3, 0, 2);

    assertEquals(true, grid.isFullOnX(0));
  }
Exemple #30
0
 public void ctick() {
   long now = System.currentTimeMillis();
   int dt = (int) (now - lastctick);
   synchronized (grids) {
     for (Grid g : grids.values()) {
       g.tick(dt);
     }
   }
   lastctick = now;
 }