bool UnaryOpExpression::preCompute(const Variant& value, Variant &result) { bool ret = true; try { g_context->setThrowAllErrors(true); auto add = RuntimeOption::IntsOverflowToInts ? cellAdd : cellAddO; auto sub = RuntimeOption::IntsOverflowToInts ? cellSub : cellSubO; switch(m_op) { case '!': result = (!toBoolean(value)); break; case '+': cellSet(add(make_tv<KindOfInt64>(0), *value.asCell()), *result.asCell()); break; case '-': cellSet(sub(make_tv<KindOfInt64>(0), *value.asCell()), *result.asCell()); break; case '~': tvSet(*value.asCell(), *result.asTypedValue()); cellBitNot(*result.asCell()); break; case '@': result = value; break; case T_INT_CAST: result = value.toInt64(); break; case T_DOUBLE_CAST: result = toDouble(value); break; case T_STRING_CAST: result = toString(value); break; case T_BOOL_CAST: result = toBoolean(value); break; case T_EMPTY: result = !toBoolean(value); break; case T_ISSET: result = is_not_null(value); break; case T_INC: case T_DEC: assert(false); default: ret = false; break; } } catch (...) { ret = false; } g_context->setThrowAllErrors(false); return ret; }
/** * @brief Determine Hillier parameters given a wavelength * * This method determines the set of Hillier parameters to use * for a given wavelength. It iterates through all band * profiles as read from the PVL file and computes the * difference between the "wavelength" parameter and the * BandBinCenter keyword. The absolute value of this value is * checked against the BandBinCenterTolerance paramter and if it * is less than or equal to it, a Parameter container is * returned. * * @author Kris Becker - 2/22/2010 * * @param wavelength Wavelength used to find parameter set * * @return Hillier::Parameters Container of valid values. If * not found, a value of iProfile = -1 is returned. */ Hillier::Parameters Hillier::findParameters(const double wavelength) const { for(unsigned int i = 0 ; i < _profiles.size() ; i++) { const DbProfile &p = _profiles[i]; if(p.exists("BandBinCenter")) { double p_center = toDouble(ConfKey(p, "BandBinCenter", toString(Null))); double tolerance = toDouble(ConfKey(p, "BandBinCenterTolerance", toString(1.0E-6))); if(fabs(wavelength - p_center) <= fabs(tolerance)) { Parameters pars = extract(p); pars.iProfile = i; pars.wavelength = wavelength; pars.tolerance = tolerance; return (pars); } } } // Not found if we reach here return (Parameters()); }
double toScalar() const { if (isInteger()) return toInteger(); if (isDouble()) return toDouble(); qWarning("can't cast term to scalar"); return 0.0; }
void XLineEdit::sParse() { if (validator() && validator()->inherits("QDoubleValidator")) { QRegExp zeroRegex(QString("^[0") + QLocale().groupSeparator() + "]*" + QLocale().decimalPoint() + "0*$"); if (! text().isEmpty() && toDouble() == 0 && ! text().contains(zeroRegex)) setText(""); } }
QVariant QDBusDemarshaller::toVariantInternal() { switch (q_dbus_message_iter_get_arg_type(&iterator)) { case DBUS_TYPE_BYTE: return qVariantFromValue(toByte()); case DBUS_TYPE_INT16: return qVariantFromValue(toShort()); case DBUS_TYPE_UINT16: return qVariantFromValue(toUShort()); case DBUS_TYPE_INT32: return toInt(); case DBUS_TYPE_UINT32: return toUInt(); case DBUS_TYPE_DOUBLE: return toDouble(); case DBUS_TYPE_BOOLEAN: return toBool(); case DBUS_TYPE_INT64: return toLongLong(); case DBUS_TYPE_UINT64: return toULongLong(); case DBUS_TYPE_STRING: return toString(); case DBUS_TYPE_OBJECT_PATH: return qVariantFromValue(toObjectPath()); case DBUS_TYPE_SIGNATURE: return qVariantFromValue(toSignature()); case DBUS_TYPE_VARIANT: return qVariantFromValue(toVariant()); case DBUS_TYPE_ARRAY: switch (q_dbus_message_iter_get_element_type(&iterator)) { case DBUS_TYPE_BYTE: // QByteArray return toByteArray(); case DBUS_TYPE_STRING: return toStringList(); case DBUS_TYPE_DICT_ENTRY: return qVariantFromValue(duplicate()); default: return qVariantFromValue(duplicate()); } case DBUS_TYPE_STRUCT: return qVariantFromValue(duplicate()); default: qWarning("QDBusDemarshaller: Found unknown D-Bus type %d '%c'", q_dbus_message_iter_get_arg_type(&iterator), q_dbus_message_iter_get_arg_type(&iterator)); return QVariant(); break; }; }
/** * @brief Extracts necessary Hillier parameters from profile * * Given a profile read from the input PVL file, this method * extracts needed parameters (from Keywords) in the PVL profile * and creates a container of the converted values. * * @author Kris Becker - 2/22/2010 * * @param p Profile to extract/convert * * @return Hillier::Parameters Container of extracted values */ Hillier::Parameters Hillier::extract(const DbProfile &p) const { Parameters pars; pars.b0 = toDouble(ConfKey(p, "B0", toString(0.0))); pars.b1 = toDouble(ConfKey(p, "B1", toString(0.0))); pars.a0 = toDouble(ConfKey(p, "A0", toString(0.0))); pars.a1 = toDouble(ConfKey(p, "A1", toString(0.0))); pars.a2 = toDouble(ConfKey(p, "A2", toString(0.0))); pars.a3 = toDouble(ConfKey(p, "A3", toString(0.0))); pars.a4 = toDouble(ConfKey(p, "A4", toString(0.0))); pars.wavelength = toDouble(ConfKey(p, "BandBinCenter", toString(Null))); pars.tolerance = toDouble(ConfKey(p, "BandBinCenterTolerance", toString(Null))); // Determine equation units - defaults to Radians pars.units = ConfKey(p, "HillierUnits", QString("Radians")); pars.phaUnit = (pars.units.toLower() == "degrees") ? 1.0 : rpd_c(); return (pars); }
/*! Returns the variant's value as double reference. */ double& cVariant::asDouble() { if ( typ != DoubleType ) { double dbl = toDouble(); clear(); value.d = dbl; typ = DoubleType; } return value.d; }
DictionaryPlugin::DictionaryPlugin(Configuration* config, ContextTracker* ht) : Plugin(config, ht, "DictionaryPlugin", "DictionaryPlugin, dictionary lookup", "DictionaryPlugin, a dictionary based plugin that generates a prediction by extracting tokens that start with the current prefix from a given dictionary") { // might throw ConfigurationException dictionary_path = config->get(DICTIONARY); probability = toDouble(config->get(PROBABILITY)); }
qreal Tools::getNum(const QChar *&str) { while (str->isSpace()) ++str; qreal num = toDouble(str); while (str->isSpace()) ++str; if (*str == QLatin1Char(',')) ++str; return num; }
RecencyPlugin::RecencyPlugin(Configuration* config, ContextTracker* ct) : Plugin(config, ct, "RecencyPlugin", "RecencyPlugin, a statistical recency promotion plugin", "RecencyPlugin, based on a recency promotion principle, generates predictions by assigning exponentially decaying probability values to previously encountered tokens. Tokens are assigned a probability value that decays exponentially with their distance from the current token, thereby promoting context recency." ) { // init default values lambda = 1; n_0 = 1; cutoff_threshold = 20; // read values from config try { Value value = config->get(LOGGER); logger << setlevel(value); logger << INFO << "LOGGER: " << value << endl; } catch (Configuration::ConfigurationException ex) { logger << WARN << "Caught ConfigurationException: " << ex.what() << endl; } try { Value value = config->get(LAMBDA); lambda = toDouble(value); logger << INFO << "LAMBDA: " << value << endl; value = config->get(N_0); n_0 = toDouble(value); logger << INFO << "N_0: " << value << endl; value = config->get(CUTOFF_THRESHOLD); cutoff_threshold = toInt(value); logger << INFO << "CUTOFF_THRESHOLD: " << value << endl; } catch (Configuration::ConfigurationException ex) { logger << ERROR << "Caught fatal ConfigurationException: " << ex.what() << endl; throw PresageException("Unable to init " + name + " predictive plugin."); } }
int GenericType::toInt() const{ if(isDouble()){ double v = toDouble(); casadi_assert_message(v == std::floor(v),"The value is not an integer"); return int(v); } else if (isBool()) { return int(toBool()); } else { casadi_assert_message(isInt(),"type mismatch"); return static_cast<const IntType*>(get())->d_; } }
eveVariant eveVariant::operator* (const eveVariant& other){ eveVariant result; if (varianttype == eveDOUBLE){ result.setType(eveDOUBLE); result.setValue(toDouble() * other.toDouble()); } else if (varianttype == eveINT){ result.setType(eveINT); result.setValue(toInt() * other.toInt()); } return result; }
Number Number::clone() const { switch (type()) { case NumberType::Integer: return Integer(toInteger()); case NumberType::Double: return Double(toDouble()); case NumberType::Float: return Float(toFloat()); case NumberType::Boolean: return Boolean(toBoolean()); } throw std::runtime_error(MakeString()<<"Could not clone number "<<toString()); }
bool eveVariant::operator< (const eveVariant& other){ if (varianttype == eveDOUBLE){ if (toDouble() < other.toDouble()) return true; } else if (varianttype == eveINT){ if (toInt() < other.toInt()) return true; } else if (varianttype == eveDateTimeT){ if (toDateTime() < other.toDateTime()) return true; } return false; }
double BtLineEdit::toSI(Unit::unitDisplay oldUnit,Unit::unitScale oldScale,bool force) { UnitSystem* temp; Unit* works; Unit::unitDisplay dspUnit = oldUnit; Unit::unitScale dspScale = oldScale; // If force is set, just use what is provided in the call. If we are // not forcing the unit & scale, we need to read the configured properties if ( ! force ) { // If the display unit is forced, use this unit the default one. if ( _forceUnit != Unit::noUnit ) dspUnit = _forceUnit; else dspUnit = (Unit::unitDisplay)Brewtarget::option(_editField, Unit::noUnit, _section, Brewtarget::UNIT).toInt(); // If the display scale is forced, use this scale as the default one. if( _forceScale != Unit::noScale ) dspScale = _forceScale; else dspScale = (Unit::unitScale)Brewtarget::option(_editField, Unit::noScale, _section, Brewtarget::SCALE).toInt(); } // Find the unit system containing dspUnit temp = Brewtarget::findUnitSystem(_units,dspUnit); if ( temp ) { // If we found it, find the unit referred by dspScale works = temp->scaleUnit(dspScale); if (! works ) // If we didn't find the unit, default to the UnitSystem's default // unit works = temp->unit(); // get the qstringToSI() from the unit system, using the found unit. // Force the issue in qstringToSI() unless dspScale is Unit::noScale. return temp->qstringToSI(text(), works, dspScale != Unit::noScale, dspScale); } else if ( _type == Unit::String ) return 0.0; // If all else fails, simply try to force the contents of the field to a // double. This doesn't seem advisable? bool ok = false; double amt = toDouble(&ok); if ( ! ok ) Brewtarget::logW( QString("%1 : could not convert %2 (%3:%4) to double").arg(Q_FUNC_INFO).arg(text()).arg(_section).arg(_editField) ); return amt; }
/// Slot called on completion of the Fit algorithm. /// @param error :: Set to true if Fit finishes with an error. void MultiDatasetFit::finishFit(bool error) { if (!error) { m_plotController->clear(); m_plotController->update(); Mantid::API::IFunction_sptr fun; auto algorithm = m_fitRunner->getAlgorithm(); if (m_fitOptionsBrowser->getCurrentFittingType() == MantidWidgets::FitOptionsBrowser::Simultaneous) { // After a simultaneous fit fun = algorithm->getProperty("Function"); updateParameters(*fun); auto status = QString::fromStdString(algorithm->getPropertyValue("OutputStatus")); auto chiSquared = QString::fromStdString( algorithm->getPropertyValue("OutputChi2overDoF")); setFitStatusInfo(status, chiSquared); formatParametersForPlotting( *fun, algorithm->getPropertyValue("OutputParameters")); } else { // After a sequential fit auto paramsWSName = m_fitOptionsBrowser->getProperty("OutputWorkspace").toStdString(); if (!Mantid::API::AnalysisDataService::Instance().doesExist(paramsWSName)) return; size_t nSpectra = getNumberOfSpectra(); if (nSpectra == 0) return; fun = m_functionBrowser->getGlobalFunction(); auto nParams = fun->nParams() / nSpectra; auto params = Mantid::API::AnalysisDataService::Instance() .retrieveWS<Mantid::API::ITableWorkspace>(paramsWSName); if (nParams * 2 + 2 != params->columnCount()) { throw std::logic_error( "Output table workspace has unexpected number of columns."); } for (size_t index = 0; index < nSpectra; ++index) { std::string prefix = "f" + boost::lexical_cast<std::string>(index) + "."; for (size_t ip = 0; ip < nParams; ++ip) { auto colIndex = ip * 2 + 1; auto column = params->getColumn(colIndex); fun->setParameter(prefix + column->name(), column->toDouble(index)); } } updateParameters(*fun); showParameterPlot(); clearFitStatusInfo(); } } m_uiForm.btnFit->setEnabled(true); }
// OLD format: // https://github.com/MinecraftForge/FML/wiki/FML-mod-information-file/5bf6a2d05145ec79387acc0d45c958642fb049fc void Mod::ReadMCModInfo(QByteArray contents) { auto getInfoFromArray = [&](QJsonArray arr)->void { if (!arr.at(0).isObject()) return; auto firstObj = arr.at(0).toObject(); m_mod_id = firstObj.value("modid").toString(); m_name = firstObj.value("name").toString(); m_version = firstObj.value("version").toString(); m_homeurl = firstObj.value("url").toString(); m_description = firstObj.value("description").toString(); QJsonArray authors = firstObj.value("authors").toArray(); if (authors.size() == 0) m_authors = ""; else if (authors.size() >= 1) { m_authors = authors.at(0).toString(); for (int i = 1; i < authors.size(); i++) { m_authors += ", " + authors.at(i).toString(); } } m_credits = firstObj.value("credits").toString(); return; }; QJsonParseError jsonError; QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError); // this is the very old format that had just the array if (jsonDoc.isArray()) { getInfoFromArray(jsonDoc.array()); } else if (jsonDoc.isObject()) { auto val = jsonDoc.object().value("modinfoversion"); int version = val.toDouble(); if (version != 2) { QLOG_ERROR() << "BAD stuff happened to mod json:"; QLOG_ERROR() << contents; return; } auto arrVal = jsonDoc.object().value("modlist"); if (arrVal.isArray()) { getInfoFromArray(arrVal.toArray()); } } }
QList<mdouble> convertToDoubles(QString &sourceString) { auto coords = sourceString.remove("(").remove(")").split(";"); QList<mdouble> values; bool ok; for (auto s = coords.begin(); s != coords.end(); s++) { values<<s->toDouble(&ok); if (!ok) { QString error; error = "Error converting " + *s + " into a number"; throw error; } } return values; }
int main(int argc, char const* argv[]) { int i; for(i = 0; i < 4096*4096; i++) { double f = (rand() % 2 == 0 ? -1 : 1) * (rand() % 2 == 0 ? gen_float_plus() : gen_float_minus()); JSON json = JSONDouble_new(f); assert(toDouble(json.val) - f <= 1e-200); JSON_free(json); char *str = JSON_toString(json); free(str); } return 0; }
/** * Create and initialize a Latitude value using the mapping group's latitude * units and radii. * * @see ErrorChecking * @see CoordinateType * @param latitude The latitude value this instance will represent, * in the mapping group's units * @param mapping A mapping group * @param latitudeUnits The angular units of the latitude value (degs, rads) * @param errors Error checking conditions */ Latitude::Latitude(double latitude, PvlGroup mapping, Angle::Units latitudeUnits, ErrorChecking errors) : Angle(latitude, latitudeUnits) { m_equatorialRadius = NULL; m_polarRadius = NULL; if (mapping.hasKeyword("EquatorialRadius") && mapping.hasKeyword("PolarRadius")) { m_equatorialRadius = new Distance(toDouble(mapping["EquatorialRadius"][0]), Distance::Meters); m_polarRadius = new Distance(toDouble(mapping["PolarRadius"][0]), Distance::Meters); } else { PvlGroup radiiGrp = TProjection::TargetRadii(mapping["TargetName"]); m_equatorialRadius = new Distance(toDouble(radiiGrp["EquatorialRadius"][0]), Distance::Meters); m_polarRadius = new Distance(toDouble(radiiGrp["PolarRadius"][0]), Distance::Meters); } m_errors = errors; if(mapping["LatitudeType"][0] == "Planetographic") { setPlanetographic(latitude, latitudeUnits); } else if(mapping["LatitudeType"][0] == "Planetocentric") { setPlanetocentric(latitude, latitudeUnits); } else { IString msg = "Latitude type [" + IString(mapping["LatitudeType"][0]) + "] is not recognized"; throw IException(IException::Programmer, msg, _FILEINFO_); } }
uint32_t UString::toUInt32(bool *ok) const { double d = toDouble(); bool b = true; if (isNaN(d) || d != static_cast<uint32_t>(d)) { b = false; d = 0; } if (ok) *ok = b; return static_cast<uint32_t>(d); }
unsigned long UString::toULong(bool *ok, bool tolerateEmptyString) const { double d = toDouble(false, tolerateEmptyString); bool b = true; if (isNaN(d) || d != static_cast<unsigned long>(d)) { b = false; d = 0; } if (ok) *ok = b; return static_cast<unsigned long>(d); }
std::map < float, Complex > loadCFloatMap(const std::string & filename){ std::map < float, Complex > aMap; std::fstream file; if (!openInFile(filename, & file)){ std::cerr << WHERE_AM_I << " Map not found: " << filename << std::endl; return aMap; } std::vector < std::string > row; while (!file.eof()) { row = getNonEmptyRow(file); if (row.size() == 3){ aMap[toFloat(row[0])] = Complex(toDouble(row[1]), toDouble(row[2])); } else { if (aMap.size() == 0){ throwError(1, "no proper format found for map <float, Complex> in " + filename + " " + str(row.size()) ); } } } file.close(); return aMap; }
void DoublePropertyWizardPane::updateValue(const QString& text) { auto hdlr = handlerCast<DoublePropertyHandler>(); // verify that value is valid and within range before setting it double value = hdlr->toDouble(text); bool valid = isValidAndInRange(hdlr, text); if (valid && value!=hdlr->value()) { hdlr->setValue(value); emit propertyValueChanged(); } setPropertyConfigured(valid); emit propertyValidChanged(valid); }
bool QueryResultXMLSerializer::unserializeQuery( TiXmlNode* queryNode ) { bool result = true; if (queryNode) { _queryResult.setQuestion ( fromNode( queryNode, "question" ) ); _queryResult.setFilter ( fromNode( queryNode, "filterField" ) ); _queryResult.setFilterValue( fromNode( queryNode, "filterValue" ) ); // _queryResult.setQueryTime ( toDouble( fromNode( queryNode, "queryTook" ) ) ); _queryResult.setQueryTime ( toDouble( fromNode( queryNode, "T" ) ) ); } return result; }
uint32_t UString::toUInt32(bool* ok, bool tolerateEmptyString) const { double d = toDouble(false, tolerateEmptyString); bool b = true; if (d != static_cast<uint32_t>(d)) { b = false; d = 0; } if (ok) *ok = b; return static_cast<uint32_t>(d); }
//! Function to set the selected scale from text // @note added in 2.0 bool QgsScaleComboBox::setScaleString( QString scaleTxt ) { bool ok; double newScale = toDouble( scaleTxt, &ok ); if ( ! ok ) { return false; } else { mScale = newScale; setEditText( toString( mScale ) ); clearFocus(); return true; } }
DepthComboBox::DepthComboBox( QWidget * parent) : QComboBox(parent) { // Add the bedrock and specify depth items addItem(tr("Specify depth...")); addItem(tr("Bedrock")); // Set the insert policy to that "specify depth..." is over-written setInsertPolicy(InsertAtCurrent); setValidator(new QDoubleValidator(this)); setCurrentIndex(-1); connect( this, SIGNAL(currentIndexChanged(int)), SLOT(updateEditable(int))); connect( this, SIGNAL(editTextChanged(QString)), SLOT(toDouble(QString))); }
void OSCDestination::send(QString path, QVariantList payload) { oscpkt::Message message(path.toStdString()); int paramIndex = 0; for (auto it = payload.constBegin(); it != payload.constEnd(); ++it) { auto value = *it; auto type = static_cast<QMetaType::Type>(value.type()); switch (type) { case QMetaType::Bool: message.pushBool(value.toBool()); break; case QMetaType::Int: message.pushInt32(value.toInt()); break; case QMetaType::Double: message.pushDouble(value.toDouble()); break; case QMetaType::QString: message.pushStr(value.toString().toStdString()); break; case QMetaType::Float: message.pushFloat(value.toFloat()); break; case QMetaType::UnknownType: std::cerr << "Unknown parameter type for parameter " << paramIndex << " in message: " << message << std::endl; break; default: std::cerr << "ignoring unhandled type: " << type << " named: " << value.typeName() << " for parameter " << paramIndex << "in message: " << message << std::endl; break; } paramIndex++; } if (!impl) { std::cerr << "not connected to any server (" << url.toString().toStdString() << ")" << std::endl; return; } impl->send(message); }
bool loadValue(const QDomElement &e, QTransform *t) { if (!Private::checkType(e, "transform")) return false; qreal m11 = toDouble(e.attribute("m11", "1.0")); qreal m12 = toDouble(e.attribute("m12", "0.0")); qreal m13 = toDouble(e.attribute("m13", "0.0")); qreal m21 = toDouble(e.attribute("m21", "0.0")); qreal m22 = toDouble(e.attribute("m22", "1.0")); qreal m23 = toDouble(e.attribute("m23", "0.0")); qreal m31 = toDouble(e.attribute("m31", "0.0")); qreal m32 = toDouble(e.attribute("m32", "0.0")); qreal m33 = toDouble(e.attribute("m33", "1.0")); t->setMatrix( m11, m12, m13, m21, m22, m23, m31, m32, m33); return true; }