示例#1
0
  public void testSumGivesCorrectValue() {
    RealmResults<AllTypes> resultList = testRealm.where(AllTypes.class).findAll();

    Number sum = resultList.sum(FIELD_LONG);
    // Sum of numbers 0 to M-1: (M-1)*M/2
    assertEquals((TEST_DATA_SIZE - 1) * TEST_DATA_SIZE / 2, sum.intValue());
  }
  /**
   * Checks whether the provided value is greater than the minimum. In case the value is an instance
   * of string: checks whether the length of the string is equal to or smaller than the minLength
   * property. In case the value is an instance of number: checks whether the length of the integer
   * value is equal to or smaller than the minLength property.
   *
   * @return boolean true if the length of value is equal to or less than the minLength property,
   *     false otherwise
   * @see
   *     nl.openedge.baritus.validation.FieldValidator#isValid(org.infohazard.maverick.flow.ControllerContext,
   *     nl.openedge.baritus.FormBeanContext, java.lang.String, java.lang.Object)
   */
  @Override
  public boolean isValid(
      ControllerContext cctx, FormBeanContext formBeanContext, String fieldName, Object value) {
    if (minLength == NO_MINIMUM) return true;

    boolean minExceeded = false;
    if (value != null) {
      if (value instanceof String) {
        String toCheck = (String) value;
        int length = toCheck.length();
        minExceeded = (length < minLength);
      } else if (value instanceof Number) {
        Number toCheck = (Number) value;
        int length = toCheck.toString().length();
        minExceeded = (length < minLength);
      } else {
        // just ignore; wrong type to check on
        log.warn(
            fieldName + " with value: " + value + " is of the wrong type for checking on length");
      }
    }

    if (minExceeded) {
      setErrorMessage(
          formBeanContext,
          fieldName,
          getErrorMessageKey(),
          new Object[] {
            getFieldName(formBeanContext, fieldName), value, Integer.valueOf(minLength)
          });
    }

    return (!minExceeded);
  }
示例#3
0
  public Matrix createVector(BitVector selector) {
    int rows = selector != null ? selector.countOnBits() : frame.size();
    Matrix m = new Matrix(rows, 1);

    for (int i = 0, j = 0; j < frame.size(); j++) {
      if (selector == null || selector.isOn(j)) {
        M rowValue = frame.object(j);

        try {
          Number numValue = (Number) numericField.get(rowValue);
          m.set(i, 0, numValue.doubleValue());

        } catch (IllegalAccessException e) {
          e.printStackTrace();
          throw new IllegalStateException(
              String.format(
                  "Couldn't access field %s: %s", numericField.getName(), e.getMessage()));
        }

        i++;
      }
    }

    return m;
  }
  @Test
  public void testCursorPosition() throws Exception {
    selenium.open("../tests/html/test_type_page1.html");
    try {
      assertEquals(selenium.getCursorPosition("username"), "8");
      fail("expected failure");
    } catch (Throwable e) {
    }
    selenium.windowFocus();
    verifyEquals(selenium.getValue("username"), "");
    selenium.type("username", "TestUser");
    selenium.setCursorPosition("username", "0");

    Number position = 0;
    try {
      position = selenium.getCursorPosition("username");
    } catch (SeleniumException e) {
      if (!isWindowInFocus(e)) {
        return;
      }
    }
    verifyEquals(position.toString(), "0");
    selenium.setCursorPosition("username", "-1");
    verifyEquals(selenium.getCursorPosition("username"), "8");
    selenium.refresh();
    selenium.waitForPageToLoad("30000");
    try {
      assertEquals(selenium.getCursorPosition("username"), "8");
      fail("expected failure");
    } catch (Throwable e) {
    }
  }
  private static JSONObject extractVuserResult(Map<Integer, TreeMap<String, Integer>> graphData) {
    JSONObject graphDataSet;
    graphDataSet = new JSONObject();
    JSONArray labels = new JSONArray();

    HashMap<String, ArrayList<Number>> vUserState = new HashMap<String, ArrayList<Number>>(0);
    vUserState.put("Passed", new ArrayList<Number>(0));
    vUserState.put("Failed", new ArrayList<Number>(0));
    vUserState.put("Stopped", new ArrayList<Number>(0));
    vUserState.put("Error", new ArrayList<Number>(0));
    for (Map.Entry<Integer, TreeMap<String, Integer>> run : graphData.entrySet()) {
      Number tempVUserCount = run.getValue().get("Count");
      if (tempVUserCount != null && tempVUserCount.intValue() > 0) {
        labels.add(run.getKey());
        vUserState.get("Passed").add(run.getValue().get("Passed"));
        vUserState.get("Failed").add(run.getValue().get("Failed"));
        vUserState.get("Stopped").add(run.getValue().get("Stopped"));
        vUserState.get("Error").add(run.getValue().get("Error"));
      }
    }

    graphDataSet.put(LABELS, labels);
    graphDataSet.put(SERIES, createGraphDatasets(vUserState));
    return graphDataSet;
  }
示例#6
0
 public Number compute(Number d1, Number d2) {
   float d2Float = d2.floatValue();
   if (d2Float == 0) {
     return null;
   }
   return d1.floatValue() / d2Float;
 }
示例#7
0
 public Number compute(Number d1, Number d2) {
   int d2Int = d2.intValue();
   if (d2Int == 0) {
     return null;
   }
   return d1.intValue() / d2Int;
 }
示例#8
0
  public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
    // only works for numbers - class exception otherwise
    Number millisNumber = (Number) obj;
    long millis = millisNumber.longValue();

    if (m_formats == null) {
      initLocale(null);
    }

    if (millis < DateUtils.MILLIS_PER_SECOND && !m_showZero) {
      return toAppendTo;
    }

    boolean added = false;
    long[] result = calculate(millis);
    for (int i = 0; i < result.length; i++) {
      long l = result[i];
      if (l > 0 || added || i == result.length - 1) {
        if (added) {
          toAppendTo.append(m_separator);
        }
        Object params = new Object[] {l};
        m_formats[i].format(params, toAppendTo, pos);
        added = true;
      }
    }
    return toAppendTo;
  }
示例#9
0
    @Override
    public int compare(Pair<V, Number> pairOne, Pair<V, Number> pairTwo) {

      Number leftSide = pairOne.getRight();
      Number rightSide = pairTwo.getRight();

      if (leftSide.getClass() == Double.class) {
        Double left = (Double) leftSide;
        Double right = (Double) rightSide;

        if (left > right) {
          return 1;
        } else if (right > left) {
          return -1;
        }

      } else if (leftSide.getClass() == Integer.class) {
        Integer left = (Integer) leftSide;
        Integer right = (Integer) rightSide;

        if (left > right) {
          return 1;
        } else if (right > left) {
          return -1;
        }
      }

      return 0;
    }
示例#10
0
  private void renderInner(Graphics2D g, int width2, int height2, double[] spaces) {
    double startAngle = 0D;
    DataModel1D model1 = (DataModel1D) this.getDataModel();
    int stop = model1.getSize();
    g.setColor(this.innerColor);
    // g.setColor(Color.BLACK);
    double ratio = 360 / this.getTotalValue().doubleValue();
    int posX = (getCenterX() - this.innerWidth / 2);
    int posY = (getCenterY() - this.innerHeight / 2); //
    // g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    // RenderingHints.VALUE_ANTIALIAS_OFF);
    for (int i = 0; i < stop; i++) {
      Number n = model1.getValueAt(i);
      if (n == null) {
        continue;
      }
      int angle = (int) Math.round(n.doubleValue() * ratio);
      double moveAngle = startAngle - angle / 2D;
      double angleRadian = ((moveAngle) * Math.PI * 2) / 360;

      double current_space = spaces[i];
      int x = posX + (int) ((Math.cos(angleRadian)) * current_space);
      int y = posY + (int) ((-Math.sin(angleRadian)) * current_space);

      // g.fillArc(x, y, width2 * 2, height2 * 2, (int)
      // Math.round(startAngle), -angle);
      g.fillArc(
          x, y, this.innerWidth, this.innerHeight, (int) Math.round(startAngle) + 50, -angle - 100);

      startAngle -= angle;
    }
  }
示例#11
0
  void _serializeNumber(String key, Number value) {
    NodeList elements = numberElements.getElementsByTagName(ENTRY_FLAG);

    final int size = elements.getLength();

    for (int i = 0; i < size; ++i) {
      Element e = (Element) elements.item(i);
      Attr nameAttr = e.getAttributeNode(KEY_FLAG);
      if (nameAttr == null) {
        throw newMalformedKeyAttrException(Repository.NUMBER);
      }
      if (key.equals(nameAttr.getValue())) {
        Attr valueAttr = e.getAttributeNode(VALUE_FLAG);
        if (valueAttr == null) {
          throw newMalformedValueAttrException(key, Repository.NUMBER);
        }
        Attr typeAttr = e.getAttributeNode(TYPE_FLAG);
        if (typeAttr == null) {
          throw newMalformedTypeAttrException(key, Repository.NUMBER);
        }
        typeAttr.setValue(Configs.resolveNumberType(value).name());
        valueAttr.setValue(value.toString());
        return;
      }
    }
    // no existing element found
    Element element = xmlDoc.createElement(ENTRY_FLAG);
    element.setAttribute(KEY_FLAG, key);
    element.setAttribute(VALUE_FLAG, value.toString());
    element.setAttribute(TYPE_FLAG, Configs.resolveNumberType(value).name());
    numberElements.appendChild(element);
  }
示例#12
0
 // ***** VDMTOOLS START Name=BoardLine#2|List|Number KEEP=NO
 public BoardLine(final List cells, final Number yi) throws CGException {
   vdm_init_BoardLine();
   if (!this.pre_BoardLine(cells, yi).booleanValue())
     UTIL.RunTime("Precondition failure in BoardLine");
   {
     final Number atom_1 = yi;
     Map res_m_8 = new HashMap();
     {
       Set e1_set_13 = new HashSet(cells);
       Set e_set_14 = new HashSet();
       e_set_14 = new HashSet();
       for (int count_17 = 1; count_17 <= 9; count_17++) e_set_14.add(new Integer(count_17));
       Number x = null;
       Cell cell = null;
       Set tmpSet_30 = new HashSet(e_set_14);
       for (Iterator enm_29 = tmpSet_30.iterator(); enm_29.hasNext(); ) {
         Number elem_28 = UTIL.NumberToInt(enm_29.next());
         /* x */
         x = elem_28;
         Set tmpSet_27 = new HashSet(e1_set_13);
         for (Iterator enm_26 = tmpSet_27.iterator(); enm_26.hasNext(); ) {
           Cell elem_25 = (Cell) enm_26.next();
           /* cell */
           cell = elem_25;
           if ((cell.x).intValue() == x.intValue()) res_m_8.put(x, cell);
         }
       }
     }
     final Map atom_2 = res_m_8;
     y = UTIL.NumberToInt(UTIL.clone(atom_1));
     line = (Map) UTIL.clone(atom_2);
   }
 }
示例#13
0
 public WOActionResults saveType() {
   EOEditingContext ec = (EOEditingContext) valueForBinding("ec");
   ec.lock();
   try {
     boolean newType = (currType == null);
     if (newType) {
       currType = (ItogType) EOUtilities.createAndInsertInstance(ec, ItogType.ENTITY_NAME);
       Number maxSort = (Number) valueForBinding("maxSort");
       if (maxSort != null) {
         currType.setSort(new Integer(maxSort.intValue() + 1));
       } else {
         currType.setSort(new Integer(1));
       }
     }
     currType.setName(itogName);
     currType.setTitle(itogTitle);
     currType.setInYearCount((itogCount == null) ? new Integer(0) : itogCount);
     ec.saveChanges();
     //			if(newType) {
     //				allTypes = allTypes.arrayByAddingObject(currType);
     //				itogsList = NSArray.EmptyArray;
     //			}
     setValueForBinding(currType, "currType");
   } catch (Exception e) {
     SetupItogs.logger.log(WOLogLevel.WARNING, "Error saving changes in list ", e);
     session().takeValueForKey(e.getMessage(), "message");
     ec.revert();
   } finally {
     ec.unlock();
   }
   return (WOActionResults) valueForBinding("actionResult");
 }
示例#14
0
 /**
  * Constructs a new <code>LongRange</code> with the specified minimum and maximum numbers (both
  * inclusive).
  *
  * <p>The arguments may be passed in the order (min,max) or (max,min). The getMinimum and
  * getMaximum methods will return the correct values.
  *
  * @param number1 first number that defines the edge of the range, inclusive
  * @param number2 second number that defines the edge of the range, inclusive
  * @throws IllegalArgumentException if either number is <code>null</code>
  */
 public LongRange(Number number1, Number number2) {
   super();
   if (number1 == null || number2 == null) {
     throw new IllegalArgumentException("The numbers must not be null");
   }
   long number1val = number1.longValue();
   long number2val = number2.longValue();
   if (number2val < number1val) {
     this.min = number2val;
     this.max = number1val;
     if (number2 instanceof Long) {
       this.minObject = (Long) number2;
     }
     if (number1 instanceof Long) {
       this.maxObject = (Long) number1;
     }
   } else {
     this.min = number1val;
     this.max = number2val;
     if (number1 instanceof Long) {
       this.minObject = (Long) number1;
     }
     if (number2 instanceof Long) {
       this.maxObject = (Long) number2;
     }
   }
 }
示例#15
0
 private double[] retrieveFcReadings(NodeList cycleList) {
   // Check the the first cycle is cycle #1, else throw an error dialog
   Element firstCycleElement = (Element) cycleList.item(0);
   String firstCycleNumber = firstCycleElement.getAttribute("X");
   if (!firstCycleNumber.contains("1")) {
     // TODO present an error dialog and terminate import
     // ...pretty harsh but this is essential for baseline subtraction
   }
   NumberFormat numFormat =
       NumberFormat.getInstance(); // Need to convert comma decimal seperators to periods
   ArrayList<Double> fcDataSet = Lists.newArrayList();
   // Cycle through the cycles and collect the Fc readings
   for (int j = 0; j < cycleList.getLength(); j++) {
     // This assumes that the first cycle is cycle 1
     Element cycleElement = (Element) cycleList.item(j);
     try {
       // NumberFormat needed to prevent locale differences in numbers (e.g. comma vs period)
       Number value = numFormat.parse(cycleElement.getAttribute("Y"));
       fcDataSet.add(value.doubleValue());
     } catch (Exception e) {
     }
   }
   double[] fcArray = new double[fcDataSet.size()];
   for (int k = 0; k < fcDataSet.size(); k++) {
     fcArray[k] = fcDataSet.get(k);
   }
   return fcArray;
 }
  private void testCorrectnessOfErrorFunction(List<Number> inputList) throws Exception {
    int inRange = 0;
    int numberOfRuns = 1000;
    double sampleRatio = 1 / (double) WEIGHT;
    double actual = getExpectedValue(inputList);
    Random rand = new Random(1);

    for (int i = 0; i < numberOfRuns; i++) {
      // Compute Sampled Value using sampledList (numberOfRuns times)
      ImmutableList.Builder<Number> sampledList = ImmutableList.builder();
      for (Number x : inputList) {
        if (rand.nextDouble() < sampleRatio) {
          sampledList.add(x);
        }
      }

      BlockBuilder builder = getType().createBlockBuilder(new BlockBuilderStatus());
      for (Number sample : sampledList.build()) {
        if (getType() == BIGINT) {
          BIGINT.writeLong(builder, sample.longValue());
        } else if (getType() == DOUBLE) {
          DOUBLE.writeDouble(builder, sample.doubleValue());
        } else {
          throw new AssertionError("Can only handle longs and doubles");
        }
      }
      Page page = new Page(builder.build());
      page = OperatorAssertion.appendSampleWeight(ImmutableList.of(page), WEIGHT).get(0);
      Accumulator accumulator =
          getFunction()
              .bind(
                  ImmutableList.of(0),
                  Optional.<Integer>absent(),
                  Optional.of(page.getChannelCount() - 1),
                  getConfidence())
              .createAccumulator();

      accumulator.addInput(page);
      Block result = accumulator.evaluateFinal();

      String approxValue =
          BlockAssertions.toValues(accumulator.getFinalType(), result).get(0).toString();
      double approx = Double.parseDouble(approxValue.split(" ")[0]);
      double error = Double.parseDouble(approxValue.split(" ")[2]);

      // Check if actual answer lies within [approxAnswer - error, approxAnswer + error]
      if (Math.abs(approx - actual) <= error) {
        inRange++;
      }
    }

    BinomialDistribution binomial = new BinomialDistribution(numberOfRuns, getConfidence());
    int lowerBound = binomial.inverseCumulativeProbability(0.01);
    int upperBound = binomial.inverseCumulativeProbability(0.99);
    assertTrue(
        lowerBound < inRange && inRange < upperBound,
        String.format(
            "%d out of %d passed. Expected [%d, %d]",
            inRange, numberOfRuns, lowerBound, upperBound));
  }
示例#17
0
 public Number compute(Number d1, Number d2) {
   double d2Double = d2.doubleValue();
   if ((divisionByZeroReturnsNull) && (d2Double == 0)) {
     return null;
   }
   return d1.doubleValue() / d2Double;
 }
示例#18
0
  static EvPixels apply(Number aVal, EvPixels b) {
    if (aVal instanceof Integer && b.getType() == EvPixelsType.INT) {
      // Should use the common higher type here
      b = b.getReadOnly(EvPixelsType.INT);
      int a = aVal.intValue();

      int w = b.getWidth();
      int h = b.getHeight();
      EvPixels out = new EvPixels(b.getType(), w, h);
      int[] bPixels = b.getArrayInt();
      int[] outPixels = out.getArrayInt();

      for (int i = 0; i < bPixels.length; i++) outPixels[i] = a / bPixels[i];

      return out;
    } else {
      // Should use the common higher type here
      b = b.getReadOnly(EvPixelsType.DOUBLE);
      double a = aVal.doubleValue();

      int w = b.getWidth();
      int h = b.getHeight();
      EvPixels out = new EvPixels(b.getType(), w, h);
      double[] bPixels = b.getArrayDouble();
      double[] outPixels = out.getArrayDouble();

      for (int i = 0; i < bPixels.length; i++) outPixels[i] = a / bPixels[i];

      return out;
    }
  }
示例#19
0
 public Number compute(Number d1, Number d2) {
   long d2Long = d2.longValue();
   if (d2Long == 0) {
     return null;
   }
   return d1.longValue() / d2Long;
 }
  private void writeTable(
      Iterable<Number> values,
      FormatAndBits compression,
      int count,
      NormMap uniqueValues,
      int numOrds)
      throws IOException {
    data.writeVInt(PackedInts.VERSION_CURRENT);
    data.writeVInt(compression.format.getId());
    data.writeVInt(compression.bitsPerValue);

    data.writeVInt(numOrds);
    for (int i = 0; i < numOrds; i++) {
      data.writeByte(uniqueValues.values[i]);
    }

    final PackedInts.Writer writer =
        PackedInts.getWriterNoHeader(
            data,
            compression.format,
            count,
            compression.bitsPerValue,
            PackedInts.DEFAULT_BUFFER_SIZE);
    for (Number nv : values) {
      int ord = uniqueValues.ord(nv.byteValue());
      if (ord < numOrds) {
        writer.add(ord);
      } else {
        writer.add(numOrds); // collapses all ords >= numOrds into a single value
      }
    }
    writer.finish();
  }
示例#21
0
文件: Utils.java 项目: paulstay/APN
  public static double getPercentParameter(
      HttpServletRequest request, String param, double defValue) {
    double p = defValue;
    String input = request.getParameter(param);
    String pattern = "##.####%";

    if ((input == null) || (input.equals(""))) {
      return p;
    }

    // Make sure we have a % at the end of the string, if not add one.
    if (input.indexOf('%') < 0) {
      input = input + "%";
    }

    NumberFormat parser = null;
    if (!pattern.equals("")) {
      parser = new DecimalFormat(pattern);
    } else {
      parser = NumberFormat.getPercentInstance();
    }

    Number parsed = null;
    try {
      parsed = parser.parse(input);
    } catch (ParseException pe) {
      return defValue;
    }

    return parsed.doubleValue();
  }
 /**
  * Returns the range of values the renderer requires to display all the items from the specified
  * dataset.
  *
  * @param dataset the dataset (<code>null</code> not permitted).
  * @return The range (or <code>null</code> if the dataset is empty).
  */
 public Range findRangeBounds(CategoryDataset dataset) {
   if (dataset == null) {
     return null;
   }
   boolean allItemsNull = true; // we'll set this to false if there is at
   // least one non-null data item...
   double minimum = 0.0;
   double maximum = 0.0;
   int columnCount = dataset.getColumnCount();
   for (int row = 0; row < dataset.getRowCount(); row++) {
     double runningTotal = 0.0;
     for (int column = 0; column <= columnCount - 1; column++) {
       Number n = dataset.getValue(row, column);
       if (n != null) {
         allItemsNull = false;
         double value = n.doubleValue();
         if (column == columnCount - 1) {
           // treat the last column value as an absolute
           runningTotal = value;
         } else {
           runningTotal = runningTotal + value;
         }
         minimum = Math.min(minimum, runningTotal);
         maximum = Math.max(maximum, runningTotal);
       }
     }
   }
   if (!allItemsNull) {
     return new Range(minimum, maximum);
   } else {
     return null;
   }
 }
示例#23
0
  private Variable getVariableFromJmxAttribute(JmxAttribute pAttribute) throws JMException {

    final Object value = pAttribute.getValue();

    if (value == null) {
      return new Null();
    }

    final String type = pAttribute.getType();

    if ("int".equals(type)) {
      final Number n = (Number) value;
      return new Integer32(n.intValue());
    } else if ("long".equals(type)) {
      final Number n = (Number) value;
      return new Counter64(n.longValue());
    } else if ("boolean".equals(type)) {
      final Boolean b = (Boolean) value;
      return new Integer32(b ? 1 : 0);
    } else if ("java.lang.String".equals(type)) {
      return new OctetString(String.valueOf(value));
    } else {
      return new OctetString("Unsupported Type: " + pAttribute.getType());
    }
  }
 @Override
 protected Prompt acceptValidatedInput(ConversationContext context, Number input) {
   boolean found = false;
   for (NPC npc : choices) {
     if (input.intValue() == npc.getId()) {
       found = true;
       break;
     }
   }
   CommandSender sender = (CommandSender) context.getForWhom();
   if (!found) {
     Messaging.sendErrorTr(sender, Messages.SELECTION_PROMPT_INVALID_CHOICE, input);
     return this;
   }
   NPC toSelect = CitizensAPI.getNPCRegistry().getById(input.intValue());
   try {
     callback.run(toSelect);
   } catch (ServerCommandException ex) {
     Messaging.sendTr(sender, CommandMessages.MUST_BE_INGAME);
   } catch (CommandUsageException ex) {
     Messaging.sendError(sender, ex.getMessage());
     Messaging.sendError(sender, ex.getUsage());
   } catch (UnhandledCommandException ex) {
     ex.printStackTrace();
   } catch (WrappedCommandException ex) {
     ex.getCause().printStackTrace();
   } catch (CommandException ex) {
     Messaging.sendError(sender, ex.getMessage());
   } catch (NumberFormatException ex) {
     Messaging.sendErrorTr(sender, CommandMessages.INVALID_NUMBER);
   }
   return null;
 }
  @Override
  public TokenStream tokenStream(Analyzer analyzer, TokenStream reuse) throws IOException {
    if (!fieldType().indexed()) {
      return null;
    }

    final NumericType numericType = fieldType().numericType();
    if (numericType != null) {
      if (!(reuse instanceof NumericTokenStream
          && ((NumericTokenStream) reuse).getPrecisionStep() == type.numericPrecisionStep())) {
        // lazy init the TokenStream as it is heavy to instantiate
        // (attributes,...) if not needed (stored field loading)
        reuse = new NumericTokenStream(type.numericPrecisionStep());
      }
      final NumericTokenStream nts = (NumericTokenStream) reuse;
      // initialize value in TokenStream
      final Number val = (Number) fieldsData;
      switch (numericType) {
        case INT:
          nts.setIntValue(val.intValue());
          break;
        case LONG:
          nts.setLongValue(val.longValue());
          break;
        case FLOAT:
          nts.setFloatValue(val.floatValue());
          break;
        case DOUBLE:
          nts.setDoubleValue(val.doubleValue());
          break;
        default:
          throw new AssertionError("Should never get here");
      }
      return reuse;
    }

    if (!fieldType().tokenized()) {
      if (stringValue() == null) {
        throw new IllegalArgumentException("Non-Tokenized Fields must have a String value");
      }
      if (!(reuse instanceof StringTokenStream)) {
        // lazy init the TokenStream as it is heavy to instantiate
        // (attributes,...) if not needed (stored field loading)
        reuse = new StringTokenStream();
      }
      ((StringTokenStream) reuse).setValue(stringValue());
      return reuse;
    }

    if (tokenStream != null) {
      return tokenStream;
    } else if (readerValue() != null) {
      return analyzer.tokenStream(name(), readerValue());
    } else if (stringValue() != null) {
      return analyzer.tokenStream(name(), stringValue());
    }

    throw new IllegalArgumentException(
        "Field must have either TokenStream, String, Reader or Number value; got " + this);
  }
 public void saveDisplayObjectType() {
   DOTPoint newDOTPoint =
       (DOTPoint) _dotDefinitionDialogFrame.getScratchDisplayObjectType().getCopy(null);
   final String name = _dotDefinitionDialogFrame.getNameText();
   if ((name == null) || (name.length() == 0)) {
     JOptionPane.showMessageDialog(
         new JFrame(), "Bitte geben Sie einen Namen an!", "Fehler", JOptionPane.ERROR_MESSAGE);
     return;
   }
   if (!_dotDefinitionDialogFrame.isReviseOnly()) {
     if (_dotDefinitionDialogFrame.getDotManager().containsDisplayObjectType(name)) {
       JOptionPane.showMessageDialog(
           new JFrame(),
           "Ein Darstellungstyp mit diesem Namen existiert bereits!",
           "Fehler",
           JOptionPane.ERROR_MESSAGE);
       return;
     }
   }
   newDOTPoint.setName(name);
   newDOTPoint.setInfo(_dotDefinitionDialogFrame.getInfoText());
   final Object value = _translationFactorSpinner.getValue();
   if (value instanceof Number) {
     final Number number = (Number) value;
     newDOTPoint.setTranslationFactor(number.doubleValue());
   }
   newDOTPoint.setJoinByLine(_joinByLineCheckBox.isSelected());
   _dotDefinitionDialogFrame.getDotManager().saveDisplayObjectType(newDOTPoint);
   _dotDefinitionDialogFrame.setDisplayObjectType(newDOTPoint, true);
 }
示例#27
0
 /**
  * Tests if this object is equal to another
  *
  * @param a_obj the other object
  * @return true: this object is equal to the other one
  * @author Klaus Meffert
  * @since 2.3
  */
 public boolean equals(final Object a_obj) {
   if (a_obj == null) {
     return false;
   }
   if (a_obj == this) {
     return true;
   }
   if (!(a_obj instanceof KeyedValues)) {
     return false;
   }
   final KeyedValues kvs = (KeyedValues) a_obj;
   final int count = size();
   if (count != kvs.size()) {
     return false;
   }
   for (int i = 0; i < count; i++) {
     final Comparable k1 = getKey(i);
     final Comparable k2 = kvs.getKey(i);
     if (!k1.equals(k2)) {
       return false;
     }
     final Number v1 = getValue(i);
     final Number v2 = kvs.getValue(i);
     if (v1 == null) {
       if (v2 != null) {
         return false;
       }
     } else {
       if (!v1.equals(v2)) {
         return false;
       }
     }
   }
   return true;
 }
示例#28
0
 /**
  * 对数字对象作处理,如果为0或空则返回默认值
  *
  * @param number 数字对象
  * @param defaultValue 默认值
  * @return
  */
 public static String number(Number number, String defaultValue) {
   if (number == null || StringUtils.isBlank(number.toString()) || "0".equals(number.toString())) {
     return defaultValue;
   } else {
     return number.toString();
   }
 }
示例#29
0
 private Object maxOfList(Node lst, RuleContext context) {
   java.util.List<Node> l = Util.convertList(lst, context);
   Number max = null;
   XSDDateTime maxDate = null;
   for (int i = 0; l != null && i < l.size(); i++) {
     Node elt = (Node) l.get(i);
     if (elt != null && elt.isLiteral()) {
       Object v1 = elt.getLiteralValue();
       if (v1 instanceof Number) {
         if (max == null || max.doubleValue() < ((Number) v1).doubleValue()) {
           max = (Number) v1;
         }
       } else if (v1 instanceof XSDDateTime) {
         if (maxDate == null || maxDate.compareTo((XSDDateTime) v1) < 0) {
           maxDate = (XSDDateTime) v1;
         }
       } else {
         throw new BuiltinException(
             this, context, "Element of list input to max not a number: " + v1.toString());
       }
     } else {
       throw new BuiltinException(
           this, context, "Element of list input to max not a Literal: " + elt.toString());
     }
   }
   if (maxDate != null) {
     return maxDate;
   }
   return max;
 }
    @Override
    public void setItem(Object anObject) {
      // System.out.println("setItem: " + anObject + " " + anObject.getClass());
      if (anObject instanceof String) {
        try {
          Object o = inputFormat.parseObject((String) anObject);
          // HACK: have to fix up DecimalFormat parsed object because
          // it may return Long whole number with fraction
          if (isNumberModel) {
            Number number = (Number) o;

            // System.out.println("SetItem PARSED: " + number + " " + number.getClass());
            if (isFloatingPoint) {
              if (!(number instanceof Double) && !(number instanceof Float))
                o = new Double(number.doubleValue());
            } else {
              if (!(number instanceof Integer) && !(number instanceof Long))
                o = new Long(number.longValue());
            }
          }
          spinner.setValue(o);
        } catch (ParseException pe) {
          RuntimeException t = new IllegalArgumentException("Illegal input: " + anObject);
          t.initCause(pe);
          throw t;
        }
      } else {
        throw new RuntimeException("asdfasdasdf");
        // spinner.setValue(anObject);
      }
    }