コード例 #1
0
  /**
   * Set <CODE>Vector</CODE> of <CODE>String</CODE>s describing the cursor location from the cursor
   * location; this is invoked when the cursor location changes or the cursor display status changes
   */
  public void setCursorStringVector() {
    synchronized (cursorStringVector) {
      cursorStringVector.removeAllElements();
      float[][] cursor = new float[3][1];
      double[] cur = getCursor();
      cursor[0][0] = (float) cur[0];
      cursor[1][0] = (float) cur[1];
      cursor[2][0] = (float) cur[2];
      Enumeration maps = display.getMapVector().elements();
      while (maps.hasMoreElements()) {
        try {
          ScalarMap map = (ScalarMap) maps.nextElement();
          DisplayRealType dreal = map.getDisplayScalar();
          DisplayTupleType tuple = dreal.getTuple();
          int index = dreal.getTupleIndex();
          if (tuple != null
              && (tuple.equals(Display.DisplaySpatialCartesianTuple)
                  || (tuple.getCoordinateSystem() != null
                      && tuple
                          .getCoordinateSystem()
                          .getReference()
                          .equals(Display.DisplaySpatialCartesianTuple)))) {
            float[] fval = new float[1];
            if (tuple.equals(Display.DisplaySpatialCartesianTuple)) {
              fval[0] = cursor[index][0];
            } else {
              float[][] new_cursor = tuple.getCoordinateSystem().fromReference(cursor);
              fval[0] = new_cursor[index][0];
            }
            float[] dval = map.inverseScaleValues(fval);
            RealType real = (RealType) map.getScalar();

            // WLH 31 Aug 2000
            Real r = new Real(real, dval[0]);
            Unit overrideUnit = map.getOverrideUnit();
            Unit rtunit = real.getDefaultUnit();
            // units not part of Time string
            // DRM 2003-08-19: don't check for equality since toString
            // may be different
            if (overrideUnit != null
                && // !overrideUnit.equals(rtunit) &&
                (!Unit.canConvert(rtunit, CommonUnit.secondsSinceTheEpoch)
                    || rtunit.getAbsoluteUnit().equals(rtunit))) {
              dval[0] = (float) overrideUnit.toThis((double) dval[0], rtunit);
              r = new Real(real, dval[0], overrideUnit);
            }
            String valueString = r.toValueString();

            // WLH 27 Oct 2000
            String s = map.getScalarName() + " = " + valueString;
            // String s = real.getName() + " = " + valueString;

            cursorStringVector.addElement(s);
          } // end if (tuple != null && ...)
        } catch (VisADException e) {
        }
      } // end while(maps.hasMoreElements())
    } // end synchronized (cursorStringVector)
    render_trigger();
  }
コード例 #2
0
ファイル: JimpleLocal.java プロジェクト: richardxx/soot
 public void convertToBaf(JimpleToBafContext context, List<Unit> out) {
   Unit u = Baf.v().newLoadInst(getType(), context.getBafLocalOfJimpleLocal(this));
   out.add(u);
   Iterator it = context.getCurrentUnit().getTags().iterator();
   while (it.hasNext()) {
     u.addTag((Tag) it.next());
   }
 }
コード例 #3
0
ファイル: StaticFieldRef.java プロジェクト: safdariqbal/soot
  public void convertToBaf(JimpleToBafContext context, List out) {
    Unit u = Baf.v().newStaticGetInst(fieldRef);
    out.add(u);

    Iterator it = context.getCurrentUnit().getTags().iterator();
    while (it.hasNext()) {
      u.addTag((Tag) it.next());
    }
  }
コード例 #4
0
ファイル: RenderState.java プロジェクト: grafov/tribaltrouble
 public final void visitUnit(final Unit unit) {
   float z_offset =
       getVisuallyCorrectHeight(unit.getPositionX(), unit.getPositionY()) + unit.getOffsetZ();
   visitSelectable(
       unit_visitor,
       unit,
       z_offset,
       unit.getUnitTemplate().getSelectionRadius(),
       unit.getUnitTemplate().getSelectionHeight());
 }
コード例 #5
0
ファイル: Wall.java プロジェクト: shaon0000/Tower-Defense
  public void attack(Unit enemy) {

    if (heatCounter >= heat) {

      fireX = enemy.getX();
      fireY = enemy.getY();
      enemy.freeze(level * 2.0);
      effects.add(new CircleTowerEffect(fireX, fireY, Global.MAX_SIZE, 100));
    }
  }
コード例 #6
0
  /**
   * Produces a string representation of the puzzle, this shall be a 9 columns and 9 rows in size,
   * separated by new line characters.
   *
   * @return A string representation of this puzzle.
   */
  public String toString() {

    String out = new String();

    for (Unit x : rows) {
      out += x.toString() + "\n";
    }

    return out;
  }
コード例 #7
0
ファイル: UnitGraph.java プロジェクト: safdariqbal/soot
 public String toString() {
   Iterator it = unitChain.iterator();
   StringBuffer buf = new StringBuffer();
   while (it.hasNext()) {
     Unit u = (Unit) it.next();
     buf.append("// preds: " + getPredsOf(u) + "\n");
     buf.append(u.toString() + '\n');
     buf.append("// succs " + getSuccsOf(u) + "\n");
   }
   return buf.toString();
 }
コード例 #8
0
ファイル: Code.java プロジェクト: peterthiemann/gradual-java
 @Override
 public List<Unit> getPredsOf(Unit unit) {
   if (unit.equals(nIf)) {
     return Collections.emptyList();
   } else if (unit.equals(n1)) {
     return Collections.singletonList(nIf);
   } else if (unit.equals(n2)) {
     return Collections.singletonList(nIf);
   } else {
     throw new RuntimeException("UNEXPECTED CASE");
   }
 }
コード例 #9
0
ファイル: JThrowStmt.java プロジェクト: Hounge/apkinspector
  public void convertToBaf(JimpleToBafContext context, List<Unit> out) {
    ((ConvertToBaf) getOp()).convertToBaf(context, out);

    Unit u;
    out.add(u = Baf.v().newThrowInst());

    Unit currentUnit = this;

    Iterator it = currentUnit.getTags().iterator();
    while (it.hasNext()) {
      u.addTag((Tag) it.next());
    }
  }
コード例 #10
0
ファイル: Printer.java プロジェクト: safdariqbal/soot
  private int addJimpleLnTags(int lnNum, Unit stmt, int endLn) {

    if (endLn - lnNum <= 1) {
      stmt.addTag(new JimpleLineNumberTag(lnNum));
      // G.v().out.println(stmt.getClass().toString());
      lnNum++;
      return lnNum;
    } else {
      stmt.addTag(new JimpleLineNumberTag(lnNum, endLn));
      // G.v().out.println("multi-line: "+stmt.getClass().toString());
      endLn++;
      return endLn;
    }
  }
コード例 #11
0
ファイル: ScalarMap.java プロジェクト: jon4than/visad
 /**
  * Set display Unit to override default Unit of Scalar; MUST be called before any data are
  * displayed
  *
  * @param unit unit that data will be displayed with
  * @throws VisADException <CODE>unit</CODE> is not convertable with the default unit or scalar is
  *     not a RealType.
  */
 public void setOverrideUnit(Unit unit) throws VisADException {
   if (!(Scalar instanceof RealType)) {
     throw new UnitException("Scalar is not RealType");
   }
   Unit rtunit = ((RealType) Scalar).getDefaultUnit();
   if (!Unit.canConvert(unit, rtunit)) {
     throw new UnitException("unit not convertable with RealType default");
   }
   if (unit != null) {
     overrideUnit = unit;
     override_offset = overrideUnit.toThis(0.0, rtunit);
     override_scale = overrideUnit.toThis(1.0, rtunit) - override_offset;
   }
 }
コード例 #12
0
  /**
   * Traverse the statements in the given body, looking for aggregation possibilities; that is,
   * given a def d and a use u, d has no other uses, u has no other defs, collapse d and u.
   *
   * <p>option: only-stack-locals; if this is true, only aggregate variables starting with $
   */
  protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
    StmtBody body = (StmtBody) b;
    boolean onlyStackVars = PhaseOptions.getBoolean(options, "only-stack-locals");

    int aggregateCount = 1;

    if (Options.v().time()) Timers.v().aggregationTimer.start();
    boolean changed = false;

    Map<ValueBox, Zone> boxToZone =
        new HashMap<ValueBox, Zone>(body.getUnits().size() * 2 + 1, 0.7f);

    // Determine the zone of every box
    {
      Zonation zonation = new Zonation(body);

      for (Unit u : body.getUnits()) {
        Zone zone = zonation.getZoneOf(u);

        for (ValueBox box : u.getUseBoxes()) {
          boxToZone.put(box, zone);
        }

        for (ValueBox box : u.getDefBoxes()) {
          boxToZone.put(box, zone);
        }
      }
    }

    do {
      if (Options.v().verbose())
        G.v()
            .out
            .println(
                "["
                    + body.getMethod().getName()
                    + "] Aggregating iteration "
                    + aggregateCount
                    + "...");

      // body.printTo(new java.io.PrintWriter(G.v().out, true));

      changed = internalAggregate(body, boxToZone, onlyStackVars);

      aggregateCount++;
    } while (changed);

    if (Options.v().time()) Timers.v().aggregationTimer.end();
  }
コード例 #13
0
ファイル: FNUnit.java プロジェクト: nikhi/basex
  /**
   * Performs the test function.
   *
   * @param ctx query context
   * @return resulting value
   * @throws QueryException query exception
   */
  private Item test(final QueryContext ctx) throws QueryException {
    final Unit unit = new Unit(ctx, info);
    if (expr.length == 0) return unit.test(sc);

    final ArrayList<StaticFunc> funcs = new ArrayList<>();
    final Iter ir = ctx.iter(expr[0]);
    for (Item it; (it = ir.next()) != null; ) {
      final FItem fi = checkFunc(it, ctx);
      if (fi.funcName() != null) {
        final StaticFunc sf = ctx.funcs.get(fi.funcName(), fi.arity(), null, true);
        if (sf != null) funcs.add(sf);
      }
    }
    return unit.test(sc, funcs);
  }
コード例 #14
0
ファイル: RenderState.java プロジェクト: grafov/tribaltrouble
 public final void markDetailPolygon(ElementRenderState render_state, int level) {
   Unit unit = (Unit) render_state.model;
   super.markDetailPolygon(render_state, level);
   UnitSupplyContainer supply_container = unit.getSupplyContainer();
   if (!render_state.render_state.isPicking()
       && unit.getAbilities().hasAbilities(Abilities.BUILD)
       && supply_container.getSupplyType() != null) {
     if (supply_container.getNumSupplies() > 0) {
       SpriteRenderer supply_sprite =
           render_state.getRenderer(
               supply_container.getSupplySpriteRenderer(supply_container.getSupplyType()));
       supply_sprite.addToRenderList(level, render_state, false);
     }
   }
 }
コード例 #15
0
  public void convertToBaf(JimpleToBafContext context, List out) {
    for (int i = 0; i < argBoxes.size(); i++) {
      ((ConvertToBaf) (getArg(i))).convertToBaf(context, out);
    }

    Unit u;
    out.add(u = Baf.v().newStaticInvokeInst(methodRef));

    Unit currentUnit = context.getCurrentUnit();

    Iterator it = currentUnit.getTags().iterator();
    while (it.hasNext()) {
      u.addTag((Tag) it.next());
    }
  }
コード例 #16
0
ファイル: ScalarMap.java プロジェクト: jon4than/visad
 /**
  * return an array of display (DisplayRealType) values by linear scaling (if applicable) the
  * data_values array (RealType values); results are scaled by the given scale factor
  *
  * @param values to scale as bytes
  * @return array of display values
  */
 public byte[] scaleValues(byte[] values, int factor) throws VisADException {
   if (values == null) return null;
   byte[] new_values = null;
   if (badRange()) {
     new_values = new byte[values.length];
   } else {
     if (overrideUnit != null && !overrideUnit.equals(((RealType) Scalar).getDefaultUnit())) {
       throw new VisADException("scaleValues(byte[]): non-default units not supported");
     }
     if (isScaled) {
       new_values = new byte[values.length];
       for (int i = 0; i < values.length; i++) {
         float v = (float) values[i];
         if (v < 0) v += 256;
         v = (float) (factor * (offset + scale * v));
         if (v < 0) v = 0;
         else if (v > 255) v = 255;
         new_values[i] = (byte) v;
       }
     } else {
       new_values = values;
     }
   }
   return new_values;
 }
コード例 #17
0
ファイル: ScalarMap.java プロジェクト: jon4than/visad
 /**
  * return an array of data (RealType) values by inverse linear scaling (if applicable) the
  * display_values array (DisplayRealType values); this is useful for direct manipulation and
  * cursor labels
  *
  * @param values display values
  * @param newArray false to transform in place
  * @return data values
  */
 public float[] inverseScaleValues(float[] values, boolean newArray) {
   if (values == null) return null;
   float[] new_values = (newArray) ? new float[values.length] : values;
   if (isScaled) {
     for (int i = 0; i < values.length; i++) {
       if (values[i] == values[i]) {
         new_values[i] = (float) ((values[i] - offset) / scale);
       } else {
         new_values[i] = Float.NaN;
       }
     }
   } else {
     if (newArray) {
       for (int i = 0; i < values.length; i++) {
         new_values[i] = values[i];
       }
     }
   }
   // WLH 31 Aug 2000
   if (overrideUnit != null) {
     // float[] old_values = new_values;
     try {
       new_values =
           overrideUnit.toThat(
               new_values, ((RealType) Scalar).getDefaultUnit(), false); // already copied above
     } catch (UnitException e) {
     }
     /*
     System.out.println("inverse values = " + values[0] + " " + old_values[0] + " " +
                        new_values[0]);
     */
   }
   return new_values;
 }
コード例 #18
0
ファイル: ScalarMap.java プロジェクト: jon4than/visad
 /**
  * return an array of display (DisplayRealType) values by linear scaling (if applicable) the
  * data_values array (RealType values)
  *
  * @param values to scale as floats
  * @param newArray false to scale in place
  * @return array of display values
  */
 public float[] scaleValues(float[] values, boolean newArray) {
   /* WLH 23 June 99
       if (values == null || badRange()) return null;
   */
   if (values == null) return null;
   float[] new_values = null;
   if (badRange()) {
     new_values = (newArray) ? new float[values.length] : values;
     for (int i = 0; i < values.length; i++) new_values[i] = Float.NaN;
   } else {
     // float[] old_values = values;
     // WLH 31 Aug 2000
     // if (overrideUnit != null) {
     // DRM 11 Jun 2003
     if (overrideUnit != null && !overrideUnit.equals(((RealType) Scalar).getDefaultUnit())) {
       try {
         values = overrideUnit.toThis(values, ((RealType) Scalar).getDefaultUnit(), newArray);
       } catch (UnitException e) {
       }
     }
     if (isScaled) {
       new_values = (newArray) ? new float[values.length] : values;
       for (int i = 0; i < values.length; i++) {
         if (values[i] == values[i]) {
           new_values[i] = (float) (offset + scale * values[i]);
         } else {
           new_values[i] = Float.NaN;
         }
       }
     } else {
       new_values = values;
     }
     /*
     if (overrideUnit != null) {
       System.out.println("values = " + old_values[0] + " " + values[0] + " " +
                          new_values[0]);
     }
     */
   }
   /* SRE 27 Oct 99
       System.out.println(
         "ScalarMap.scaleValues(double[]): values[0] = " + values[0] +
         "; new_values[0] = " + new_values[0]);
   */
   return new_values;
 }
コード例 #19
0
ファイル: BoardPanel.java プロジェクト: Toshu/RoBoardGames
  public void finishedSelectingUnits(TilePanel tilePanel, List<Unit> chosenUnits) {
    UnitActionDetector unitActionDetector =
        new UnitActionDetector(selectedPanel, selectedUnit, tilePanel, chosenUnits);

    if (unitActionDetector.isSelectingUnit()) {
      selectedPanel = tilePanel;
      selectedPanel.addTileStateFromKey(selectedStateKey);
      repaintPanels(selectedPanel);
      selectedUnit = getUnit(chosenUnits);
      selectValidMovements(selectedPanel.getTile(), selectedUnit);
    } else if (unitActionDetector.isDeselectingUnit()) {
      selectedPanel.removeTileStateFromKey(selectedStateKey);
      deselectValidMovements(selectedPanel.getTile(), selectedUnit);
      repaintPanels(selectedPanel);
      selectedPanel = null;
      selectedUnit = null;
    } else if (unitActionDetector.isMovingUnit()) {
      Position from = selectedPanel.getTile().getPosition();
      Position to = tilePanel.getTile().getPosition();
      if (movementStrategy.isValidMove(selectedUnit, from, to, unitMap)) {
        deselectValidMovements(selectedPanel.getTile(), selectedUnit);
        selectedPanel.removeTileStateFromKey(selectedStateKey);

        List<Unit> units = unitMap.get(to);
        if (units != null && !units.isEmpty()) {
          Unit defending = units.get(0);
          BattleStrategy strategy =
              battleStrategyConfiguration.getBattleStrategy(
                  selectedUnit, defending, selectedPanel.getTile(), tilePanel.getTile());
          Unit winner = strategy.getWinner(selectedUnit, defending);
          if (winner.equals(selectedUnit)) {
            units.remove(defending);
          }
        }
        board.move(selectedUnit, from, to);
        repaintPanels(selectedPanel);
        selectedPanel = null;
        selectedUnit = null;
      }
    }
    frame.setEnabled(true);
    resetPositions();
  }
コード例 #20
0
ファイル: UnitGraph.java プロジェクト: safdariqbal/soot
  /**
   * Utility method for <tt>UnitGraph</tt> constructors. It computes the edges corresponding to
   * unexceptional control flow.
   *
   * @param unitToSuccs A {@link Map} from {@link Unit}s to {@link List}s of {@link Unit}s. This is
   *     an ``out parameter''; callers must pass an empty {@link Map}.
   *     <tt>buildUnexceptionalEdges</tt> will add a mapping for every <tt>Unit</tt> in the body to
   *     a list of its unexceptional successors.
   * @param unitToPreds A {@link Map} from {@link Unit}s to {@link List}s of {@link Unit}s. This is
   *     an ``out parameter''; callers must pass an empty {@link Map}.
   *     <tt>buildUnexceptionalEdges</tt> will add a mapping for every <tt>Unit</tt> in the body to
   *     a list of its unexceptional predecessors.
   */
  protected void buildUnexceptionalEdges(Map unitToSuccs, Map unitToPreds) {

    // Initialize the predecessor sets to empty
    for (Iterator unitIt = unitChain.iterator(); unitIt.hasNext(); ) {
      unitToPreds.put(unitIt.next(), new ArrayList());
    }

    Iterator unitIt = unitChain.iterator();
    Unit currentUnit, nextUnit;

    nextUnit = unitIt.hasNext() ? (Unit) unitIt.next() : null;

    while (nextUnit != null) {
      currentUnit = nextUnit;
      nextUnit = unitIt.hasNext() ? (Unit) unitIt.next() : null;

      List successors = new ArrayList();

      if (currentUnit.fallsThrough()) {
        // Add the next unit as the successor
        if (nextUnit != null) {
          successors.add(nextUnit);
          ((List) unitToPreds.get(nextUnit)).add(currentUnit);
        }
      }

      if (currentUnit.branches()) {
        for (Iterator targetIt = currentUnit.getUnitBoxes().iterator(); targetIt.hasNext(); ) {
          Unit target = ((UnitBox) targetIt.next()).getUnit();
          // Arbitrary bytecode can branch to the same
          // target it falls through to, so we screen for duplicates:
          if (!successors.contains(target)) {
            successors.add(target);
            ((List) unitToPreds.get(target)).add(currentUnit);
          }
        }
      }

      // Store away successors
      unitToSuccs.put(currentUnit, successors);
    }
  }
コード例 #21
0
  /**
   * This method return the the sum of duplicate values in each unit.
   *
   * <p>Each unit may contain each number 1 to 9 once. The conflict count is incremented by 1 each
   * time a number occurs more than once in a unit. So if a unit contains [1,3,4,1,1], its conflict
   * count is 2.
   *
   * @return The the sum of duplicate values in each unit.
   */
  public Integer conflictCount() {

    if (modified) {
      conflicts = 0;

      for (Unit x : rows) {
        conflicts += x.conflictCount();
      }

      for (Unit x : cols) {
        conflicts += x.conflictCount();
      }

      for (Unit x : boxes) {
        conflicts += x.conflictCount();
      }
    }

    return conflicts;
  }
コード例 #22
0
  /** @param args the command line arguments */
  public static void main(String[] args) {
    // TODO code application logic here
    Model model;
    String insertstmt;
    String insertmodel = "",
        insertspecies = "",
        insertcompartment = "",
        insertfunction = "",
        insertunitdef = "",
        insertunits = "",
        insertreaction = "",
        insertreactant = "",
        insertproduct = "";
    String insertmodifier = "",
        insertklaw = "",
        insertrules = "",
        insertconstraint = "",
        insertdelay = "",
        inserttrigger = "",
        insertevent = "",
        inserteventassign = "",
        insertparameter = "";
    String insertstatement = "";
    String server, user, password, dbname, filepath;

    String Filedata = "";

    String cwd = System.getProperty("user.dir");

    if (args.length == 0) {
      server = "localhost";
      user = "******";
      password = "******";
      dbname = "sbmldb2";

      /**
       * Path to extract the SBML files from database, where cwd is
       * "github\db2sbml\dbtosbml_standalone_Project\dbtosbml" so add a folder in this directory and
       * mention folder name instead of extractedbm folder
       */
      filepath = cwd + "\\extractedbm\\";
    } else {
      server = args[0];
      user = args[1];
      password = args[2];
      dbname = args[3];
      filepath = args[4];
    }

    try {
      Filedata = readFileAsString(cwd + "\\sbmldbschema.sql");
    } catch (Exception e) {
      e.printStackTrace();
    }

    Mysqlconn sql = new Mysqlconn(server, user, password, dbname);
    // String modelids.getId() = "MorrisonAllegra" ;

    ASTNode math = null;
    int level = 0, version = 0;

    ArrayList<modellist> modelidlist = sql.getmodels();
    insertstatement =
        "LOCK TABLES `model` WRITE,`species` WRITE,`compartment` WRITE,`functiondefinition` WRITE,";
    insertstatement =
        insertstatement
            + "`listofunitdefinitions` WRITE,`listofunits` WRITE,`reaction` WRITE,`simplespeciesreference` WRITE,";
    insertstatement =
        insertstatement
            + "`modifierspeciesreference` WRITE,`kineticlaw` WRITE,`parameter` WRITE,`sbmlconstraint` WRITE,";
    insertstatement =
        insertstatement
            + "`event` WRITE,`sbmltrigger` WRITE,`delay` WRITE,`eventassignment` WRITE,`rules` WRITE"
            + ";";

    for (modellist modelids : modelidlist) {

      ArrayList<modellist> modellevel = sql.getmodeldetails(modelids.getId());

      for (modellist modellv : modellevel) {
        level = modellv.getlevel();
        version = modellv.getversion();
      }

      SBMLDocument doc = new SBMLDocument(level, version);

      ArrayList<modellist> modellists = sql.getmodeldetails(modelids.getId());

      if (!modellists.isEmpty())
        insertmodel =
            insertmodel
                + "\nInsert Into model (id, name,SBML_level,version,notes,annotation) Values";
      for (modellist models : modellists) {
        insertmodel =
            insertmodel
                + "(\'"
                + models.getId()
                + "\',\'"
                + models.getName()
                + "\',"
                + models.getlevel()
                + ","
                + models.getversion()
                + ",\'"
                + models.getnotes()
                + "\',\'"
                + models.getannotation().toString()
                + "\'),";
        model = doc.createModel(models.getId());
        model.setName(models.getName());
        // System.out.println("model : " + models.getId());
        // model.setNotes(models.getnotes());  // there is some null exception is command line run
        // but run perfectly from netbeans so ommented out
        if (!models.getannotation().equals("")) {
          Annotation annot = new Annotation(models.getannotation().toString());
          model.setAnnotation(annot);
        }
        doc.setModel(model);
      }
      if (!modellists.isEmpty()) {
        insertmodel = insertmodel.substring(0, insertmodel.length() - 1);
        insertmodel = insertmodel + ';';
      }
      //   insertmodel = insertmodel + "\nUNLOCK TABLES;";
      //  System.out.println(insertmodel);

      ArrayList<SpeciesList> specieslist = sql.getspecies(modelids.getId());

      if (!specieslist.isEmpty())
        insertspecies =
            insertspecies
                + "\nInsert Into species (id, name, compartment, initialAmount, initialConcentration,substanceUnits,hasOnlySubstanceUnits,boundaryCondition,constant,conversionFactor,model_id,annotation) Values";
      for (SpeciesList species : specieslist) {
        insertspecies =
            insertspecies
                + "(\'"
                + species.getId()
                + "\',\'"
                + species.getName()
                + "\',\'"
                + species.getcompartment()
                + "\',"
                + species.getia()
                + ","
                + species.getic()
                + ",\'"
                + species.getsu()
                + "\',"
                + species.gethosu()
                + ","
                + species.getbc()
                + ","
                + species.getconstant()
                + ","
                + species.getcf()
                + ",\'"
                + modelids.getId()
                + "\',\'"
                + species.getannotation()
                + "\'),";
        Species sp = doc.getModel().createSpecies(species.getId());
        sp.setName(species.getName());
        sp.setCompartment(species.getcompartment());
        sp.setConstant(species.getconstant());
        sp.setInitialAmount(species.getia());
        sp.setInitialConcentration(species.getic());
        sp.setHasOnlySubstanceUnits(species.gethosu());
        if (doc.getModel().getLevel() == 3) sp.setConversionFactor(species.getcf());
        sp.setBoundaryCondition(species.getbc());
        sp.setSubstanceUnits(species.getsu());
        if (!species.getannotation().equals("")) {
          Annotation annot = new Annotation(species.getannotation().toString());
          sp.setAnnotation(annot);
        }
        // doc.getModel().addSpecies(sp) ;
      }
      if (!specieslist.isEmpty()) {
        insertspecies = insertspecies.substring(0, insertspecies.length() - 1);
        insertspecies = insertspecies + ';';
      }

      ArrayList<CompartmentList> complist = sql.getcompartments(modelids.getId());

      if (!complist.isEmpty())
        insertcompartment =
            insertcompartment
                + "\nInsert Into compartment (id, name,constant,model_id,spacialDimensions,size,units) Values";

      for (CompartmentList comp : complist) {
        insertcompartment =
            insertcompartment
                + "(\'"
                + comp.getId()
                + "\',\'"
                + comp.getName()
                + "\',"
                + comp.getconstant()
                + ",\'"
                + modelids.getId()
                + "\',"
                + comp.getspatialdimensions()
                + ","
                + comp.getsize()
                + ","
                + comp.getunits()
                + "\'),";
        Compartment c = doc.getModel().createCompartment(comp.getId());
        c.setName(comp.getName());
        c.setConstant(comp.getconstant());
        c.setSize(comp.getsize());
        c.setSpatialDimensions(comp.getspatialdimensions());
        if (comp.getspatialdimensions() != 0) c.setUnits(comp.getunits());
        // doc.getModel().addSpecies(sp) ;
      }
      if (!complist.isEmpty()) {
        insertcompartment = insertcompartment.substring(0, insertcompartment.length() - 1);
        insertcompartment = insertcompartment + ';';
      }

      ArrayList<functionList> funclist = sql.getfunctions(modelids.getId());

      if (!funclist.isEmpty())
        insertfunction =
            insertfunction + "\nInsert Into functiondefinition (id, xmlns,model_id) Values";

      for (functionList func : funclist) {
        insertfunction =
            insertfunction
                + "(\'"
                + func.getId()
                + "\',\'"
                + func.getxmlns()
                + "\',\'"
                + modelids.getId()
                + "\'),";
        FunctionDefinition fd = doc.getModel().createFunctionDefinition(func.getId());

        try {
          math = ASTNode.parseFormula(func.getxmlns());
          fd.setMath(math);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      if (!funclist.isEmpty()) {
        insertfunction = insertfunction.substring(0, insertfunction.length() - 1);
        insertfunction = insertfunction + ';';
      }

      ArrayList<unitList> unitlist = sql.getunitlist(modelids.getId());

      if (!unitlist.isEmpty())
        insertunitdef =
            insertunitdef + "\nInsert Into listofunitdefinitions (id,name,model_id) Values";

      for (unitList units : unitlist) {
        insertunitdef =
            insertunitdef
                + "(\'"
                + units.getId()
                + "\',\'"
                + units.getName()
                + "\',\'"
                + modelids.getId()
                + "\'),";

        UnitDefinition ud = doc.getModel().createUnitDefinition(units.getId());
        ud.setName(units.getName());
        ArrayList<unitList> unitdeflist = sql.getunitdef(units.getId());

        if (!unitdeflist.isEmpty())
          insertunits =
              insertunits
                  + "\nInsert Into listofunits (listofunitdefinitions_id,kind, scale,exponent,multiplier) Values";

        for (unitList unitdef : unitdeflist) {
          insertunits =
              insertunits
                  + "(\'"
                  + units.getId()
                  + "\',\'"
                  + unitdef.getkind()
                  + "\',"
                  + unitdef.getscale()
                  + ","
                  + unitdef.getexponent()
                  + ","
                  + unitdef.getmultiplier()
                  + "),";
          Unit u = ud.createUnit(Unit.Kind.valueOf(unitdef.getkind()));
          u.setScale(unitdef.getscale());
          u.setExponent(unitdef.getexponent());
          u.setMultiplier(unitdef.getmultiplier());
        }
        // doc.getModel().addSpecies(sp) ;
        if (!unitdeflist.isEmpty()) {
          insertunits = insertunits.substring(0, insertunits.length() - 1);
          insertunits = insertunits + ';';
        }
      }
      if (!unitlist.isEmpty()) {
        insertunitdef = insertunitdef.substring(0, insertunitdef.length() - 1);
        insertunitdef = insertunitdef + ';';
      }

      ArrayList<reactionList> reactionlist = sql.getreactons(modelids.getId());

      if (!reactionlist.isEmpty())
        insertreaction =
            insertreaction
                + "\nInsert Into reaction (id,name, reversible,fast,model_id,compartment,annotation) Values";

      for (reactionList reaction : reactionlist) {
        insertreaction =
            insertreaction
                + "(\'"
                + reaction.getId()
                + "\',\'"
                + reaction.getName()
                + "\',"
                + reaction.getreversible()
                + ","
                + reaction.getfast()
                + ",\'"
                + modelids.getId()
                + "\',\'"
                + reaction.getcompartment()
                + "\',\'"
                + reaction.getannotation()
                + "\'),";
        Reaction rn = doc.getModel().createReaction(reaction.getId());
        rn.setName(reaction.getName());
        if (doc.getModel().getLevel() == 3) rn.setCompartment(reaction.getcompartment());
        rn.setFast(reaction.getfast());
        rn.setReversible(reaction.getreversible());
        if (!reaction.getannotation().equals("")) {
          Annotation annot = new Annotation(reaction.getannotation().toString());
          rn.setAnnotation(annot);
        }

        ArrayList<reactionList> reactantlist = sql.getreactants(reaction.getId());

        if (!reactantlist.isEmpty())
          insertreactant =
              insertreactant
                  + "\nInsert Into simplespeciesreference (reaction_id,species, sboTerm,stoichiometry,speciestype,constant) Values";
        for (reactionList reactant : reactantlist) {
          insertreactant =
              insertreactant
                  + "(\'"
                  + reaction.getId()
                  + "\',\'"
                  + reactant.getspecies()
                  + "\',\'"
                  + reactant.getsboTerm()
                  + "\',"
                  + reactant.getstoichometry()
                  + ","
                  + reactant.getconstant()
                  + ",\'reactants\'),";
          SpeciesReference rt = new SpeciesReference();
          rt.setName(reactant.getspecies());
          rt.setSpecies(reactant.getspecies());
          // rt.setSBOTerm(reactant.getsboTerm());
          rt.setStoichiometry(reactant.getstoichometry());
          //    rt.setConstant(reactant.getconstant());
          rn.addReactant(rt);
        }
        if (!reactantlist.isEmpty()) {
          insertreactant = insertreactant.substring(0, insertreactant.length() - 1);
          insertreactant = insertreactant + ';';
        }

        ArrayList<reactionList> productlist = sql.getproducts(reaction.getId());

        if (!productlist.isEmpty())
          insertproduct =
              insertproduct
                  + "\nInsert Into simplespeciesreference (reaction_id,species, sboTerm,stoichiometry,constant,speciestype) Values";
        for (reactionList product : productlist) {
          insertproduct =
              insertproduct
                  + "(\'"
                  + reaction.getId()
                  + "\',\'"
                  + product.getspecies()
                  + "\',\'"
                  + product.getsboTerm()
                  + "\',"
                  + product.getstoichometry()
                  + ","
                  + product.getconstant()
                  + ",\'products\'),";
          SpeciesReference pr = new SpeciesReference();
          pr.setName(product.getspecies());
          pr.setSpecies(product.getspecies());
          //   pr.setSBOTerm(product.getsboTerm());
          pr.setStoichiometry(product.getstoichometry());
          //    pr.setConstant(product.getconstant());
          rn.addProduct(pr);
        }
        if (!productlist.isEmpty()) {
          insertproduct = insertproduct.substring(0, insertproduct.length() - 1);
          insertproduct = insertproduct + ';';
        }

        ArrayList<reactionList> modifierlist = sql.getmodifiers(reaction.getId());

        if (!modifierlist.isEmpty())
          insertmodifier =
              insertmodifier
                  + "\nInsert Into modifierspeciesreference (reaction_id,species, sboTerm,speciestype) Values";
        for (reactionList modifier : modifierlist) {
          insertmodifier =
              insertmodifier
                  + "(\'"
                  + reaction.getId()
                  + "\',\'"
                  + modifier.getspecies()
                  + "\',\'"
                  + modifier.getsboTerm()
                  + "\',\'modifiers\'),";
          ModifierSpeciesReference m = new ModifierSpeciesReference();
          m.setName(modifier.getspecies());
          m.setSpecies(modifier.getspecies());
          //    m.setSBOTerm(modifier.getsboTerm());
          rn.addModifier(m);
        }
        if (!modifierlist.isEmpty()) {
          insertmodifier = insertmodifier.substring(0, insertmodifier.length() - 1);
          insertmodifier = insertmodifier + ';';
        }

        ArrayList<reactionList> klawlist = sql.getkineticlaws(reaction.getId());

        if (!klawlist.isEmpty())
          insertklaw =
              insertklaw + "\nInsert Into kineticlaw (reaction_id,kid, math,annotation) Values";
        for (reactionList klaw : klawlist) {
          insertklaw =
              insertklaw
                  + "(\'"
                  + reaction.getId()
                  + "\',\'"
                  + klaw.getId()
                  + "\',\'"
                  + klaw.getmath()
                  + "\',\'"
                  + klaw.getannotation()
                  + "\'),";
          KineticLaw kl = rn.createKineticLaw();
          try {
            math = ASTNode.parseFormula(klaw.getmath());
            kl.setMath(math);
            if (!klaw.getannotation().equals("")) {
              Annotation annot = new Annotation(klaw.getannotation().toString());
              kl.setAnnotation(annot);
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
        if (!klawlist.isEmpty()) {
          insertklaw = insertklaw.substring(0, insertklaw.length() - 1);
          insertklaw = insertklaw + ';';
        }
      }
      if (!reactionlist.isEmpty()) {
        insertreaction = insertreaction.substring(0, insertreaction.length() - 1);
        insertreaction = insertreaction + ';';
      }

      ArrayList<parameterList> paralist = sql.getparameters(modelids.getId());

      if (!paralist.isEmpty())
        insertparameter =
            insertparameter
                + "\nInsert Into parameter (id,name,value,units,constant,model_id) Values";

      for (parameterList para : paralist) {
        insertparameter =
            insertparameter
                + "(\'"
                + para.getId()
                + "\',\'"
                + para.getName()
                + "\',"
                + para.getvalue()
                + ","
                + para.getunits()
                + ","
                + para.getconstant()
                + ",\'"
                + modelids.getId()
                + "\'),";
        Parameter par = doc.getModel().createParameter(para.getId());
        par.setName(para.getId());
        par.setConstant(para.getconstant());
        par.setUnits(para.getunits());
        par.setValue(para.getvalue());
      }
      if (!paralist.isEmpty()) {
        insertparameter = insertparameter.substring(0, insertparameter.length() - 1);
        insertparameter = insertparameter + ';';
      }

      ArrayList<constraintList> conslist = sql.getconstraints(modelids.getId());

      if (!conslist.isEmpty())
        insertconstraint =
            insertconstraint + "\nInsert Into sbmlconstraint (math,message,model_id) Values";

      for (constraintList constraint : conslist) {
        insertconstraint =
            insertconstraint
                + "(\'"
                + constraint.getmath()
                + "\',\'"
                + constraint.getmessage()
                + "\',\'"
                + modelids.getId()
                + "\'),";
        Constraint cons = doc.getModel().createConstraint();
        try {
          math = ASTNode.parseFormula(constraint.getmath());
          cons.setMath(math);
          cons.setMessage(constraint.getmessage());
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      if (!conslist.isEmpty()) {
        insertconstraint = insertconstraint.substring(0, insertconstraint.length() - 1);
        insertconstraint = insertconstraint + ';';
      }

      ArrayList<eventsList> eventlist = sql.getevents(modelids.getId());

      if (!eventlist.isEmpty())
        insertevent =
            insertevent + "\nInsert Into event (id,name,UseValuesFromTriggerTime,model_id) Values";

      for (eventsList events : eventlist) {
        insertevent =
            insertevent
                + "(\'"
                + events.getId()
                + "\',\'"
                + events.getName()
                + "\',"
                + events.getuservalues()
                + ",\'"
                + modelids.getId()
                + "\'),";
        Event ev = doc.getModel().createEvent(events.getId());
        ev.setName(events.getName());
        // ev.setUseValuesFromTriggerTime(events.getuservalues());

        ArrayList<eventsList> triggerlist = sql.gettriggers(events.getId());

        if (!triggerlist.isEmpty())
          inserttrigger =
              inserttrigger
                  + "\nInsert Into sbmltrigger (event_id,initialvalue,persisent,math) Values";
        for (eventsList triggers : triggerlist) {
          Trigger tr = doc.getModel().createTrigger();
          try {
            math = ASTNode.parseFormula(triggers.getmath());
            tr.setMath(math);
            tr.setInitialValue(triggers.getinitialval());
            tr.setPersistent(triggers.getpersistent());
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
        if (!triggerlist.isEmpty()) {
          inserttrigger = inserttrigger.substring(0, insertmodel.length() - 1);
          inserttrigger = inserttrigger + ';';
        }

        ArrayList<eventsList> delaylist = sql.getdelays(events.getId());

        if (!delaylist.isEmpty())
          insertdelay = insertdelay + "\nInsert Into delay (event_id,math) Values";
        for (eventsList delays : delaylist) {
          Delay d = doc.getModel().createDelay();
          try {
            math = ASTNode.parseFormula(delays.getmath());
            d.setMath(math);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
        if (!delaylist.isEmpty()) {
          insertdelay = insertdelay.substring(0, insertdelay.length() - 1);
          insertdelay = insertdelay + ';';
        }

        ArrayList<eventsList> evasslist = sql.geteventassignments(events.getId());

        if (!evasslist.isEmpty())
          inserteventassign =
              inserteventassign + "\nInsert Into eventassignment (event_id,variable,math) Values";
        for (eventsList evassign : evasslist) {
          EventAssignment ea = doc.getModel().createEventAssignment();
          try {
            math = ASTNode.parseFormula(evassign.getmath());
            ea.setMath(math);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
        if (!evasslist.isEmpty()) {
          inserteventassign = inserteventassign.substring(0, inserteventassign.length() - 1);
          inserteventassign = inserteventassign + ';';
        }
      }
      if (!eventlist.isEmpty()) {
        insertevent = insertevent.substring(0, insertevent.length() - 1);
        insertevent = insertevent + ';';
      }

      ArrayList<ruleslist> rulelist = sql.getrules(modelids.getId());

      if (!rulelist.isEmpty())
        insertrules = insertrules + "\nInsert Into rules (id,math,ruletype,model_id) Values";
      for (ruleslist rules : rulelist) {
        insertrules =
            insertrules
                + "(\'"
                + rules.getId()
                + "\',\'"
                + rules.getmath()
                + "\',\'"
                + rules.getruletype()
                + "\',\'"
                + modelids.getId()
                + "\'),";
        if (rules.getruletype().equals("assignmentrule")) {
          Rule r = doc.getModel().createAssignmentRule();
          r.setMetaId(rules.getId());
          try {
            math = ASTNode.parseFormula(rules.getmath());
            r.setMath(math);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
      if (!rulelist.isEmpty()) {
        insertrules = insertrules.substring(0, insertrules.length() - 1);
        insertrules = insertrules + ';';
      }

      SBMLWriter writer = new SBMLWriter();
      try {
        String Path = filepath + modelids.getId() + ".xml";
        writer.write(doc, Path);

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(Path);
        Element root = document.getDocumentElement();
        Element newdataset = document.createElement("dataset");
        root.appendChild(newdataset);

        ArrayList<dataset> datasetlist = sql.getdataset(modelids.getId());
        for (dataset ds : datasetlist) {
          // System.out.println(ds.getexpcond());

          Element name = document.createElement("experimentalcondition");
          name.setAttribute("bioelement", ds.getbioel());
          name.setAttribute("name", ds.getName());
          name.setAttribute("descr", ds.getdescr());
          name.setAttribute("expcond", ds.getexpcond());
          name.setAttribute("value", String.valueOf(ds.getvalue()));
          name.setAttribute("type", ds.gettype());
          name.setAttribute("uri", ds.geturi());
          newdataset.appendChild(name);
        }

        root.appendChild(newdataset);
        DOMSource source = new DOMSource(document);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        StreamResult result = new StreamResult(filepath + modelids.getId() + "d.xml");
        transformer.transform(source, result);
        System.out.println(
            "Files : "
                + modelids.getId()
                + ".xml and "
                + modelids.getId()
                + "d.xml have been generated successfully !!!");

      } catch (Exception e) {
        e.printStackTrace();
      }

      insertstatement =
          insertstatement
              + "\n\n"
              + insertmodel
              + "\n"
              + insertspecies
              + "\n"
              + insertcompartment
              + "\n"
              + insertfunction;
      insertstatement =
          insertstatement
              + "\n"
              + insertparameter
              + "\n"
              + insertreaction
              + "\n"
              + insertreactant
              + "\n"
              + insertproduct;
      insertstatement =
          insertstatement
              + "\n"
              + insertmodifier
              + "\n"
              + insertklaw
              + "\n"
              + insertunitdef
              + "\n"
              + insertunits;
      insertstatement =
          insertstatement
              + "\n"
              + insertrules
              + "\n"
              + insertconstraint
              + "\n"
              + insertevent
              + "\n"
              + inserttrigger
              + "\n"
              + insertdelay
              + "\n"
              + inserteventassign;

      insertcompartment = "";
      insertmodel = "";
      insertspecies = "";

      // System.out.println("document : " + doc);
    }
    insertstatement = insertstatement + "\nUNLOCK TABLES;";
    Filedata = Filedata + "\n\n\n" + insertstatement;

    try {
      wrtireStringToFile(Filedata, filepath + "sbmldb.sql");
    } catch (IOException e) {
      e.printStackTrace();
    }
    // System.out.println(insertstatement);
  }
コード例 #23
0
  SimpleLiveLocalsAnalysis(UnitGraph g) {
    super(g);

    if (Options.v().time()) Timers.v().liveSetupTimer.start();

    emptySet = new ArraySparseSet();

    // Create kill sets.
    {
      unitToKillSet = new HashMap<Unit, FlowSet>(g.size() * 2 + 1, 0.7f);

      Iterator unitIt = g.iterator();

      while (unitIt.hasNext()) {
        Unit s = (Unit) unitIt.next();

        FlowSet killSet = emptySet.clone();

        Iterator boxIt = s.getDefBoxes().iterator();

        while (boxIt.hasNext()) {
          ValueBox box = (ValueBox) boxIt.next();

          if (box.getValue() instanceof Local) killSet.add(box.getValue(), killSet);
        }

        unitToKillSet.put(s, killSet);
      }
    }

    // Create generate sets
    {
      unitToGenerateSet = new HashMap<Unit, FlowSet>(g.size() * 2 + 1, 0.7f);

      Iterator unitIt = g.iterator();

      while (unitIt.hasNext()) {
        Unit s = (Unit) unitIt.next();

        FlowSet genSet = emptySet.clone();

        Iterator boxIt = s.getUseBoxes().iterator();

        while (boxIt.hasNext()) {
          ValueBox box = (ValueBox) boxIt.next();

          if (box.getValue() instanceof Local) genSet.add(box.getValue(), genSet);
        }

        unitToGenerateSet.put(s, genSet);
      }
    }

    if (Options.v().time()) Timers.v().liveSetupTimer.end();

    if (Options.v().time()) Timers.v().liveAnalysisTimer.start();

    doAnalysis();

    if (Options.v().time()) Timers.v().liveAnalysisTimer.end();
  }
コード例 #24
0
ファイル: TestCase.java プロジェクト: heavenlyhash/ahslib
  /**
   * By default, this will always attempt to call {@link System#exit(int)} at the end of running
   * tests, exiting with 0 if all tests pass, 4 if any units have failed, and 5 if any unit failed
   * catastrophically (i.e. the entire case was not completed). This behavior and/or those values
   * can be overridden by overriding the {@link #succeeded()}, {@link #failed()}, and {@link
   * #aborted()} methods, respectively.
   */
  public synchronized void run() {
    List<Unit> $units = getUnits(); // list is assumed immutable on pain of death or idiocy

    $numUnits = $units.size();
    $numUnitsRun = 0;
    $numUnitsPassed = 0;
    $numUnitsFailed = 0;

    for (int $i = 0; $i < $units.size(); $i++) {
      Unit $unit = $units.get($i);
      if ($unit == null) continue;

      try {
        resetFailures();

        $log.info("TEST UNIT " + $unit.getName() + " STARTING...");
        $numUnitsRun++;
        $unit.call();
        if ($unit.expectExceptionType() != null) {
          $numUnitsFailed++;
          $log.error("EXPECTED EXCEPTION; TEST CASE ABORTED.");
          aborted();
        }
        if ($unitFailures == 0) {
          $numUnitsPassed++;
          $log.info("TEST UNIT " + $unit.getName() + " PASSED SUCCESSFULLY!\n");
        } else {
          $numUnitsFailed++;
          $log.info(
              "TEST UNIT " + $unit.getName() + " FAILED (WITH " + $unitFailures + " FAILURES)!\n");
        }
      } catch (AssertionFatal $e) {
        $numUnitsFailed++;
        $log.error("FATAL EXCEPTION; TEST CASE ABORTED.", $e);
        aborted();
        break;
      } catch (AssertionFailed $e) {
        $numUnitsFailed++;
        $log.error("TEST UNIT " + $unit.getName() + " ABORTED.", $e);
      } catch (Throwable $e) {
        if ($unit.expectExceptionType() != null) {
          // some kind of exception was expected.
          if ($unit.expectExceptionType().isAssignableFrom($e.getClass())) {
            // and it was this kind that was expected, so this is good.
            $numUnitsPassed++;
            $unit.assertInstanceOf(
                $unit.expectExceptionType(), $e); // generates a normal confirmation message
            $log.info("TEST UNIT " + $unit.getName() + " PASSED SUCCESSFULLY!\n");
          } else {
            // and it wasn't this kind.  this represents fatal failure.
            $numUnitsFailed++;
            $log.error("FATAL EXCEPTION; TEST CASE ABORTED.", $e);
            aborted();
            break;
          }
        } else {
          // no exception was expected.  any exception represents fatal failure.
          $numUnitsFailed++;
          $log.error("FATAL EXCEPTION; TEST CASE ABORTED.", $e);
          aborted();
          break;
        }
      }
    }

    if ($numUnitsFailed > 0) failed();
    else succeeded();
  }
コード例 #25
0
  /**
   * This method pushes all newExpr down to be the stmt directly before every invoke of the init
   * only if they are in the types list
   */
  public void internalTransform(Body b, String phaseName, Map options) {
    JimpleBody body = (JimpleBody) b;

    if (Options.v().verbose())
      G.v().out.println("[" + body.getMethod().getName() + "] Folding Jimple constructors...");

    Chain units = body.getUnits();
    List<Unit> stmtList = new ArrayList<Unit>();
    stmtList.addAll(units);

    Iterator<Unit> it = stmtList.iterator();
    Iterator<Unit> nextStmtIt = stmtList.iterator();
    // start ahead one
    nextStmtIt.next();

    SmartLocalDefs localDefs = SmartLocalDefsPool.v().getSmartLocalDefsFor(body);
    UnitGraph graph = localDefs.getGraph();
    LocalUses localUses = new SimpleLocalUses(graph, localDefs);

    /* fold in NewExpr's with specialinvoke's */
    while (it.hasNext()) {
      Stmt s = (Stmt) it.next();

      if (!(s instanceof AssignStmt)) continue;

      /* this should be generalized to ArrayRefs */
      // only deal with stmts that are an local = newExpr
      Value lhs = ((AssignStmt) s).getLeftOp();
      if (!(lhs instanceof Local)) continue;

      Value rhs = ((AssignStmt) s).getRightOp();
      if (!(rhs instanceof NewExpr)) continue;

      // check if very next statement is invoke -->
      // this indicates there is no control flow between
      // new and invoke and should do nothing
      if (nextStmtIt.hasNext()) {
        Stmt next = (Stmt) nextStmtIt.next();
        if (next instanceof InvokeStmt) {
          InvokeStmt invoke = (InvokeStmt) next;

          if (invoke.getInvokeExpr() instanceof SpecialInvokeExpr) {
            SpecialInvokeExpr invokeExpr = (SpecialInvokeExpr) invoke.getInvokeExpr();
            if (invokeExpr.getBase() == lhs) {
              break;
            }
          }
        }
      }

      // check if new is in the types list - only process these
      if (!types.contains(((NewExpr) rhs).getType())) continue;

      List lu = localUses.getUsesOf(s);
      Iterator luIter = lu.iterator();
      boolean MadeNewInvokeExpr = false;

      while (luIter.hasNext()) {
        Unit use = ((UnitValueBoxPair) (luIter.next())).unit;
        if (!(use instanceof InvokeStmt)) continue;
        InvokeStmt is = (InvokeStmt) use;
        if (!(is.getInvokeExpr() instanceof SpecialInvokeExpr)
            || lhs != ((SpecialInvokeExpr) is.getInvokeExpr()).getBase()) continue;

        // make a new one here
        AssignStmt constructStmt =
            Jimple.v()
                .newAssignStmt(((DefinitionStmt) s).getLeftOp(), ((DefinitionStmt) s).getRightOp());
        constructStmt.setRightOp(Jimple.v().newNewExpr(((NewExpr) rhs).getBaseType()));
        MadeNewInvokeExpr = true;

        // redirect jumps
        use.redirectJumpsToThisTo(constructStmt);
        // insert new one here
        units.insertBefore(constructStmt, use);

        constructStmt.addTag(s.getTag("SourceLnPosTag"));
      }
      if (MadeNewInvokeExpr) {
        units.remove(s);
      }
    }
  }
コード例 #26
0
ファイル: ScalarMap.java プロジェクト: jon4than/visad
  /** set range used for linear map from Scalar to DisplayScalar values */
  private synchronized void setRange(
      DataShadow shadow, double low, double hi, boolean unit_flag, int remoteId)
      throws VisADException, RemoteException {
    int i = ScalarIndex;
    if (shadow != null) {
      // WLH - 23 Sept 99
      if (DisplayScalar.equals(Display.Latitude) || DisplayScalar.equals(Display.Longitude)) {
        Unit data_unit = (Scalar instanceof RealType) ? ((RealType) Scalar).getDefaultUnit() : null;
        Unit display_unit = DisplayScalar.getDefaultUnit();
        if (data_unit != null && display_unit != null && Unit.canConvert(data_unit, display_unit)) {
          dataRange[0] = data_unit.toThis(displayRange[0], display_unit);
          dataRange[1] = data_unit.toThis(displayRange[1], display_unit);
        } else {
          if (i < 0 || i >= shadow.ranges[0].length) return;
          dataRange[0] = shadow.ranges[0][i];
          dataRange[1] = shadow.ranges[1][i];
        }
      } else {
        if (i < 0 || i >= shadow.ranges[0].length) return;
        dataRange[0] = shadow.ranges[0][i];
        dataRange[1] = shadow.ranges[1][i];
      }
    } else if (unit_flag) {
      Unit data_unit = (Scalar instanceof RealType) ? ((RealType) Scalar).getDefaultUnit() : null;
      Unit display_unit = DisplayScalar.getDefaultUnit();
      if (data_unit == null || display_unit == null) {
        throw new UnitException("ScalarMap.setRangeByUnits: null Unit");
      }
      dataRange[0] = data_unit.toThis(displayRange[0], display_unit);
      dataRange[1] = data_unit.toThis(displayRange[1], display_unit);
      /*
      System.out.println("data_unit = " + data_unit + " display_unit = " + display_unit);
      System.out.println("dataRange = " + dataRange[0] + " " + dataRange[1] +
      " displayRange = " + displayRange[0] + " " + displayRange[1]);
      */
    } else {
      dataRange[0] = low;
      dataRange[1] = hi;
      // WLH 31 Aug 2000
      // manual range is in overrideUnit. so convert to Scalar default Unit
      if (overrideUnit != null) {
        dataRange[0] = (dataRange[0] - override_offset) / override_scale;
        dataRange[1] = (dataRange[1] - override_offset) / override_scale;
      }
    }
    /*
    if (shadow != null || remoteId != VisADEvent.LOCAL_SOURCE) {
      System.out.println(Scalar + " -> " + DisplayScalar + " range: " + dataRange[0] +
                         " to " + dataRange[1] + " " + display.getName());
    }
    */
    // at this point dataRange is range for Scalar default Unit
    //   even if (overrideUnit != null)
    // DRM 17 Feb 2006 - so set the defaultUnitRange to be these values.
    defaultUnitRange[0] = dataRange[0];
    defaultUnitRange[1] = dataRange[1];
    if (defaultUnitRange[0] == defaultUnitRange[1]) {
      double half = defaultUnitRange[0] / 2000.0;
      if (half < 0.5) half = 0.5;
      defaultUnitRange[0] -= half;
      defaultUnitRange[1] += half;
    }

    if (isScaled) {
      computeScaleAndOffset();
    } else { // if (!isScaled)
      if (dataRange[0] == Double.MAX_VALUE || dataRange[1] == -Double.MAX_VALUE) {
        dataRange[0] = Double.NaN;
        dataRange[1] = Double.NaN;
      }

      // WLH 31 Aug 2000
      if (overrideUnit != null) {
        // now convert dataRange to overrideUnit
        dataRange[0] = defaultUnitRange[0] * override_scale + override_offset;
        dataRange[1] = defaultUnitRange[1] * override_scale + override_offset;
      }
    }
    /*
    System.out.println(Scalar + " -> " + DisplayScalar + " range: " + dataRange[0] +
                       " to " + dataRange[1] + " scale: " + scale + " " + offset);
    */
    if (DisplayScalar.equals(Display.Animation) && shadow != null) {
      if (control != null && ((AnimationControl) control).getComputeSet()) {
        Set set = shadow.animationSampling;
        /* DRM: 04 Jan 2003
        if (set == null) {
          return;
        }
        */
        ((AnimationControl) control).setSet(set, true);
      }
    } else if (DisplayScalar.equals(Display.IsoContour)) {
      if (control != null) {

        // WLH 10 July 2002
        // don't set if application has called control.setLevels()
        float[] lowhibase = new float[3];
        boolean[] dashes = new boolean[1];

        boolean public_set = ((ContourControl) control).getPublicSet();
        if (!public_set) {
          boolean[] bvalues = new boolean[2];
          float[] values = new float[5];
          ((ContourControl) control).getMainContours(bvalues, values);
          if (shadow == null) {
            // don't set surface value for auto-scale
            values[0] = (float) dataRange[0]; // surfaceValue
          }
          // CTR: 29 Jul 1999: interval should never be zero
          float f = (float) (dataRange[1] - dataRange[0]) / 10.0f;
          if (f != 0.0f) values[1] = f; // contourInterval
          values[2] = (float) dataRange[0]; // lowLimit
          values[3] = (float) dataRange[1]; // hiLimit
          values[4] = (float) dataRange[0]; // base
          ((ContourControl) control).setMainContours(bvalues, values, true, true);
        }
      }
    } else if (DisplayScalar.equals(Display.XAxis)
        || DisplayScalar.equals(Display.YAxis)
        || DisplayScalar.equals(Display.ZAxis)) {
      if (dataRange[0] != Double.MAX_VALUE
          && dataRange[1] != -Double.MAX_VALUE
          && dataRange[0] == dataRange[0]
          && dataRange[1] == dataRange[1]
          && dataRange[0] != dataRange[1]
          && scale == scale
          && offset == offset) {
        if (display != null) {
          makeScale();
        } else {
          scale_flag = true;
        }
        back_scale_flag = true;
      }
    }

    if (dataRange[0] == dataRange[0] && dataRange[1] == dataRange[1] && ListenerVector != null) {
      ScalarMapEvent evt;
      evt =
          new ScalarMapEvent(
              this, (shadow == null ? ScalarMapEvent.MANUAL : ScalarMapEvent.AUTO_SCALE), remoteId);
      Vector listeners_clone = null;
      synchronized (ListenerVector) {
        listeners_clone = (Vector) ListenerVector.clone();
      }
      Enumeration listeners = listeners_clone.elements();
      while (listeners.hasMoreElements()) {
        ScalarMapListener listener = (ScalarMapListener) listeners.nextElement();
        listener.mapChanged(evt);
      }
    }
  }
コード例 #27
0
ファイル: Printer.java プロジェクト: safdariqbal/soot
  /** Prints the given <code>JimpleBody</code> to the specified <code>PrintWriter</code>. */
  private void printStatementsInBody(
      Body body, java.io.PrintWriter out, LabeledUnitPrinter up, UnitGraph unitGraph) {
    Chain units = body.getUnits();
    Iterator unitIt = units.iterator();
    Unit currentStmt = null, previousStmt;

    while (unitIt.hasNext()) {

      previousStmt = currentStmt;
      currentStmt = (Unit) unitIt.next();

      // Print appropriate header.
      {
        // Put an empty line if the previous node was a branch node, the current node is a join node
        //   or the previous statement does not have body statement as a successor, or if
        //   body statement has a label on it

        if (currentStmt != units.getFirst()) {
          if (unitGraph.getSuccsOf(previousStmt).size() != 1
              || unitGraph.getPredsOf(currentStmt).size() != 1
              || up.labels().containsKey(currentStmt)) {
            up.newline();
          } else {
            // Or if the previous node does not have body statement as a successor.

            List succs = unitGraph.getSuccsOf(previousStmt);

            if (succs.get(0) != currentStmt) {
              up.newline();
            }
          }
        }

        if (up.labels().containsKey(currentStmt)) {
          up.unitRef(currentStmt, true);
          up.literal(":");
          up.newline();
        }

        if (up.references().containsKey(currentStmt)) {
          up.unitRef(currentStmt, false);
        }
      }

      up.startUnit(currentStmt);
      currentStmt.toString(up);
      up.endUnit(currentStmt);

      up.literal(";");
      up.newline();

      // only print them if not generating attributes files
      // because they mess up line number
      // if (!addJimpleLn()) {
      if (Options.v().print_tags_in_output()) {
        Iterator tagIterator = currentStmt.getTags().iterator();
        while (tagIterator.hasNext()) {
          Tag t = (Tag) tagIterator.next();
          up.noIndent();
          up.literal("/*");
          up.literal(t.toString());
          up.literal("*/");
          up.newline();
        }
        /*Iterator udIt = currentStmt.getUseAndDefBoxes().iterator();
        while (udIt.hasNext()) {
            ValueBox temp = (ValueBox)udIt.next();
            Iterator vbtags = temp.getTags().iterator();
            while (vbtags.hasNext()) {
                Tag t = (Tag) vbtags.next();
                up.noIndent();
                up.literal("VB Tag: "+t.toString());
                up.newline();
            }
        }*/
      }
    }

    out.print(up.toString());
    if (addJimpleLn()) {
      setJimpleLnNum(up.getPositionTagger().getEndLn());
    }

    // Print out exceptions
    {
      Iterator trapIt = body.getTraps().iterator();

      if (trapIt.hasNext()) {
        out.println();
        incJimpleLnNum();
      }

      while (trapIt.hasNext()) {
        Trap trap = (Trap) trapIt.next();

        out.println(
            "        catch "
                + Scene.v().quotedNameOf(trap.getException().getName())
                + " from "
                + up.labels().get(trap.getBeginUnit())
                + " to "
                + up.labels().get(trap.getEndUnit())
                + " with "
                + up.labels().get(trap.getHandlerUnit())
                + ";");

        incJimpleLnNum();
      }
    }
  }
コード例 #28
0
  public synchronized void drag_direct(VisADRay ray, boolean first, int mouseModifiers) {
    if (barbValues == null || ref == null || shadow == null) return;

    if (first) {
      stop = false;
    } else {
      if (stop) return;
    }

    // modify direction if mshift != 0
    // modify speed if mctrl != 0
    // modify speed and direction if neither
    int mshift = mouseModifiers & InputEvent.SHIFT_MASK;
    int mctrl = mouseModifiers & InputEvent.CTRL_MASK;

    float o_x = (float) ray.position[0];
    float o_y = (float) ray.position[1];
    float o_z = (float) ray.position[2];
    float d_x = (float) ray.vector[0];
    float d_y = (float) ray.vector[1];
    float d_z = (float) ray.vector[2];

    if (pickCrawlToCursor) {
      if (first) {
        offset_count = OFFSET_COUNT_INIT;
      } else {
        if (offset_count > 0) offset_count--;
      }
      if (offset_count > 0) {
        float mult = ((float) offset_count) / ((float) OFFSET_COUNT_INIT);
        o_x += mult * offsetx;
        o_y += mult * offsety;
        o_z += mult * offsetz;
      }
    }

    if (first || refirst) {
      point_x = barbValues[2];
      point_y = barbValues[3];
      point_z = 0.0f;
      line_x = 0.0f;
      line_y = 0.0f;
      line_z = 1.0f; // lineAxis == 2 in DataRenderer.drag_direct
    } // end if (first || refirst)

    float[] x = new float[3]; // x marks the spot
    // DirectManifoldDimension = 2
    // intersect ray with plane
    float dot = (point_x - o_x) * line_x + (point_y - o_y) * line_y + (point_z - o_z) * line_z;
    float dot2 = d_x * line_x + d_y * line_y + d_z * line_z;
    if (dot2 == 0.0) return;
    dot = dot / dot2;
    // x is intersection
    x[0] = o_x + dot * d_x;
    x[1] = o_y + dot * d_y;
    x[2] = o_z + dot * d_z;
    /*
    System.out.println("x = " + x[0] + " " + x[1] + " " + x[2]);
    */
    try {

      Tuple data = (Tuple) link.getData();
      int n = ((TupleType) data.getType()).getNumberOfRealComponents();
      Real[] reals = new Real[n];

      int k = 0;
      int m = data.getDimension();
      for (int i = 0; i < m; i++) {
        Data component = data.getComponent(i);
        if (component instanceof Real) {
          reals[k++] = (Real) component;
        } else if (component instanceof RealTuple) {
          for (int j = 0; j < ((RealTuple) component).getDimension(); j++) {
            reals[k++] = (Real) ((RealTuple) component).getComponent(j);
          }
        }
      }

      if (first || refirst) {
        // get first Data flow vector
        for (int i = 0; i < 3; i++) {
          int j = flowToComponent[i];
          data_flow[i] = (j >= 0) ? (float) reals[j].getValue() : 0.0f;
        }

        if (coord != null) {
          float[][] ds = {{data_flow[0]}, {data_flow[1]}, {data_flow[2]}};
          ds = coord.toReference(ds);
          data_flow[0] = ds[0][0];
          data_flow[1] = ds[1][0];
          data_flow[2] = ds[2][0];
        }

        data_speed =
            (float)
                Math.sqrt(
                    data_flow[0] * data_flow[0]
                        + data_flow[1] * data_flow[1]
                        + data_flow[2] * data_flow[2]);
        float barb0 = barbValues[2] - barbValues[0];
        float barb1 = barbValues[3] - barbValues[1];
        /*
        System.out.println("data_flow = " + data_flow[0] + " " + data_flow[1] +
                           " " + data_flow[2]);
        System.out.println("barbValues = " + barbValues[0] + " " + barbValues[1] +
                           "   " + barbValues[2] + " " + barbValues[3]);
        System.out.println("data_speed = " + data_speed);
        */
      } // end if (first || refirst)

      // convert x to a flow vector, and from spatial to earth
      if (getRealVectorTypes(which_barb) instanceof EarthVectorType) {
        // don't worry about vector magnitude -
        // data_speed & display_speed take care of that
        float eps = 0.0001f; // estimate derivative with a little vector
        float[][] spatial_locs = {
          {barbValues[0], barbValues[0] + eps * (x[0] - barbValues[0])},
          {barbValues[1], barbValues[1] + eps * (x[1] - barbValues[1])},
          {0.0f, 0.0f}
        };
        /*
        System.out.println("spatial_locs = " + spatial_locs[0][0] + " " +
                           spatial_locs[0][1] + " " + spatial_locs[1][0] + " " +
                           spatial_locs[1][1]);
        */
        float[][] earth_locs = spatialToEarth(spatial_locs);
        // WLH - 18 Aug 99
        if (earth_locs == null) return;
        /*
        System.out.println("earth_locs = " + earth_locs[0][0] + " " +
                           earth_locs[0][1] + " " + earth_locs[1][0] + " " +
                           earth_locs[1][1]);
        */
        x[2] = 0.0f;
        x[0] =
            (earth_locs[1][1] - earth_locs[1][0])
                * ((float) Math.cos(Data.DEGREES_TO_RADIANS * earth_locs[0][0]));
        x[1] = earth_locs[0][1] - earth_locs[0][0];
        /*
        System.out.println("x = " + x[0] + " " + x[1] + " " + x[2]);
        */
      } else { // if (!(getRealVectorTypes(which_barb) instanceof EarthVectorType))
        // convert x to vector
        x[0] -= barbValues[0];
        x[1] -= barbValues[1];

        // adjust for spatial map scalings but don't worry about vector
        // magnitude - data_speed & display_speed take care of that
        // also, spatial is Cartesian
        double[] ranges = getRanges();
        for (int i = 0; i < 3; i++) {
          x[i] /= ranges[i];
        }
        /*
        System.out.println("ranges = " + ranges[0] + " " + ranges[1] +
                           " " + ranges[2]);
        System.out.println("x = " + x[0] + " " + x[1] + " " + x[2]);
        */
      }

      // WLH 6 August 99
      x[0] = -x[0];
      x[1] = -x[1];
      x[2] = -x[2];

      /* may need to do this for performance
            float[] xx = {x[0], x[1], x[2]};
            addPoint(xx);
      */

      float x_speed = (float) Math.sqrt(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]);
      /* WLH 16 April 2002 - from Ken
            if (x_speed < 0.000001f) x_speed = 0.000001f;
      */
      if (x_speed < 0.01f) x_speed = 0.01f;
      if (first || refirst) {
        display_speed = x_speed;
      }
      refirst = false;

      if (mshift != 0) {
        // only modify data_flow direction
        float ratio = data_speed / x_speed;
        x[0] *= ratio;
        x[1] *= ratio;
        x[2] *= ratio;
        /*
        System.out.println("direction, ratio = " + ratio + " " +
                           data_speed + " " + x_speed);
        System.out.println("x = " + x[0] + " " + x[1] + " " + x[2]);
        */
      } else if (mctrl != 0) {
        // only modify data_flow speed
        float ratio = x_speed / display_speed;
        if (data_speed < EPS) {
          data_flow[0] = 2.0f * EPS;
          refirst = true;
        }
        x[0] = ratio * data_flow[0];
        x[1] = ratio * data_flow[1];
        x[2] = ratio * data_flow[2];
        /*
        System.out.println("speed, ratio = " + ratio + " " +
                           x_speed + " " + display_speed);
        System.out.println("x = " + x[0] + " " + x[1] + " " + x[2]);
        */
      } else {
        // modify data_flow speed and direction
        float ratio = data_speed / display_speed;
        /*
        System.out.println("data_speed = " + data_speed +
                           " display_speed = " + display_speed +
                           " ratio = " + ratio + " EPS = " + EPS);
        System.out.println("x = " + x[0] + " " + x[1] +" " + x[2] +
                           " x_speed = " + x_speed);
          data_speed = 21.213203 display_speed = 0.01 ratio = 2121.3203 EPS = 0.2
          x = 1.6170928E-4 1.6021729E-4 -0.0 x_speed = 0.01
          wind = (0.3430372, 0.33987218) at (-35.0, 5.0)
        */
        if (data_speed < EPS) {
          data_flow[0] = 2.0f * EPS;
          x[0] = data_flow[0];
          x[1] = data_flow[1];
          x[2] = data_flow[2];
          refirst = true;
        } else {
          x[0] *= ratio;
          x[1] *= ratio;
          x[2] *= ratio;
        }
      }

      if (coord != null) {
        float[][] xs = {{x[0]}, {x[1]}, {x[2]}};
        xs = coord.fromReference(xs);
        x[0] = xs[0][0];
        x[1] = xs[1][0];
        x[2] = xs[2][0];
      }

      // now replace flow values
      Vector vect = new Vector();
      for (int i = 0; i < 3; i++) {
        int j = flowToComponent[i];
        if (j >= 0) {
          RealType rtype = (RealType) reals[j].getType();
          reals[j] = new Real(rtype, (double) x[i], rtype.getDefaultUnit(), null);

          // WLH 31 Aug 2000
          Real r = reals[j];
          Unit overrideUnit = null;
          if (directMap[i] != null) {
            overrideUnit = directMap[i].getOverrideUnit();
          }
          Unit rtunit = rtype.getDefaultUnit();
          // units not part of Time string
          if (overrideUnit != null
              && !overrideUnit.equals(rtunit)
              && !RealType.Time.equals(rtype)) {
            double d = (float) overrideUnit.toThis((double) x[0], rtunit);
            r = new Real(rtype, d, overrideUnit);
            String valueString = r.toValueString();
            vect.addElement(rtype.getName() + " = " + valueString);
          } else {
            // create location string
            vect.addElement(rtype.getName() + " = " + x[i]);
          }
        }
      }
      getDisplayRenderer().setCursorStringVector(vect);

      Data newData = null;
      // now build new RealTuple or Flat Tuple
      if (data instanceof RealTuple) {
        newData =
            new RealTuple(
                ((RealTupleType) data.getType()), reals, ((RealTuple) data).getCoordinateSystem());
      } else {
        Data[] new_components = new Data[m];
        k = 0;
        for (int i = 0; i < m; i++) {
          Data component = data.getComponent(i);
          if (component instanceof Real) {
            new_components[i] = reals[k++];
          } else if (component instanceof RealTuple) {
            Real[] sub_reals = new Real[((RealTuple) component).getDimension()];
            for (int j = 0; j < ((RealTuple) component).getDimension(); j++) {
              sub_reals[j] = reals[k++];
            }
            new_components[i] =
                new RealTuple(
                    ((RealTupleType) component.getType()),
                    sub_reals,
                    ((RealTuple) component).getCoordinateSystem());
          }
        }
        newData = new Tuple(new_components, false);
      }
      ref.setData(newData);
    } catch (VisADException e) {
      // do nothing
      System.out.println("drag_direct " + e);
      e.printStackTrace();
    } catch (RemoteException e) {
      // do nothing
      System.out.println("drag_direct " + e);
      e.printStackTrace();
    }
  }