public static void main(String[] args) {
    int km, litros, kmTotal, litrosTotal;
    Scanner input = new Scanner(System.in);
    Func f = new Func();
    km = 0;
    litros = 0;
    kmTotal = 0;
    litrosTotal = 0;

    do {
      System.out.print("Digite a quilometragem (-1 para sair): ");
      km = input.nextInt();
      if (km >= 0) {
        System.out.print("Digite os litros consumidos: ");
        litros = input.nextInt();
        System.out.println("Consumo: ");
        f.calcula(km, litros);
        kmTotal += km;
        litrosTotal += litros;
      }
    } while (km >= 0);

    System.out.printf("Total de KM: %d\nTotal de Litros: %d\n", kmTotal, litrosTotal);
    System.out.println("FIM!");
  }
 public String toString() {
   return super.toString()
       + Func.toStringRow("Destination", dest)
       + Func.toStringRow("Dest. IP", destIp.getHostAddress())
       + Func.toStringRow("Dest. port", destPort)
       + Func.toStringRow("CCid", cCid);
 }
Exemple #3
0
  public void applyPickColors() {
    float[] nodeHSV = new float[3];
    nodeHSV = Func.RGBtoHSV(app.pickGradEnd);
    float[] pickHSV = new float[3];
    pickHSV = Func.RGBtoHSV(app.pickGradStart);

    for (Node n : net.nNodes) {
      //	calculate hue based on network distance from selected node
      float max = app.getPickdepth();
      float grad = n.pickDistance / max;
      float hue = pickHSV[0] + grad * (nodeHSV[0] - pickHSV[0]);
      float[] result = new float[3];
      result = Func.HSVtoRGB(hue, nodeHSV[1], nodeHSV[2], 0.8f);
      //	set the color of the selection frame
      float alpha = Math.max(0f, Math.min(1, max - n.pickDistance + 1));
      result[3] = alpha;
      n.setPickColor(result);

      //			set the alpha of the node color	based on selection
      if (app.fadeNodes && !n.rollover && !n.isFrame()) n.setAlpha(Math.max(0.05f, alpha));
      else n.setAlpha(app.nodeColor[3]);

      n.genColorFromAtt();
    }
  }
Exemple #4
0
 public void layoutRandomize() {
   for (Node n : net.fNodes) {
     float randPos = (float) Math.sqrt(net.fNodes.size()) * 50f + 50f;
     n.pos.setXYZ(
         Func.rnd(-randPos, randPos), Func.rnd(-randPos, randPos), Func.rnd(-randPos, randPos));
   }
 }
Exemple #5
0
  @Override
  public void createPartControl(Composite parent) {
    this.parent = parent;
    Model m = new Model();
    parent.setLayout(new GridLayout(2, false));

    Func func = new Func(m, parent, this);
    func.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 2));

    Show view = new Show(m, parent);
    view.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    Info text = new Info(m, parent);
    text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    m.addObserver(view);
    m.addObserver(func);
    m.addObserver(text);
    m.setNotified();
    parent.layout();

    PlatformUI.getWorkbench()
        .getHelpSystem()
        .setHelp(parent, ACOPlugin.PLUGIN_ID + ".view"); // $NON-NLS-1$
  }
Exemple #6
0
 private NumValue unary(NumValue[] params) {
   switch (m_uop) {
     case UMINUS:
       return m_right.evaluate(params).neg();
     case NOT:
       return m_right.evaluate(params).not();
     default:
       return null;
   }
 }
Exemple #7
0
    @Override
    public void map(WritableComparable docID, Text docContents, Context context)
        throws IOException, InterruptedException {

      Matcher matcher = WORD_PATTERN.matcher(docContents.toString());
      Func func = this.funcFromNum(funcNum);
      String w = new String();
      String v = new String();
      ArrayList<Integer> tarIndice = new ArrayList<Integer>();

      double fScore, distance;

      int counter = 0;
      while (matcher.find()) {
        docC.put(new Integer(counter), matcher.group());
        counter++;
      }

      for (int i = 0; i < counter; i++) {

        for (int j = 0; j < n; j++) {
          if ((i + j) < counter) {
            w = w + " " + docC.get(new Integer(i + j));
          } else {
            break;
          }
        }
        w = w.toLowerCase().substring(1);
        if (w.equals(targetGram)) {
          tarIndice.add(new Integer(i));
        }
        w = new String();
      }

      for (int i = 0; i < counter; i++) {

        for (int j = 0; j < n; j++) {
          if ((i + j) < counter) {
            v = v + " " + docC.get(new Integer(i + j));
          } else {
            break;
          }
        }
        v = v.toLowerCase().substring(1);

        if (!v.equals(targetGram)) {
          word.set(v);
          distance = this.distance(tarIndice, i);
          fScore = func.f(distance);
          fSText.set(Double.toString(fScore) + " 1");
          context.write(word, fSText);
        }
        v = new String();
      }
    }
Exemple #8
0
  /**
   * calculate node color based on gradient and level
   *
   * @param level
   * @param m
   */
  void setNodeColor(int level, Node m) {
    float[] nodeHSV = new float[3];
    nodeHSV = Func.RGBtoHSV(app.pickGradEnd);
    float[] pickHSV = new float[3];
    pickHSV = Func.RGBtoHSV(app.pickGradStart);

    if (m.hasAttribute("color")) m.setColor(Func.parseColorInt(m.getAttribute("color"), 16));
    else {
      float[] color = Func.colorGrad(level, nodeHSV, pickHSV);
      m.setColor(color);
    }
  }
Exemple #9
0
 public Func shift(int shift) {
   switch (m_type) {
     case VAR:
       return new Func(m_index + shift);
     case CONST:
       return this;
     case UNOP:
       return new Func(m_uop, m_right.shift(shift));
     case BINOP:
       return new Func(m_left.shift(shift), m_bop, m_right.shift(shift));
     default:
       return null;
   }
 }
Exemple #10
0
 public Func nest(Func[] params) {
   switch (m_type) {
     case VAR:
       return params[m_index].copy();
     case CONST:
       return this;
     case UNOP:
       return new Func(m_uop, m_right.nest(params));
     case BINOP:
       return new Func(m_left.nest(params), m_bop, m_right.nest(params));
     default:
       return null;
   }
 }
Exemple #11
0
 public String toString() {
   switch (m_type) {
     case VAR:
       return "in[" + m_index + "]";
     case CONST:
       return m_value.toString();
     case UNOP:
       return uopString() + "(" + m_right.toString() + ")";
     case BINOP:
       return "(" + m_left.toString() + " " + bopString() + " " + m_right.toString() + ")";
     default:
       return "";
   }
 }
 public Func getFunc(Env env, Object owner) {
   if (attachCond != null && !attachCond.test(env)) {
     return null;
   }
   try {
     Func f = (Func) constructor.newInstance(stat, order, owner, lambda);
     if (applayCond != null) {
       f.setCondition(applayCond);
     }
     return f;
   } catch (Exception e) {
     _log.log(Level.ERROR, "", e);
     return null;
   }
 }
 public static <I, O> List<O> map(Iterable<I> items, Func<? super I, O> func) {
   List<O> result = new ArrayList<O>();
   for (I item : items) {
     O output = func.eval(item);
     result.add(output);
   }
   return result;
 }
Exemple #14
0
 /** {@inheritDoc} */
 @Override
 public List<? extends Browsable> getSubnodes() {
   if (args.size() == 0) {
     Expr b = fun.getBody();
     return Util.asList(make(b.pos(), b.span(), b.getHTML(), b.getSubnodes()));
   }
   Pos p = pos;
   if (p == Pos.UNKNOWN) p = span();
   Browsable f =
       make(p, p, (fun.isPred ? "<b>pred</b> " : "<b>fun</b> ") + fun.label, fun.getSubnodes());
   Browsable a =
       make(
           span(),
           span(),
           "<b>" + args.size() + " argument" + (args.size() == 1 ? "</b>" : "s</b>"),
           args);
   return Util.asList(f, a);
 }
Exemple #15
0
 public void layoutNodePosPlace() {
   for (Node n : net.fNodes) {
     float randPos = net.fNodes.size() * 10f + 50f;
     n.pos.setXYZ(
         Integer.MAX_VALUE / (float) n.getId(),
         Integer.MAX_VALUE / ((float) String.valueOf(n.getId() + 3).hashCode()),
         Func.rnd(-randPos, randPos));
   }
 }
Exemple #16
0
 @Override
 public final <E> E read(Func<InputStream, E> readCallback) {
   final InputStream in = read();
   try {
     final E result = readCallback.eval(in);
     return result;
   } catch (Exception e) {
     throw new ResourceException(this, "Error occurred in read callback", e);
   } finally {
     FileHelper.safeClose(in);
   }
 }
 public Func getFunc(Env env, Object owner) {
   if ((attachCond != null) && !attachCond.test(env)) {
     return null;
   }
   try {
     Func f = (Func) constructor.newInstance(stat, order, owner, lambda);
     if (applayCond != null) {
       f.setCondition(applayCond);
     }
     return f;
   } catch (IllegalAccessException e) {
     _log.log(Level.WARNING, "", e);
     return null;
   } catch (InstantiationException e) {
     _log.log(Level.WARNING, "", e);
     return null;
   } catch (InvocationTargetException e) {
     _log.log(Level.WARNING, "", e);
     return null;
   }
 }
 static int apply(Func f, int x)
       // @ requires [_]Func(f, ?level) &*& [2]call_perm(level);
       // @ ensures true;
       // @ terminates;
     {
   // @ open Func(_, _);
   // @ assert [_]f.valid(?level0);
   // @ call_perm_weaken(2, level0);
   // @ f.getClass_le_level();
   // @ consume_call_perm_for(f.getClass());
   return f.apply(x);
 }
Exemple #19
0
  private void makeReg() {
    slope = Func.slope(data.get(dataType), x, y);
    slopeField.setValue(slope[0]);
    slopeErrField.setValue(slope[1]);
    rField.setValue(slope[2]);
    //		Setting.getElement("/bat/isotope/calc/bg/factor").setText(((Double)slope[0]).toString());
    //		Setting.getElement("/bat/isotope/calc/bg/error").setText(((Double)slope[1]).toString());
    //		for (int i=0;i<data.corrList.size();i++) {
    //			data.corrList.get(i).isoFact=(Double)slope[0];
    //			data.corrList.get(i).isoErr=(Double)slope[1];
    //		}

  }
 /**
  * Applies a comprehension function to each element of a given ArrayList and returns a new
  * ArrayList (with those modification) as a result. The given input ArrayList is not modified. If
  * the comprehension function returns null the according list element is not included in the
  * returned ArrayList. This is the ArrayList version of @link map(List...)
  *
  * @param in input ArrayList
  * @param f comprehension function
  * @return new list that is a comprehension of in (the input ArrayList)
  */
 public static <In, Out> ArrayList<Out> map(ArrayList<In> in, Func<In, Out> f) {
   if (in != null && f != null) {
     ArrayList<Out> out = new ArrayList<Out>(in.size());
     for (int i = 0; i < in.size(); i++) {
       Out o = f.apply(in.get(i));
       if (o != null) {
         out.add(o);
       }
     }
     return out;
   }
   return null;
 }
 /**
  * Applies a comprehension function to each element of a given set and returns a new set (with
  * those modifications) as a result. The given input set is not modified. If the comprehension
  * function returns null the according set element is not included in the returned set.
  *
  * @param in input set
  * @param f comprehension function
  * @return new list that is a comprehension of in (the input set)
  */
 public static <In, Out> Set<Out> map(Set<In> in, Func<In, Out> f) {
   if (in != null) {
     Set<Out> out = new HashSet<Out>(in.size());
     for (In inObj : in) {
       Out o = f.apply(inObj);
       if (o != null) {
         out.add(o);
       }
     }
     return out;
   }
   return null;
 }
  @Override
  public String toString() {
    StringBuilder buf = new StringBuilder();

    buf.append("import java.util.concurrent.Callable;\n");
    buf.append("import java.util.concurrent.ExecutionException;\n");
    buf.append("import java.util.concurrent.ExecutorService;\n");
    buf.append("import java.util.concurrent.Executors;\n");
    buf.append("import java.rmi.*;\n");
    buf.append("import java.rmi.registry.*;\n");
    Iterator<Func> FuncIterator = userDefinedFuncs.iterator();
    while (FuncIterator.hasNext()) {
      Func f = FuncIterator.next();
      if (f != null) buf.append(f.toString());
    }
    buf.append("public class Generated {\n");
    buf.append("public static ExecutorService service = Executors.newCachedThreadPool();\n");
    buf.append("public static void main(String[] args) throws Exception ");
    buf.append(mainFunction.body.toString());
    buf.append("\n}");

    return buf.toString();
  }
 /**
  * Decomposes a given collection containing nested collections and iterates over the elements
  * which can be manipulated with a user- specified function f.
  *
  * @param in Collection containing collection (i.e. Collection<Collection<type>>)
  * @param f function to be applied to individual elements
  * @return collection of all individual elements (if f returns non-null for individual element,
  *     else this element is excluded)
  */
 public static <In, Out> Collection<Out> decomposeCollectionToElements(
     Collection<HashSet<In>> in, Func<In, Out> f) {
   if (in != null) {
     Set<Out> out = new HashSet<Out>(in.size());
     for (Collection<In> inCol : in) {
       for (In inObj : inCol) {
         Out o = f.apply(inObj);
         if (o != null) {
           out.add(o);
         }
       }
     }
     return out;
   }
   return null;
 }
Exemple #24
0
  private JFreeChart createChart(XYDataset dataset) {
    JFreeChart chart =
        ChartFactory.createXYLineChart(
            Setting.getString("/bat/isotope/graph/bg/title"), // chart title
            Setting.getString("/bat/isotope/graph/bg/x_axes"), // x axis label
            Setting.getString("/bat/isotope/graph/bg/y_axes"), // y axis label
            dataset, // data
            PlotOrientation.VERTICAL,
            false, // include legend
            true, // tooltips
            false // urls
            );

    chart.setBackgroundPaint(Setting.getColor("/bat/isotope/graph/background"));
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Setting.getColor("/bat/isotope/graph/background"));
    plot.setRangeGridlinePaint(Setting.getColor("/bat/isotope/graph/background"));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    plot.getDomainAxis().getUpperBound();
    plot.setDataset(1, Func.xYSlope(slope, plot.getDomainAxis().getUpperBound()));

    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setBaseSeriesVisible(true);
    renderer.setBaseShapesFilled(true);
    renderer.setBaseShapesVisible(true);
    renderer.setDrawOutlines(true);
    renderer.setSeriesItemLabelFont(0, fText);
    renderer.setBaseItemLabelFont(fText);
    chart.getTitle().setFont(fTitel);

    renderer.setSeriesLinesVisible(0, true);
    renderer.setSeriesLinesVisible(1, true);
    renderer.setSeriesShapesVisible(1, true);

    NumberAxis axis = (NumberAxis) plot.getRangeAxis();
    axis.setAutoRangeIncludesZero(true);
    axis.setLabelFont(fAxes);
    plot.getDomainAxis().setLabelFont(fAxes);

    return chart;
  }
Exemple #25
0
 public void fieldChange() {
   Double value = (Double) textField.getValue();
   log.debug("Changed isoFact to: " + value);
   if (value.isInfinite() || value.isNaN()) {
     value = 0.0;
   }
   Setting.getElement("/bat/isotope/calc/bg/factor").setText(value.toString());
   for (int i = 0; i < data.corrList.size(); i++) {
     data.corrList.get(i).isoFact = value;
   }
   data.calcAll();
   makeReg();
   dataSet = Func.getXY(data.get(dataType), null, x, y, x_multi, y_multi);
   chart.getXYPlot().setDataset(0, dataSet);
   log.debug(
       "Isobar correction factor set to: "
           + value
           + "-"
           + Setting.getDouble("/bat/isotope/calc/bg/factor"));
 }
 /**
  * Applies a comprehension function to each element of a given list and manipulates the list
  * according to this function. If the comprehension function returns null, the element is removed
  * from the list.
  *
  * @param list input list
  * @param f comprehension function
  */
 public static <T> void applyToListInPlace(List<T> list, Func<T, T> f) {
   if (list != null && f != null) {
     for (int i = 0; i < list.size(); i++) {
       T o = f.apply(list.get(i));
       if (o != null) {
         list.set(i, o);
       } else {
         list.remove(i);
         i--;
       }
     }
   }
   /*ListIterator<T> itr = list.listIterator();
   while (itr.hasNext()) {
       T output = f.apply(itr.next());
       if(output != null){
       	itr.set(output);
       } else {
       	itr.remove();
       }
   }*/
 }
Exemple #27
0
 /** {@inheritDoc} */
 @Override
 public Expr resolve(Type t, Collection<ErrorWarning> warns) {
   if (errors.size() > 0) return this;
   TempList<Expr> args = new TempList<Expr>(this.args.size());
   boolean changed = false;
   for (int i = 0; i < this.args.size(); i++) {
     Type p = fun.get(i).type;
     Expr x = this.args.get(i);
     Expr y =
         x.resolve(p, warns)
             .typecheck_as_set(); // Use the function's param type to narrow down the choices
     if (x != y) changed = true;
     args.add(y);
     // if (warns!=null && Version.experimental && !y.type.isSubtypeOf(p))
     //    warns.add(new ErrorWarning(x.span(), "This argument may contain a tuple not in the
     // parameter's type.\n"
     //    +"The Alloy Analyzer's analysis may be unsound\n"
     //    +"if the argument has a tuple outside the parameter's type.\n"
     //    +"The argument has type "+y.type+"\nbut the parameter has type "+p));
   }
   return changed ? make(pos, closingBracket, fun, args.makeConst(), extraWeight) : this;
 }
Exemple #28
0
 public String toString() {
   switch (m_utype) {
     case SIN:
       return "sin(" + m_func.toString() + ")";
     case COS:
       return "cos(" + m_func.toString() + ")";
     case LN:
       return "ln(" + m_func.toString() + ")";
     case LOG:
       return "log(" + m_func.toString() + ")";
     case CEIL:
       return "ceil(" + m_func.toString() + ")";
     case FLOOR:
       return "floor(" + m_func.toString() + ")";
     default:
       return null;
   }
 }
Exemple #29
0
 public NumValue evaluate(NumValue[] params) {
   switch (m_utype) {
     case SIN:
       return NumLang.Func.sin(m_func.evaluate(params));
     case COS:
       return NumLang.Func.cos(m_func.evaluate(params));
     case LN:
       return NumLang.Func.ln(m_func.evaluate(params));
     case LOG:
       return NumLang.Func.log(m_func.evaluate(params));
     case CEIL:
       return NumLang.Func.ceil(m_func.evaluate(params));
     case FLOOR:
       return NumLang.Func.floor(m_func.evaluate(params));
     default:
       return null;
   }
 }
Exemple #30
0
 /**
  * Constructs an ExprCall node with the given predicate/function "fun" and the list of arguments
  * "args".
  */
 public static Expr make(
     Pos pos, Pos closingBracket, Func fun, List<Expr> args, long extraPenalty) {
   if (extraPenalty < 0) extraPenalty = 0;
   if (args == null) args = ConstList.make();
   long weight = extraPenalty;
   boolean ambiguous = false;
   JoinableList<Err> errs = emptyListOfErrors;
   TempList<Expr> newargs = new TempList<Expr>(args.size());
   if (args.size() != fun.count()) {
     errs =
         errs.make(
             new ErrorSyntax(
                 pos,
                 ""
                     + fun
                     + " has "
                     + fun.count()
                     + " parameters but is called with "
                     + args.size()
                     + " arguments."));
   }
   for (int i = 0; i < args.size(); i++) {
     final int a = (i < fun.count()) ? fun.get(i).type.arity() : 0;
     final Expr x = args.get(i).typecheck_as_set();
     ambiguous = ambiguous || x.ambiguous;
     errs = errs.make(x.errors);
     weight = weight + x.weight;
     if (x.mult != 0)
       errs = errs.make(new ErrorSyntax(x.span(), "Multiplicity expression not allowed here."));
     if (a > 0 && x.errors.isEmpty() && !x.type.hasArity(a))
       errs =
           errs.make(
               new ErrorType(
                   x.span(),
                   "This should have arity "
                       + a
                       + " but instead its possible type(s) are "
                       + x.type));
     newargs.add(x);
   }
   Type t = Type.FORMULA;
   if (!fun.isPred && errs.size() == 0) {
     final Type tt = fun.returnDecl.type;
     try {
       // This provides a limited form of polymorphic function,
       // by using actual arguments at each call site to derive a tighter bound on the return
       // value.
       DeduceType d = new DeduceType();
       for (int i = 0; i < args.size(); i++) {
         ExprVar param = fun.get(i);
         d.env.put(param, newargs.get(i).type.extract(param.type.arity()));
       }
       t = fun.returnDecl.accept(d);
       if (t == null || t.is_int() || t.is_bool || t.arity() != tt.arity())
         t = tt; // Just in case an error occurred...
     } catch (Throwable ex) {
       t = tt; // Just in case an error occurred...
     }
   }
   return new ExprCall(
       pos, closingBracket, ambiguous, t, fun, newargs.makeConst(), extraPenalty, weight, errs);
 }