Java Code Examples for com.google.common.primitives.Doubles#tryParse()

The following examples show how to use com.google.common.primitives.Doubles#tryParse() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LocalVerCodeParseServiceImpl.java    From baidu-chain-dog with GNU General Public License v3.0 6 votes vote down vote up
private StringBuilder doPredict(List<String> svmTest) {
    StringBuilder result = new StringBuilder();
    for(String line : svmTest) {
        StringTokenizer st = new StringTokenizer(line, " \t\n\r\f:");
        Double target = Doubles.tryParse(st.nextToken());
        Preconditions.checkNotNull(target);
        int m = st.countTokens() / 2;
        svm_node[] x = new svm_node[m];
        for (int j = 0; j < m; j++) {
            x[j] = new svm_node();
            Integer index = Ints.tryParse(st.nextToken());
            Double value = Doubles.tryParse(st.nextToken());
            Preconditions.checkNotNull(index);
            Preconditions.checkNotNull(value);
            x[j].index = index;
            x[j].value = value;
        }

        double v = svm.svm_predict(model, x);
        result.append(labels.get((int)v));

    }
    return result;
}
 
Example 2
Source File: BuyTask.java    From baidu-chain-dog with GNU General Public License v3.0 6 votes vote down vote up
private void tryCreateOrder(Acount acount, List<Pet> pets) {
    for (Pet pet : pets) {
        try {
            Amount rareDegree = rareDegreeMap.get(pet.getRareDegree());
            Double amount = Doubles.tryParse(pet.getAmount());
            if (canCreateOrder(rareDegree, amount, pet)) {
                createOrder(acount, pet);
            }
        } catch (Throwable e) {
            if (config.getConfig().getLogSwitch()) {
                log.error("生单时发生异常, user:{}", acount.getDes(), e);
            }
            log.info("生单时发生异常, user:{} petId:{},amount:{}", acount.getDes(), pet.getPetId(), pet.getAmount());

        }
    }
}
 
Example 3
Source File: TimeSeries.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
void parseToken(int i, String token) {
    if (dataTypes[i - 2] == null) {
        // test double parsing, in case of error we consider it a string time series
        if (Doubles.tryParse(token) != null) {
            dataTypes[i - 2] = TimeSeriesDataType.DOUBLE;
            TDoubleArrayList doubleValues = createDoubleValues();
            doubleValues.add(parseDouble(token));
            values[i - 2] = doubleValues;
        } else {
            dataTypes[i - 2] = TimeSeriesDataType.STRING;
            List<String> stringValues = createStringValues();
            stringValues.add(checkString(token));
            values[i - 2] = stringValues;
        }
    } else {
        if (dataTypes[i - 2] == TimeSeriesDataType.DOUBLE) {
            ((TDoubleArrayList) values[i - 2]).add(parseDouble(token));
        } else if (dataTypes[i - 2] == TimeSeriesDataType.STRING) {
            ((List<String>) values[i - 2]).add(checkString(token));
        } else {
            throw assertDataType(dataTypes[i - 2]);
        }
    }
}
 
Example 4
Source File: SmartUriAdapter.java    From rya with Apache License 2.0 6 votes vote down vote up
private static IRI determineType(final String data) {
    if (Ints.tryParse(data) != null) {
        return XMLSchema.INTEGER;
    } else if (Doubles.tryParse(data) != null) {
        return XMLSchema.DOUBLE;
    } else if (Floats.tryParse(data) != null) {
        return XMLSchema.FLOAT;
    } else if (isShort(data)) {
        return XMLSchema.SHORT;
    } else if (Longs.tryParse(data) != null) {
        return XMLSchema.LONG;
    } if (Boolean.parseBoolean(data)) {
        return XMLSchema.BOOLEAN;
    } else if (isByte(data)) {
        return XMLSchema.BYTE;
    } else if (isDate(data)) {
        return XMLSchema.DATETIME;
    } else if (isUri(data)) {
        return XMLSchema.ANYURI;
    }

    return XMLSchema.STRING;
}
 
Example 5
Source File: ProperHeadMatchSieve.java    From baleen with Apache License 2.0 5 votes vote down vote up
private List<Double> extractNumbers(String text) {
  final List<Double> list = new LinkedList<>();
  final Matcher matcher = NUMBER.matcher(text);
  while (matcher.find()) {
    final Double d = Doubles.tryParse(matcher.group().replaceAll(",", ""));
    if (d != null) {
      list.add(d);
    }
  }
  return list;
}
 
Example 6
Source File: Series.java    From jpandas with Apache License 2.0 5 votes vote down vote up
public double mean() {
    double sum = 0;
    for (E item : this) {
        // TODO: Correspond missing value
        if (Doubles.tryParse(item.toString()) != null ) {
            sum += Double.parseDouble(item.toString());
        }
    }
    return this.size() == 0 ? 0 : sum / this.size();
}
 
Example 7
Source File: Series.java    From jpandas with Apache License 2.0 5 votes vote down vote up
public double std() {
    double sum = 0;
    double mean = this.mean();

    for (E item: this) {
        // TODO: Correspond missing value
        if (Doubles.tryParse(item.toString()) != null) {
            sum += Math.pow(Double.parseDouble(item.toString()) - mean, 2);
        }
    }

    return this.size() == 0 ? 0 : sum / this.size();
}
 
Example 8
Source File: BeforeConstant.java    From Mixin with MIT License 5 votes vote down vote up
public BeforeConstant(InjectionPointData data) {
    super(data);
    
    String strNullValue = data.get("nullValue", null);
    Boolean empty = strNullValue != null ? Boolean.parseBoolean(strNullValue) : null;
    
    this.ordinal = data.getOrdinal();
    this.nullValue = empty != null && empty.booleanValue();
    this.intValue = Ints.tryParse(data.get("intValue", ""));
    this.floatValue = Floats.tryParse(data.get("floatValue", ""));
    this.longValue = Longs.tryParse(data.get("longValue", ""));
    this.doubleValue = Doubles.tryParse(data.get("doubleValue", ""));
    this.stringValue = data.get("stringValue", null);
    String strClassValue = data.get("classValue", null);
    this.typeValue = strClassValue != null ? Type.getObjectType(strClassValue.replace('.', '/')) : null;
    
    this.matchByType = this.validateDiscriminator(data.getContext(), "V", empty, "in @At(\"CONSTANT\") args");
    if ("V".equals(this.matchByType)) {
        throw new InvalidInjectionException(data.getContext(), "No constant discriminator could be parsed in @At(\"CONSTANT\") args");
    }
    
    List<Condition> conditions = new ArrayList<Condition>();
    String strConditions = data.get("expandZeroConditions", "").toLowerCase(Locale.ROOT);
    for (Condition condition : Condition.values()) {
        if (strConditions.contains(condition.name().toLowerCase(Locale.ROOT))) {
            conditions.add(condition);
        }
    }
    
    this.expandOpcodes = this.parseExpandOpcodes(conditions);
    this.expand = this.expandOpcodes.length > 0;
    
    this.log = data.get("log", false);
}
 
Example 9
Source File: InfluxDBEventReporter.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Convert the event value taken from the metadata to double (default type).
 * It falls back to string type if the value is missing or it is non-numeric
 * is of string or missing
 * Metadata entries are emitted as distinct events (see {@link MultiPartEvent})
 *
 * @param field {@link GobblinTrackingEvent} metadata key
 * @param value {@link GobblinTrackingEvent} metadata value
 * @return The converted event value
 */
private Object convertValue(String field, String value) {
  if (value == null) return EMTPY_VALUE;
  if (METADATA_DURATION.equals(field)) {
    return convertDuration(TimeUnit.MILLISECONDS.toNanos(Long.parseLong(value)));
  }
  else {
    Double doubleValue = Doubles.tryParse(value);
    return (doubleValue == null) ? value : doubleValue;
  }
}
 
Example 10
Source File: PlainTextTableWriter.java    From JGiven with Apache License 2.0 5 votes vote down vote up
private List<ColumnSpec> getColumnSpecs( List<List<String>> dataTableModel ) {
    if( dataTableModel.isEmpty() ) {
        return Collections.emptyList();
    }

    ColumnSpec[] result = new ColumnSpec[dataTableModel.get( 0 ).size()];
    for( int nrow = 0; nrow < dataTableModel.size(); nrow++ ) {
        List<String> row = dataTableModel.get( nrow );
        for( int ncol = 0; ncol < row.size(); ncol++ ) {
            String value = row.get( ncol );
            int width = Math.max( value.length(), 1 );
            ColumnSpec spec = result[ncol];
            if( spec == null ) {
                spec = new ColumnSpec();
                result[ncol] = spec;
            }
            if( width > spec.width ) {
                spec.width = width;
            }

            if( nrow > 0 && Doubles.tryParse( value ) == null ) {
                spec.leftAligned = true;
            }
        }
    }
    return Lists.newArrayList( result );
}
 
Example 11
Source File: LumongoQueryParser.java    From lumongo with Apache License 2.0 5 votes vote down vote up
@Override
protected Query newTermQuery(org.apache.lucene.index.Term term) {
	String field = term.field();
	String text = term.text();

	FieldConfig.FieldType fieldType = indexConfig.getFieldTypeForIndexField(field);
	if (IndexConfigUtil.isNumericOrDateFieldType(fieldType)) {
		if (IndexConfigUtil.isDateFieldType(fieldType)) {
			return getNumericOrDateRange(field, text, text, true, true);
		}
		else {
			if (IndexConfigUtil.isNumericIntFieldType(fieldType) && Ints.tryParse(text) != null) {
				return getNumericOrDateRange(field, text, text, true, true);
			}
			else if (IndexConfigUtil.isNumericLongFieldType(fieldType) && Longs.tryParse(text) != null) {
				return getNumericOrDateRange(field, text, text, true, true);
			}
			else if (IndexConfigUtil.isNumericFloatFieldType(fieldType) && Floats.tryParse(text) != null) {
				return getNumericOrDateRange(field, text, text, true, true);
			}
			else if (IndexConfigUtil.isNumericDoubleFieldType(fieldType) && Doubles.tryParse(text) != null) {
				return getNumericOrDateRange(field, text, text, true, true);
			}
		}
		return new MatchNoDocsQuery(field + " expects numeric");
	}

	return super.newTermQuery(term);
}
 
Example 12
Source File: LogFilter.java    From jinjava with Apache License 2.0 4 votes vote down vote up
@Override
public Object filter(Object object, JinjavaInterpreter interpreter, String... args) {
  // default to e
  Double root = null;
  if (args.length > 0 && args[0] != null) {
    Double tryRoot = Doubles.tryParse(args[0]);
    if (tryRoot == null) {
      throw new InvalidArgumentException(
        interpreter,
        this,
        InvalidReason.NUMBER_FORMAT,
        0,
        args[0]
      );
    }

    root = tryRoot;
  }

  if (object instanceof Integer) {
    return calculateLog(interpreter, (Integer) object, root);
  }
  if (object instanceof Float) {
    return calculateLog(interpreter, (Float) object, root);
  }
  if (object instanceof Long) {
    return calculateLog(interpreter, (Long) object, root);
  }
  if (object instanceof Short) {
    return calculateLog(interpreter, (Short) object, root);
  }
  if (object instanceof Double) {
    return calculateLog(interpreter, (Double) object, root);
  }
  if (object instanceof Byte) {
    return calculateLog(interpreter, (Byte) object, root);
  }
  if (object instanceof BigDecimal) {
    return calculateBigLog(interpreter, (BigDecimal) object, root);
  }
  if (object instanceof BigInteger) {
    return calculateBigLog(interpreter, new BigDecimal((BigInteger) object), root);
  }
  if (object instanceof String) {
    try {
      return calculateBigLog(interpreter, new BigDecimal((String) object), root);
    } catch (NumberFormatException e) {
      throw new InvalidInputException(
        interpreter,
        this,
        InvalidReason.NUMBER_FORMAT,
        object.toString()
      );
    }
  }

  return object;
}
 
Example 13
Source File: RootFilter.java    From jinjava with Apache License 2.0 4 votes vote down vote up
@Override
public Object filter(Object object, JinjavaInterpreter interpreter, String... args) {
  double root = 2;
  if (args.length > 0 && args[0] != null) {
    Double tryRoot = Doubles.tryParse(args[0]);
    if (tryRoot == null) {
      throw new InvalidArgumentException(
        interpreter,
        this,
        InvalidReason.NUMBER_FORMAT,
        0,
        args[0]
      );
    }

    root = tryRoot;
  }

  if (object instanceof Integer) {
    return calculateRoot(interpreter, (Integer) object, root);
  }
  if (object instanceof Float) {
    return calculateRoot(interpreter, (Float) object, root);
  }
  if (object instanceof Long) {
    return calculateRoot(interpreter, (Long) object, root);
  }
  if (object instanceof Short) {
    return calculateRoot(interpreter, (Short) object, root);
  }
  if (object instanceof Double) {
    return calculateRoot(interpreter, (Double) object, root);
  }
  if (object instanceof Byte) {
    return calculateRoot(interpreter, (Byte) object, root);
  }
  if (object instanceof BigDecimal) {
    return calculateBigRoot(interpreter, (BigDecimal) object, root);
  }
  if (object instanceof BigInteger) {
    return calculateBigRoot(interpreter, new BigDecimal((BigInteger) object), root);
  }
  if (object instanceof String) {
    try {
      return calculateBigRoot(interpreter, new BigDecimal((String) object), root);
    } catch (NumberFormatException e) {
      throw new InvalidInputException(
        interpreter,
        this,
        InvalidReason.NUMBER_FORMAT,
        object.toString()
      );
    }
  }

  return object;
}
 
Example 14
Source File: IsStringANumber.java    From levelup-java-examples with Apache License 2.0 3 votes vote down vote up
@Test
public void is_string_a_number_guava () {
	
	Double parsedString = Doubles.tryParse("123234.54");
	
	assertEquals(new Double(123234.54), parsedString);
}