Exemple #1
0
  public void compare(Map<String, List<String>> requestProperties) {
    Compare _compare = new Compare();
    UnitofInteraction talking = new UnitofInteraction(requestProperties);
    talking.startThread();

    Map<String, String> result = null;

    try {
      result = _compare.Run(GeneralStuff._getArguments(requestProperties));
    } catch (IOException ex) {
      talking.notifyError();
    } catch (SQLException ex) {
      talking.notifyError();
    } catch (ClassNotFoundException ex) {
      talking.notifyError();
    } finally {
      talking.stopThread();
    }

    String text = result.get("text");
    requestProperties.put("text", Arrays.asList(new String[] {text}));
    System.out.println(text);

    try {
      GeneralStuff._sendMessage(GeneralStuff._forgeMessage(requestProperties));
    } catch (IOException ex) {
      Logger.getLogger(Commands.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
 @Override
 public void meet(Compare cmp) throws RuntimeException {
   optypes.push(new OPTypeFinder(cmp).coerce());
   cmp.getLeftArg().visit(this);
   builder.append(getSQLOperator(cmp.getOperator()));
   cmp.getRightArg().visit(this);
   optypes.pop();
 }
Exemple #3
0
  public void update() {
    bg.update();
    int remaining = 0;

    if (state != 4) {
      done.setBitmap(scaledDone);
      if (state == 1) {
        for (int i = 0; i < gameObject1.size(); i++) {
          gameObject1.get(i).update();
          score11.update();
          gameWord1.update();
        }
      }
      if (state == 2) {
        for (int i = 0; i < gameObject2.size(); i++) {
          gameObject2.get(i).update();
          score22.update();
          gameWord2.update();
        }
      }
    }
    if (state == 4) {
      done.setBitmap(scaledNew);
      if (score1 > score2) {
        totalWinner = 1;
      } else if (score1 < score2) {
        totalWinner = 2;
      } else {
        totalWinner = 0;
      }
    }

    done.update();
    moneyPanel.update();
    timer.update();
    mid.update();
    newMoney(scaledTimer, timer.drawUpdate());
    timer.setBitmap(scaledTimer.get(0), scaledTimer.get(1));
    if (timer.getGG() && state == 1) {
      state = 2;

      timer.resetTimer();
    }

    if (timer.getGG() && state == 2) {
      state = 3;
      compare.setCompare(choose, usedDiamond, choose2, usedDiamond2);
      winner = compare.comparator();
      choose = "Nope";
      choose2 = "Nope";
      usedDiamond = false;
      usedDiamond2 = false;
      timer.resetTimer();
    }

    // System.out.println("test");
  }
Exemple #4
0
 private void quickSort(int left, int right) {
   if (right > left) {
     Object o1 = elementAt(right);
     int i = left - 1;
     int j = right;
     while (true) {
       while (compare.lessThan(elementAt(++i), o1)) ;
       while (j > 0) if (compare.lessThanOrEqual(elementAt(--j), o1)) break; // out of while
       if (i >= j) break;
       swap(i, j);
     }
     swap(i, right);
     quickSort(left, i - 1);
     quickSort(i + 1, right);
   }
 }
Exemple #5
0
 /**
  * Performs the assert-equals function.
  *
  * @param ctx query context
  * @return resulting value
  * @throws QueryException query exception
  */
 private Item assertEquals(final QueryContext ctx) throws QueryException {
   final byte[] str = expr.length < 3 ? null : checkStr(expr[2], ctx);
   final Iter iter1 = ctx.iter(expr[0]), iter2 = ctx.iter(expr[1]);
   final Compare comp = new Compare(info);
   Item it1, it2;
   int c = 1;
   while (true) {
     it1 = iter1.next();
     it2 = iter2.next();
     final boolean empty1 = it1 == null, empty2 = it2 == null;
     if (empty1 && empty2) return null;
     if (empty1 || empty2 || !comp.deep(it1.iter(), it2.iter())) break;
     c++;
   }
   if (str != null) throw UNIT_MESSAGE.get(info, str);
   throw new UnitException(info, UNIT_ASSERT_EQUALS, it1, it2, c);
 }
 public void __delete__(PyObject obj) {
   PyType self_type = getType();
   PyObject impl = self_type.lookup("__delete__");
   if (impl != null) {
     impl.__get__(this, self_type).__call__(obj);
     return;
   }
   super.__delete__(obj);
 }
 public void __delattr__(String name) {
   PyType self_type = getType();
   PyObject impl = self_type.lookup("__delattr__");
   if (impl != null) {
     impl.__get__(this, self_type).__call__(PyString.fromInterned(name));
     return;
   }
   super.__delattr__(name);
 }
 public void __delitem__(PyObject key) { // ???
   PyType self_type = getType();
   PyObject impl = self_type.lookup("__delitem__");
   if (impl != null) {
     impl.__get__(this, self_type).__call__(key);
     return;
   }
   super.__delitem__(key);
 }
Exemple #9
0
 public static Node find(Node n, Object key, Comparator comparator) {
   while (n != Null) {
     int difference = Compare.compare(key, n.key, comparator);
     if (difference < 0) {
       n = n.left;
     } else if (difference > 0) {
       n = n.right;
     } else {
       return n;
     }
   }
   return Null;
 }
 public void __delslice__(PyObject start, PyObject stop, PyObject step) {
   if (step != null) {
     __delitem__(new PySlice(start, stop, step));
     return;
   }
   PyType self_type = getType();
   PyObject impl = self_type.lookup("__delslice__");
   if (impl != null) {
     PyObject[] indices = PySlice.indices2(this, start, stop);
     impl.__get__(this, self_type).__call__(indices[0], indices[1]);
     return;
   }
   super.__delslice__(start, stop, step);
 }
Exemple #11
0
  public void run() {
    InstField instField = new InstField();
    instField.run();

    StaticField.run();

    IntMath.run();
    FloatMath.run();
    Compare.run();

    Monitor.run();
    Switch.run();
    Array.run();
    Classes.run();
    Goto.run();
    MethodCall.run();
    Throw.run();

    try {
      UnresTest1.run();
    } catch (VerifyError ve) {
      System.out.println("Caught: " + ve);
    }
    try {
      UnresTest1.run();
    } catch (VerifyError ve) {
      System.out.println("Caught (retry): " + ve);
    }

    try {
      UnresTest2.run();
    } catch (VerifyError ve) {
      System.out.println("Caught: " + ve);
    } catch (Throwable th) {
      // We and the RI throw ClassNotFoundException, but that isn't declared so javac
      // won't let us try to catch it.
      th.printStackTrace();
    }
    InternedString.run();
  }
Exemple #12
0
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    ArrayList<GameObject> gameObject = new ArrayList<GameObject>();
    String player = null;
    GameWord gameWord = gameWord1;
    boolean playerDiamond = false;
    if (state == 1) {
      gameObject = gameObject1;
      playerDiamond = usedDiamond;
      player = choose;
      gameWord = gameWord1;
    }
    if (state == 2) {
      gameObject = gameObject2;
      playerDiamond = usedDiamond2;
      player = choose2;
      gameWord = gameWord2;
    }
    if (state == 3) {
      gameObject = gameObject3;
    }
    if (state == 4) {
      gameObject = gameObject4;
    }

    switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
        playerDiamond = false;
        xTouch = event.getX();
        yTouch = event.getY();

        // System.out.println("x: "+ (int)(xTouch/scaleFactorX)+" "+scaleFactorX);
        // System.out.println("y: "+ (int)(yTouch/scaleFactorY)+" "+scaleFactorY);
        for (int i = 0; i < gameObject.size(); i++) {
          gameObjectName =
              collision(
                  (int) (xTouch / scaleFactorX), (int) (yTouch / scaleFactorY), gameObject.get(i));

          if (gameObjectName != null) {
            imageWord(gameWord, gameObjectName);
            System.out.println(gameObjectName);
            num = i;
            // gameObject.get(i).setX((int)(xTouch/scaleFactorX));
            // gameObject.get(i).setY((int)(yTouch/scaleFactorY));
            break;
          }
        }
        break;
      case MotionEvent.ACTION_MOVE:
        if (state == 1 || state == 2) {
          if (num != -1) {
            if (gameObjectName != "Done") {
              xTouch = event.getX();
              // System.out.println("X: " + xTouch);
              yTouch = event.getY();
              // System.out.println("Y: " + yTouch);

              if (num >= 0) {
                gameObject
                    .get(num)
                    .setX((int) (xTouch / scaleFactorY) - (gameObject.get(num).getWidth() / 2));
                gameObject
                    .get(num)
                    .setY((int) (yTouch / scaleFactorY) - (gameObject.get(num).getHeight() / 2));
              }
            }
          }
        }
        break;

      case MotionEvent.ACTION_UP:
        /*if (collBetObj(gameObject.get(num),mid)){
            System.out.println("collide");
            gameObject.remove(num);
            overlayBitmap.eraseColor(Color.TRANSPARENT);
        }*/
        if (num != -1) {
          if ((collBetObj(gameObject.get(num), mid) && player == "Nope")
              || (collBetObj(gameObject.get(num), mid))
                  && (gameObject.get(num).getString() == "Diamond")) {
            if (gameObject.get(num).getString() != "Diamond") {
              player = gameObject.get(num).getString();
              // System.out.println("Choose: " + player);
              gameObject.remove(num);
            } else if (gameObject.get(num).getString() == "Diamond" && player == "Nope") {
              // System.out.println("Choose: " + player);
              gameObject.get(num).setX(gameObject.get(num).getInitialX());
              gameObject.get(num).setY(gameObject.get(num).getInitialY());
            } else {
              playerDiamond = true;
              // System.out.println("Diamond used: " + playerDiamond);
              gameObject.remove(num);
            }
            if (state == 1) {
              usedDiamond = playerDiamond;
              choose = player;
            } else if (state == 2) {
              usedDiamond2 = playerDiamond;
              choose2 = player;
            }
            // gameObject.get(num).getBit().eraseColor(Color.TRANSPARENT);

          } else {

            if (gameObject.get(num).getString() != "Done") {
              gameObject.get(num).setX(gameObject.get(num).getInitialX());
              gameObject.get(num).setY(gameObject.get(num).getInitialY());
            } else {
              if (state == 1) {
                // usedDiamond = playerDiamond;
                // choose =  player;
                state = 2;
                scaledGameWord =
                    Bitmap.createScaledBitmap(
                        BitmapFactory.decodeResource(getResources(), R.drawable.player2),
                        192,
                        64,
                        true);
                gameWord2.setBitmap(scaledGameWord);
                timer.resetTimer();
              } else if (state == 2) {
                // usedDiamond2 = playerDiamond;
                // choose2 = player;
                state = 3;
                timer.resetTimer();

                compare.setCompare(choose, usedDiamond, choose2, usedDiamond2);
                winner = compare.comparator();
                System.out.println("Winner: " + winner);
                choose = "Nope";
                choose2 = "Nope";
                usedDiamond = false;
                usedDiamond2 = false;
              } else if (state == 3) {
                state = 1;
                scaledGameWord =
                    Bitmap.createScaledBitmap(
                        BitmapFactory.decodeResource(getResources(), R.drawable.player1),
                        192,
                        64,
                        true);
                gameWord1.setBitmap(scaledGameWord);
                // gameWord2.setBitmap(scaledGameWord);
                if (winner == 1) {
                  score1 = score1 + money.vals[round];
                  newMoney(Money1, score11.drawUpdate(score1));
                  score11.setBitmap(Money1.get(0), Money1.get(1));
                } else if (winner == 2) {
                  score2 = score2 + money.vals[round];
                  newMoney(Money2, score22.drawUpdate(score2));
                  score22.setBitmap(Money2.get(0), Money2.get(1));
                }
                if (round < 5) {
                  round++;

                  if (round == 5) {
                    state = 4;
                  } else {

                    newMoney(scaledMoney, money.drawUpdate(money.vals[round]));
                    money.setBitmap(scaledMoney.get(0), scaledMoney.get(1));
                  }
                }

                int remaining = 0;
                for (int i = 0; i < ((money.vals.length) - round); i++) {
                  remaining = remaining + money.vals[4 - i];
                  System.out.println("Money: " + money.vals[4 - i]);
                }
                System.out.println(remaining);
                System.out.println((score1 + remaining) < score2);
                System.out.println((score2 + remaining) < score1);

                if (((score1 + remaining) < score2) || ((score2 + remaining) < score1)) {
                  state = 4;
                  System.out.println("Sad");
                }

                timer.resetTimer();
                winner = 0;

              } else if (state == 4) {
                newGame();
              }
              // System.out.println("State: "+ state);
              // System.out.println("Score1: "+ score1);
              // System.out.println("Score2: "+ score2);
            }
          }
          num = -1;
          gameObjectName = null;
        }
        break;
    }

    return true;
  }
 @Override
 public Collection<? extends ComplexTypeMetadata> visit(Compare condition) {
   condition.getLeft().accept(this);
   condition.getRight().accept(this);
   return closure;
 }
 public boolean matches(Object value1, Object value2) {
   if (value1 == value2) return true;
   if (NumberValue.isNaN(value1) && NumberValue.isNaN(value2)) return true;
   return Compare.apply(Compare.LENIENT_EQ, value1, value2, collator);
 }
Exemple #15
0
  public static MyRevision mergeRevisions(
      MyRevision base,
      MyRevision left,
      MyRevision right,
      ConflictResolver conflictResolver,
      ForeignKeyResolver foreignKeyResolver) {
    // System.out.println("base:");
    // Node.dump(base.root, System.out, 0);
    // System.out.println("left:");
    // Node.dump(left.root, System.out, 0);
    // System.out.println("right:");
    // Node.dump(right.root, System.out, 0);

    if (base.equals(right) || left.equals(right)) {
      return left;
    } else if (base.equals(left)) {
      if (left.equals(right)) {
        return left;
      } else {
        return right;
      }
    }

    // The merge builds a new revision starting with the specified
    // left revision via a process which consists of the following
    // steps:
    //
    //  1. Merge the primary key data trees of each table and delete
    //     obsolete index and view data trees.
    //
    //  2. Update non-primary-key index and view data trees, removing
    //     obsolete rows and adding new or updated ones.
    //
    //  3. Build data trees for any new indexes and views added.
    //
    //  4. Verify foreign key constraints.

    MyRevisionBuilder builder = new MyRevisionBuilder(new Object(), left, new NodeStack());

    Set<Index> indexes = new TreeSet<Index>();
    Set<Index> newIndexes = new TreeSet<Index>();

    Set<View> views = new TreeSet<View>();
    Set<View> newViews = new TreeSet<View>();

    NodeStack baseStack = new NodeStack();
    NodeStack leftStack = new NodeStack();
    NodeStack rightStack = new NodeStack();

    {
      MergeIterator[] iterators = new MergeIterator[Constants.MaxDepth + 1];
      iterators[0] =
          new MergeIterator(
              base.root,
              baseStack,
              left.root,
              leftStack,
              right.root,
              rightStack,
              Compare.TableComparator);

      int depth = 0;
      int bottom = -1;
      Table table = null;
      MergeIterator.MergeTriple triple = new MergeIterator.MergeTriple();

      // merge primary key data trees of each table, deleting obsolete
      // rows from any other index data trees as we go
      while (true) {
        if (iterators[depth].next(triple)) {
          expect(triple.base != Node.Null && triple.left != Node.Null && triple.right != Node.Null);

          Comparator comparator = iterators[depth].comparator;

          boolean descend = false;
          boolean conflict = false;
          if (triple.base == null) {
            if (triple.left == null) {
              if (depth != Constants.IndexDataDepth || ((Index) triple.right.key).isPrimary()) {
                builder.insertOrUpdate(depth, triple.right.key, comparator, triple.right.value);
              }
            } else if (triple.right == null) {
              // do nothing -- left already has insert
            } else if (depth == bottom) {
              if (Compare.equal(triple.left.value, triple.right.value)) {
                // do nothing -- inserts match and left already has it
              } else {
                conflict = true;
              }
            } else {
              descend = true;
            }
          } else if (triple.left != null) {
            if (triple.right != null) {
              if (triple.left == triple.base) {
                if (depth == Constants.IndexDataDepth) {
                  indexes.remove(triple.right.key);
                }
                builder.insertOrUpdate(depth, triple.right.key, comparator, triple.right.value);
              } else if (triple.right == triple.base) {
                // do nothing -- left already has update
              } else if (depth == bottom) {
                if (Compare.equal(triple.left.value, triple.right.value)
                    || Compare.equal(triple.base.value, triple.right.value)) {
                  // do nothing -- updates match or only left changed,
                  // and left already has it
                } else if (Compare.equal(triple.base.value, triple.left.value)) {
                  builder.insertOrUpdate(depth, triple.right.key, comparator, triple.right.value);
                } else {
                  conflict = true;
                }
              } else {
                descend = true;
              }
            } else if (depth != bottom) {
              descend = true;
            } else {
              builder.deleteKey(depth, triple.left.key, comparator);
            }
          } else if (depth != bottom) {
            descend = true;
          } else {
            // do nothing -- left already has delete
          }

          Object key =
              triple.base == null
                  ? (triple.left == null ? triple.right.key : triple.left.key)
                  : triple.base.key;

          if (conflict) {
            Object[] primaryKeyValues = new Object[depth - Constants.IndexDataBodyDepth];

            for (int i = 0; i < primaryKeyValues.length; ++i) {
              primaryKeyValues[i] = builder.keys[i + Constants.IndexDataBodyDepth];
            }

            Object result =
                conflictResolver.resolveConflict(
                    table,
                    (Column<?>) key,
                    primaryKeyValues,
                    triple.base == null ? null : triple.base.value,
                    triple.left.value,
                    triple.right.value);

            if (Compare.equal(result, triple.left.value)) {
              // do nothing -- left already has insert
            } else if (result == null) {
              builder.deleteKey(depth, key, comparator);
            } else {
              builder.insertOrUpdate(depth, key, comparator, result);
            }
          } else if (descend) {
            Comparator nextComparator;
            if (depth == Constants.TableDataDepth) {
              table = (Table) key;

              if (Node.pathFind(
                      left.root,
                      Constants.ViewTable,
                      Compare.TableComparator,
                      Constants.ViewTableIndex,
                      Compare.IndexComparator,
                      table,
                      Constants.ViewTableColumn.comparator)
                  != Node.Null) {
                // skip views -- we'll handle them later
                continue;
              }

              nextComparator = Compare.IndexComparator;

              {
                DiffIterator indexIterator =
                    new DiffIterator(
                        Node.pathFind(
                            left.root,
                            Constants.IndexTable,
                            Compare.TableComparator,
                            Constants.IndexTable.primaryKey,
                            Compare.IndexComparator,
                            table,
                            Constants.TableColumn.comparator),
                        baseStack = new NodeStack(baseStack),
                        Node.pathFind(
                            builder.result.root,
                            Constants.IndexTable,
                            Compare.TableComparator,
                            Constants.IndexTable.primaryKey,
                            Compare.IndexComparator,
                            table,
                            Constants.TableColumn.comparator),
                        leftStack = new NodeStack(leftStack),
                        list(Interval.Unbounded).iterator(),
                        true,
                        Constants.IndexColumn.comparator);

                DiffIterator.DiffPair pair = new DiffIterator.DiffPair();
                while (indexIterator.next(pair)) {
                  if (pair.base != null) {
                    if (pair.fork != null) {
                      Index index = (Index) pair.base.key;
                      if (!index.equals(table.primaryKey)) {
                        indexes.add(index);
                      }
                    } else {
                      builder.setKey(Constants.TableDataDepth, table, Compare.TableComparator);
                      builder.deleteKey(
                          Constants.IndexDataDepth, pair.base.key, Compare.IndexComparator);
                    }
                  } else if (pair.fork != null) {
                    Index index = (Index) pair.fork.key;
                    if (!index.equals(table.primaryKey)) {
                      newIndexes.add(index);
                    }
                  }
                }

                baseStack = baseStack.popStack();
                leftStack = leftStack.popStack();
              }

              {
                DiffIterator indexIterator =
                    new DiffIterator(
                        Node.pathFind(
                            left.root,
                            Constants.ViewTable,
                            Compare.TableComparator,
                            Constants.ViewTable.primaryKey,
                            Compare.IndexComparator,
                            table,
                            Constants.TableColumn.comparator),
                        baseStack = new NodeStack(baseStack),
                        Node.pathFind(
                            builder.result.root,
                            Constants.ViewTable,
                            Compare.TableComparator,
                            Constants.ViewTable.primaryKey,
                            Compare.IndexComparator,
                            table,
                            Constants.TableColumn.comparator),
                        leftStack = new NodeStack(leftStack),
                        list(Interval.Unbounded).iterator(),
                        true,
                        Constants.ViewColumn.comparator);

                DiffIterator.DiffPair pair = new DiffIterator.DiffPair();
                while (indexIterator.next(pair)) {
                  if (pair.base != null) {
                    View view = (View) pair.base.key;
                    if (pair.fork != null) {
                      views.add(view);
                    } else {
                      builder.deleteKey(
                          Constants.TableDataDepth, view.table, Compare.TableComparator);
                    }
                  } else if (pair.fork != null) {
                    newViews.add((View) pair.fork.key);
                  }
                }

                baseStack = baseStack.popStack();
                leftStack = leftStack.popStack();
              }
            } else if (depth == Constants.IndexDataDepth) {
              Index index = (Index) key;

              if (Compare.equal(index, table.primaryKey, comparator)) {
                bottom = index.columns.size() + Constants.IndexDataBodyDepth;
              } else {
                // skip non-primary-key index data trees -- we'll handle
                // those later
                continue;
              }

              nextComparator = table.primaryKey.columns.get(0).comparator;
            } else if (depth + 1 == bottom) {
              nextComparator = Compare.ColumnComparator;
            } else {
              nextComparator =
                  table.primaryKey.columns.get(depth + 1 - Constants.IndexDataBodyDepth).comparator;
            }

            builder.setKey(depth, key, comparator);

            ++depth;

            iterators[depth] =
                new MergeIterator(
                    triple.base == null ? Node.Null : (Node) triple.base.value,
                    baseStack = new NodeStack(baseStack),
                    triple.left == null ? Node.Null : (Node) triple.left.value,
                    leftStack = new NodeStack(leftStack),
                    triple.right == null ? Node.Null : (Node) triple.right.value,
                    rightStack = new NodeStack(rightStack),
                    nextComparator);
          }
        } else if (depth == 0) {
          break;
        } else {
          iterators[depth] = null;

          --depth;

          baseStack = baseStack.popStack();
          leftStack = leftStack.popStack();
          rightStack = rightStack.popStack();
        }
      }
    }

    // Update non-primary-key index data trees
    for (Index index : indexes) {
      builder.updateIndexTree(index, left, leftStack, baseStack);
    }

    // Update view data trees
    for (View view : views) {
      builder.updateViewTree(view, left, leftStack, baseStack);
    }

    // build data trees for any new indexes
    for (Index index : newIndexes) {
      builder.updateIndexTree(index, MyRevision.Empty, leftStack, baseStack);
    }

    // build data trees for any new views
    for (View view : newViews) {
      builder.updateViewTree(view, MyRevision.Empty, leftStack, baseStack);
    }

    // verify all foreign key constraints
    ForeignKeys.checkForeignKeys(
        leftStack, left, baseStack, builder, rightStack, foreignKeyResolver, null);

    ForeignKeys.checkForeignKeys(
        rightStack, right, baseStack, builder, leftStack, foreignKeyResolver, null);

    // System.out.println("merge base");
    // Node.dump(base.root, System.out, 1);
    // System.out.println("merge left");
    // Node.dump(left.root, System.out, 1);
    // System.out.println("merge right");
    // Node.dump(right.root, System.out, 1);
    // System.out.println("merge result");
    // Node.dump(builder.result.root, System.out, 1);
    // System.out.println();

    if (left.equals(builder.result)) {
      return left;
    } else if (base.equals(builder.result)) {
      return base;
    } else {
      return builder.result;
    }
  }
Exemple #16
0
  public static Node blaze(
      BlazeResult result,
      Object token,
      NodeStack stack,
      Node root,
      Object key,
      Comparator comparator) {
    if (key == null) throw new NullPointerException();

    if (root == null) {
      root = Null;
    }

    if (Debug) {
      token = new Object();
      validate(null, root);
    }

    stack = new NodeStack(stack);
    Node newRoot = getNode(token, root);

    Node old = root;
    Node new_ = newRoot;
    while (old != Null) {
      int difference = Compare.compare(key, old.key, comparator);
      if (difference < 0) {
        stack.push(new_);
        old = old.left;
        new_ = new_.left = getNode(token, old);
      } else if (difference > 0) {
        stack.push(new_);
        old = old.right;
        new_ = new_.right = getNode(token, old);
      } else {
        result.node = new_;
        stack.popStack();
        if (Debug) {
          validate(root, newRoot);
        }
        return newRoot;
      }
    }

    new_.key = key;
    result.node = new_;

    // rebalance
    new_.red = true;

    while (stack.top != null && stack.top.red) {
      if (stack.top == stack.peek().left) {
        if (stack.peek().right.red) {
          stack.top.red = false;
          stack.peek().right = getNode(token, stack.peek().right);
          stack.peek().right.red = false;
          stack.peek().red = true;
          new_ = stack.peek();
          stack.pop(2);
        } else {
          if (new_ == stack.top.right) {
            new_ = stack.top;
            stack.pop();

            Node n = leftRotate(token, new_);
            if (stack.top.right == new_) {
              stack.top.right = n;
            } else {
              stack.top.left = n;
            }
            stack.push(n);
          }
          stack.top.red = false;
          stack.peek().red = true;

          Node n = rightRotate(token, stack.peek());
          if (stack.index <= stack.base + 1) {
            newRoot = n;
          } else if (stack.peek(1).right == stack.peek()) {
            stack.peek(1).right = n;
          } else {
            stack.peek(1).left = n;
          }
          // done
        }
      } else {
        // this is just the above code with left and right swapped:
        if (stack.peek().left.red) {
          stack.top.red = false;
          stack.peek().left = getNode(token, stack.peek().left);
          stack.peek().left.red = false;
          stack.peek().red = true;
          new_ = stack.peek();
          stack.pop(2);
        } else {
          if (new_ == stack.top.left) {
            new_ = stack.top;
            stack.pop();

            Node n = rightRotate(token, new_);
            if (stack.top.right == new_) {
              stack.top.right = n;
            } else {
              stack.top.left = n;
            }
            stack.push(n);
          }
          stack.top.red = false;
          stack.peek().red = true;

          Node n = leftRotate(token, stack.peek());
          if (stack.index <= stack.base + 1) {
            newRoot = n;
          } else if (stack.peek(1).right == stack.peek()) {
            stack.peek(1).right = n;
          } else {
            stack.peek(1).left = n;
          }
          // done
        }
      }
    }

    newRoot.red = false;

    stack.popStack();
    if (Debug) {
      validate(root, newRoot);
    }
    return newRoot;
  }
Exemple #17
0
 private static boolean valuesEqual(Node a, Node b) {
   return a != null && b != null && Compare.equal(a.value, b.value);
 }
Exemple #18
0
  public static Node delete(
      Object token, NodeStack stack, Node root, Object key, Comparator comparator) {
    if (Debug) {
      token = new Object();
      validate(null, root);
    }

    if (root == Null) {
      return root;
    } else if (root.left == Null && root.right == Null) {
      if (Compare.equal(key, root.key, comparator)) {
        return Null;
      } else {
        return root;
      }
    }

    stack = new NodeStack(stack);
    Node newRoot = getNode(token, root);

    Node old = root;
    Node new_ = newRoot;
    while (old != Null) {
      if (key == null) throw new NullPointerException();
      if (old.key == null) {
        throw new NullPointerException();
      }
      int difference = Compare.compare(key, old.key, comparator);
      if (difference < 0) {
        stack.push(new_);
        old = old.left;
        new_ = new_.left = getNode(token, old);
      } else if (difference > 0) {
        stack.push(new_);
        old = old.right;
        new_ = new_.right = getNode(token, old);
      } else {
        break;
      }
    }

    if (old == Null) {
      if (stack.top.left == new_) {
        stack.top.left = Null;
      } else {
        stack.top.right = Null;
      }
      stack.popStack();
      return root;
    }

    Node dead;
    if (new_.left == Null || new_.right == Null) {
      dead = new_;
    } else {
      successor(token, new_, stack);
      dead = stack.top;
      stack.pop();
    }

    Node child;
    if (dead.left != Null) {
      child = getNode(token, dead.left);
    } else if (dead.right != Null) {
      child = getNode(token, dead.right);
    } else {
      child = Null;
    }

    if (stack.top == null) {
      child.red = false;
      stack.popStack();
      if (Debug) {
        validate(root, child);
      }
      return child;
    } else if (dead == stack.top.left) {
      stack.top.left = child;
    } else {
      stack.top.right = child;
    }

    if (dead != new_) {
      new_.key = dead.key;
      new_.value = dead.value;
    }

    if (!dead.red) {
      // rebalance
      while (stack.top != null && !child.red) {
        if (Debug) checkArgument(stack.top.token == token);
        if (child == stack.top.left) {
          Node sibling = stack.top.right = getNode(token, stack.top.right);
          if (sibling.red) {
            if (Debug) checkArgument(sibling.token == token);
            sibling.red = false;
            stack.top.red = true;

            Node n = leftRotate(token, stack.top);
            if (stack.index == stack.base) {
              newRoot = n;
            } else if (stack.peek().right == stack.top) {
              if (Debug) checkArgument(stack.peek().token == token);
              stack.peek().right = n;
            } else {
              if (Debug) checkArgument(stack.peek().token == token);
              stack.peek().left = n;
            }
            Node parent = stack.top;
            stack.top = n;
            stack.push(parent);

            sibling = stack.top.right = getNode(token, stack.top.right);
          }

          if (!(sibling.left.red || sibling.right.red)) {
            if (Debug) checkArgument(sibling.token == token);
            sibling.red = true;
            child = stack.top;
            stack.pop();
          } else {
            if (!sibling.right.red) {
              sibling.left = getNode(token, sibling.left);
              sibling.left.red = false;

              if (Debug) checkArgument(sibling.token == token);
              sibling.red = true;
              sibling = stack.top.right = rightRotate(token, sibling);
            }

            if (Debug) checkArgument(sibling.token == token);
            sibling.red = stack.top.red;
            stack.top.red = false;

            sibling.right = getNode(token, sibling.right);
            sibling.right.red = false;

            Node n = leftRotate(token, stack.top);
            if (stack.index == stack.base) {
              newRoot = n;
            } else if (stack.peek().right == stack.top) {
              if (Debug) checkArgument(stack.peek().token == token);
              stack.peek().right = n;
            } else {
              if (Debug) checkArgument(stack.peek().token == token);
              stack.peek().left = n;
            }

            child = newRoot;
            stack.clear();
          }
        } else {
          // this is just the above code with left and right swapped:
          Node sibling = stack.top.left = getNode(token, stack.top.left);
          if (sibling.red) {
            if (Debug) checkArgument(sibling.token == token);
            sibling.red = false;
            stack.top.red = true;

            Node n = rightRotate(token, stack.top);
            if (stack.index == stack.base) {
              newRoot = n;
            } else if (stack.peek().left == stack.top) {
              if (Debug) checkArgument(stack.peek().token == token);
              stack.peek().left = n;
            } else {
              if (Debug) checkArgument(stack.peek().token == token);
              stack.peek().right = n;
            }
            Node parent = stack.top;
            stack.top = n;
            stack.push(parent);

            sibling = stack.top.left = getNode(token, stack.top.left);
          }

          if (!(sibling.right.red || sibling.left.red)) {
            if (Debug) checkArgument(sibling.token == token);
            sibling.red = true;
            child = stack.top;
            stack.pop();
          } else {
            if (!sibling.left.red) {
              sibling.right = getNode(token, sibling.right);
              sibling.right.red = false;

              if (Debug) checkArgument(sibling.token == token);
              sibling.red = true;
              sibling = stack.top.left = leftRotate(token, sibling);
            }

            if (Debug) checkArgument(sibling.token == token);
            sibling.red = stack.top.red;
            stack.top.red = false;

            sibling.left = getNode(token, sibling.left);
            sibling.left.red = false;

            Node n = rightRotate(token, stack.top);
            if (stack.index == stack.base) {
              newRoot = n;
            } else if (stack.peek().left == stack.top) {
              if (Debug) checkArgument(stack.peek().token == token);
              stack.peek().left = n;
            } else {
              if (Debug) checkArgument(stack.peek().token == token);
              stack.peek().right = n;
            }

            child = newRoot;
            stack.clear();
          }
        }
      }

      if (Debug) checkArgument(child.token == token);
      child.red = false;
    }

    stack.popStack();
    if (Debug) {
      validate(root, newRoot);
    }
    return newRoot;
  }
 public void start(String[] args) {
   parseargs(args);
   if (printhelp) {
     System.out.println(
         "LB-Impute is a program for imputing missing data and correcting erroneous data in biallelic populations. Command line options are as follows:");
     System.out.println(
         "-method	<impute, compare, randomremove>	Determines what operation LB-Impute will undertake. REQUIRED.\n");
     System.out.println();
     System.out.println();
     System.out.println("IMPUTE OPTIONS\n");
     System.out.println("-f	<filename>	VCF input file name. REQUIRED.");
     System.out.println("-o	<filename>	Output file name. REQUIRED.");
     System.out.println(
         "-parents	<parentnames>	Names of parental samples separated by comma. NO SPACE BETWEEN COMMA AND NAMES. Names with spaces or commas will not work properly. REQUIRED.");
     System.out.println("-offspringimpute		LB-Impute will impute offspring.");
     System.out.println("-parentimpute		Default. LB-Impute will impute parents.");
     System.out.println(
         "-readerr	<double>	Default value is 0.05. Probability that any given read is erroneous.");
     System.out.println(
         "-genotypeerr	<double>	Default value is 0.05. Probability that any given genotype call is erroneous.");
     System.out.println(
         "-recombdist	<integer>	Default value is 10,000,000. Expected distance of 50cM.");
     System.out.println(
         "-resolveconflicts		Default is off. When on, it will use the path with the highest probability to resolve a conflict rather than leaving a conflicting genotype empty. May reduce accuracy.");
     System.out.println(
         "-dr 		Default is off. When on, a homozygous to homozygous recombination event (double recombination) will have the same probability as a single event. This may be useful for inbred populations such as NAMs.\n");
     System.out.println(
         "-minsamples	<integer>	Default is 5. Minimum number of imputed samples required to infer a parental genotype. Has no function when imputing offspring.\n");
     System.out.println(
         "-minfraction	<double>	Default is 0.5. For a genotype at a given locus to be assigned to a parent, that genotype must be at least this fraction of the total genotypes of offspring assigned to that parent. This value should be somewhat low for low coverage populations, as false homozygotes will be confounding.");
     System.out.println(
         "-window	<integer>	Default is 7. Window length of the Vitterbi trellis. Longer windows produce more accurate results, but have longer runtimes. It is recommended to keep this between 5 and 7, though 2 is the minimum.");
     System.out.println();
     System.out.println();
     System.out.println();
     System.out.println("RANDOMREMOVE OPTIONS\n");
     System.out.println(
         "Random remove removes calls at a specific level or range of coverage to serve as a validation set. When used along with compare, it can validate imputation on a dataset. Prints new dataset to stdout.");
     System.out.println();
     System.out.println("-f	<filename>	Name of VCF file. REQUIRED.");
     System.out.println(
         "-parents	<parentnames>	Names of parental samples separated by comma. NO SPACE BETWEEN COMMA AND NAMES. Names with spaces or commas will not work properly. REQUIRED.");
     System.out.println(
         "-removefraction	<double>	Fraction of calls fitting criteria to be removed.");
     System.out.println(
         "-minhomcov	<int>	Minimum coverage of homozygous calls to be removed. Inclusive. REQUIRED.");
     System.out.println(
         "-maxhomcov	<int>	Maximum coverage of homozygous calls to be removed. Inclusive. REQUIRED.");
     System.out.println(
         "-minhetcov	<int>	Minimum coverage of heterozygous calls to be removed. Inclusive. REQUIRED.");
     System.out.println(
         "-maxhetcov	<int>	Maximum coverage of heterozygous calls to be removed. Inclusive. REQUIRED.");
     System.out.println();
     System.out.println();
     System.out.println("COMPARE OPTIONS");
     System.out.println(
         "Compare compares the original file with an imputed file and a file with a validation set removed then outputs statistics to stdout.");
     System.out.println("-mainfile	<filename>	Name of original file. REQUIRED.");
     System.out.println("-imputefile	<filename>	Name of imputed file. REQUIRED.");
     System.out.println(
         "-missfile	<filename>	Name of file with validation set removed. REQUIRED.");
     System.out.println("-offspringcompare		Compares offspring rather than parental calls.");
     System.out.println(
         "-parents	<parentnames>	Names of parental samples separated by comma. NO SPACE BETWEEN COMMA AND NAMES. Names with spaces or commas will not work properly. REQUIRED.");
     System.exit(0);
   }
   if (method.equals(
       "compare")) { // this is the algorithm for accuracy metrics. Requires a file with correct
     // genotypes, erroneous or missing genotypes, and imputed genotypes.
     Compare compare = new Compare();
     compare.compare(args);
   }
   if (method.equals("randomremove")) { // I don't think this is used anymore.
     RemoveValues randomremove = new RemoveValues();
     randomremove.remove(args);
   }
   if (method.equals("impute")) { // this is the primary algorithm for imputation.
     Impute impute = new Impute();
     impute.impute(args);
   }
 }
Exemple #20
0
 public void compare(ObjectContainer con, Object obj, int ver) {
   Compare.compare(con, set(newInstance(), ver), obj, "", null);
 }
Exemple #21
0
  /** TwoGtp main function. */
  public static void main(String[] args) {
    boolean exitError = false;
    try {
      String options[] = {
        "alternate",
        "analyze:",
        "auto",
        "black:",
        "compare",
        "config:",
        "debugtocomment",
        "force",
        "games:",
        "help",
        "komi:",
        "maxmoves:",
        "observer:",
        "openings:",
        "referee:",
        "sgffile:",
        "size:",
        "threads:",
        "time:",
        "verbose",
        "version",
        "white:",
        "xml"
      };
      Options opt = Options.parse(args, options);
      opt.checkNoArguments();
      if (opt.contains("help")) {
        String helpText =
            "Usage: gogui-twogtp [options]\n"
                + "\n"
                + "-alternate      alternate colors\n"
                + "-analyze file   analyze result file\n"
                + "-auto           autoplay games\n"
                + "-black          command for black program\n"
                + "-compare        compare list of sgf files\n"
                + "-config         config file\n"
                + "-debugtocomment save stderr of programs in SGF comments\n"
                + "-force          overwrite existing files\n"
                + "-games          number of games (0=unlimited)\n"
                + "-help           display this help and exit\n"
                + "-komi           komi\n"
                + "-maxmoves       move limit\n"
                + "-observer       command for observer program\n"
                + "-openings       directory with opening sgf files\n"
                + "-referee        command for referee program\n"
                + "-sgffile        filename prefix\n"
                + "-size           board size for autoplay (default 19)\n"
                + "-threads n      number of threads\n"
                + "-time spec      set time limits (min[+min/moves])\n"
                + "-verbose        log GTP streams to stderr\n"
                + "-version        print version and exit\n"
                + "-white          command for white program\n"
                + "-xml            save games in XML format\n";
        System.out.print(helpText);
        System.exit(0);
      }
      boolean compare = opt.contains("compare");
      if (compare) {
        Compare.compare(opt.getArguments());
        System.exit(0);
      }
      if (opt.contains("version")) {
        System.out.println("gogui-twogtp " + "XXX");
        System.exit(0);
      }
      boolean force = opt.contains("force");
      if (opt.contains("analyze")) {
        String filename = opt.get("analyze");
        new Analyze(filename, force);
        return;
      }
      boolean alternate = opt.contains("alternate");
      boolean auto = opt.contains("auto");
      boolean debugToComment = opt.contains("debugtocomment");
      boolean verbose = opt.contains("verbose");
      String black = opt.get("black", "");
      if (black.equals("")) throw new ErrorMessage("No black program set");
      String white = opt.get("white", "");
      if (white.equals("")) throw new ErrorMessage("No white program set");
      String referee = opt.get("referee", "");
      String observer = opt.get("observer", "");
      int size = opt.getInteger("size", GoPoint.DEFAULT_SIZE, 1, GoPoint.MAX_SIZE);
      Komi komi = new Komi(6.5);
      if (opt.contains("komi")) komi = Komi.parseKomi(opt.get("komi"));
      int maxMoves = opt.getInteger("maxmoves", 1000, -1);
      TimeSettings timeSettings = null;
      if (opt.contains("time")) timeSettings = TimeSettings.parse(opt.get("time"));
      int defaultGames = (auto ? 1 : 0);
      int numberGames = opt.getInteger("games", defaultGames, 0);
      int numberThreads = opt.getInteger("threads", 1, 1);
      if (numberThreads > 1 && !auto) throw new ErrorMessage("Option -threads needs option -auto");
      String sgfFile = opt.get("sgffile", "");
      if (opt.contains("games") && sgfFile.equals(""))
        throw new ErrorMessage("Use option -sgffile with -games");
      Openings openings = null;
      if (opt.contains("openings")) openings = new Openings(new File(opt.get("openings")));
      boolean useXml = opt.contains("xml");
      if (auto) System.in.close();

      TwoGtp twoGtp[] = new TwoGtp[numberThreads];
      TwoGtpThread thread[] = new TwoGtpThread[numberThreads];
      ResultFile resultFile = null;
      for (int i = 0; i < numberThreads; ++i) {
        ArrayList<Program> allPrograms = new ArrayList<Program>();
        Program blackProgram = new Program(black, "Black", "B", verbose);
        allPrograms.add(blackProgram);
        Program whiteProgram = new Program(white, "White", "W", verbose);
        allPrograms.add(whiteProgram);
        Program refereeProgram;
        if (referee.equals("")) refereeProgram = null;
        else {
          refereeProgram = new Program(referee, "Referee", "R", verbose);
          allPrograms.add(refereeProgram);
        }
        for (Program program : allPrograms) program.setLabel(allPrograms);
        if (!sgfFile.equals("") && resultFile == null)
          resultFile =
              new ResultFile(
                  force,
                  blackProgram,
                  whiteProgram,
                  refereeProgram,
                  numberGames,
                  size,
                  komi,
                  sgfFile,
                  openings,
                  alternate,
                  useXml,
                  numberThreads);
        if (i > 0) verbose = false;
        twoGtp[i] =
            new TwoGtp(
                blackProgram,
                whiteProgram,
                refereeProgram,
                observer,
                size,
                komi,
                numberGames,
                alternate,
                sgfFile,
                verbose,
                openings,
                timeSettings,
                resultFile);
        twoGtp[i].setMaxMoves(maxMoves);
        if (debugToComment) twoGtp[i].setDebugToComment(true);
        if (auto) {
          thread[i] = new TwoGtpThread(twoGtp[i]);
          thread[i].start();
        }
      }
      if (auto) {
        for (int i = 0; i < numberThreads; ++i) thread[i].join();
        for (int i = 0; i < numberThreads; ++i)
          if (thread[i].getException() != null) {
            StringUtil.printException(thread[i].getException());
            exitError = true;
          }
      } else twoGtp[0].mainLoop(System.in, System.out);
      if (resultFile != null) resultFile.close();
    } catch (Throwable t) {
      StringUtil.printException(t);
      exitError = true;
    }
    if (exitError) System.exit(1);
  }