Beispiel #1
0
void Thesaurus::Lookup(std::string const& word, std::vector<Entry> *out) {
	out->clear();
	if (!dat.get()) return;

	std::map<std::string, int>::const_iterator it = offsets.find(word);
	if (it == offsets.end()) return;

	dat->seekg(it->second, std::ios::beg);
	if (!dat->good()) return;

	// First line is the word and meaning count
	std::string temp;
	getline(*dat, temp);
	std::vector<std::string> header;
	std::string converted(conv->Convert(temp));
	boost::split(header, converted, _1 == '|');
	if (header.size() != 2) return;
	int meanings = atoi(header[1].c_str());

	out->resize(meanings);
	for (int i = 0; i < meanings; ++i) {
		std::vector<std::string> line;
		getline(*dat, temp);
		std::string converted(conv->Convert(temp));
		boost::split(line, converted, _1 == '|');

		// The "definition" is just the part of speech plus the word it's
		// giving synonyms for (which may not be the passed word)
		(*out)[i].first = line[0] + ' ' + line[1];
		(*out)[i].second.reserve(line.size() - 2);
		copy(line.begin() + 2, line.end(), back_inserter((*out)[i].second));
	}
}
Beispiel #2
0
std::shared_ptr<RGBAImage> RGBAImage::down_sample(unsigned int w,
                                                  unsigned int h) const
{
    if (w == 0)
    {
        w = width_ / 2;
    }

    if (h == 0)
    {
        h = weight_ / 2;
    }

    if (width_ <= 1 or weight_ <= 1)
    {
        return nullptr;
    }
    if (width_ == w and weight_ == h)
    {
        return nullptr;
    }
    assert(w <= width_);
    assert(h <= weight_);

    auto bitmap = to_free_image(*this);
    std::unique_ptr<FIBITMAP, FreeImageDeleter> converted(
        FreeImage_Rescale(bitmap.get(), w, h, FILTER_BICUBIC));

    auto img = to_rgba_image(converted.get(), name_);

    return img;
}
Beispiel #3
0
QString QgsField::displayString( const QVariant &v ) const
{
  if ( v.isNull() )
  {
    return QgsApplication::nullRepresentation();
  }

  // Special treatment for numeric types if group separator is set or decimalPoint is not a dot
  if ( d->type == QVariant::Double )
  {
    // Locales with decimal point != '.' or that require group separator: use QLocale
    if ( QLocale().decimalPoint() != '.' ||
         !( QLocale().numberOptions() & QLocale::NumberOption::OmitGroupSeparator ) )
    {
      if ( d->precision > 0 )
      {
        return QLocale().toString( v.toDouble(), 'f', d->precision );
      }
      else
      {
        // Precision is not set, let's guess it from the
        // standard conversion to string
        QString s( v.toString() );
        int dotPosition( s.indexOf( '.' ) );
        int precision;
        if ( dotPosition < 0 )
        {
          precision = 0;
        }
        else
        {
          precision = s.length() - dotPosition - 1;
        }
        return QLocale().toString( v.toDouble(), 'f', precision );
      }
    }
    // Default for doubles with precision
    else if ( d->type == QVariant::Double && d->precision > 0 )
    {
      return QString::number( v.toDouble(), 'f', d->precision );
    }
  }
  // Other numeric types than doubles
  else if ( isNumeric() &&
            !( QLocale().numberOptions() & QLocale::NumberOption::OmitGroupSeparator ) )
  {
    bool ok;
    qlonglong converted( v.toLongLong( &ok ) );
    if ( ok )
      return QLocale().toString( converted );
  }
  else if ( d->typeName == QLatin1String( "json" ) || d->typeName == QLatin1String( "jsonb" ) )
  {
    QJsonDocument doc = QJsonDocument::fromVariant( v );
    return QString::fromUtf8( doc.toJson().data() );
  }
  // Fallback if special rules do not apply
  return v.toString();
}
 Expression::Ptr InstructionDecoderImpl::makeRegisterExpression(MachRegister registerID)
 {
     int newID = registerID.val();
     int minusArch = newID & ~(registerID.getArchitecture());
     int convertedID = minusArch | m_Arch;
     MachRegister converted(convertedID);
     return make_shared(singleton_object_pool<RegisterAST>::construct(converted, 0, registerID.size() * 8));
 }
Beispiel #5
0
 std::string Auxiliary::toString(char * value,
                                 std::string const & error)
 {
     if (value == 0) throw std::runtime_error(error);
     std::string converted(value);
     gaiaFree(value);
     return converted;
 }
Beispiel #6
0
void indri::index::MemoryIndex::_writeFieldExtents( lemur::api::DOCID_T documentID, indri::utility::greedy_vector<indri::parse::TagExtent *>& indexedTags ) {
  indri::utility::HashTable< indri::parse::TagExtent *, int> tagIdMap;
  
  // sort fields
  std::sort( indexedTags.begin(), indexedTags.end(), indri::parse::LessTagExtent() );
  
  // we'll add to the end of the fields greedy_vector
  indri::utility::greedy_vector<indri::index::FieldExtent> & fields = _termList.fields();
  // this is used to set the parentOrdinals
  int offset = fields.size();
  
  // convert to field extents, set ids, and create the node map
  for( size_t i=0; i<indexedTags.size(); i++ ) {
    indri::parse::TagExtent * extent = indexedTags[i];
    
    int ordinal = int(i) + 1;

    // this is the id for the field type
    int tagId = _fieldID( extent->name );
    
    // convert the field
    indri::index::FieldExtent converted( tagId, extent->begin, extent->end, extent->number, ordinal);

    // add this node to the map;
    tagIdMap.insert( extent, ordinal );

    // add his field to the field list for the document
    fields.push_back( converted );

    // add this location to the inverted list for fields - deferred to below - 
    // _fieldLists[tagId - 1]->addLocation( documentID, extent->begin, extent->end, extent->number, ordinal );
  }

  // set the parent ordinals
  for( size_t j=0; j<indexedTags.size(); j++ ) {
    indri::parse::TagExtent * extent = indexedTags[j];
    
    // look up the parent 
    int parentOrdinal = 0;
    int * parentIter;
    if ( extent->parent != 0 ) {
      parentIter = tagIdMap.find( extent->parent );
      if( parentIter != 0 ) {
        parentOrdinal = *parentIter;
      } else {
        parentOrdinal = 0;
      }
    }
    // set the parent
    int ordinal = fields[ offset + j ].ordinal;
    int tagId = fields[ offset + j ].id;
    fields[ offset + j ].parentOrdinal = parentOrdinal;

    // add this location to the inverted list for fields
    _fieldLists[tagId - 1]->addLocation( documentID, extent->begin, extent->end, extent->number, ordinal, parentOrdinal );
  }
}
Beispiel #7
0
	void primeFactorization(const bignum &bn, vector<bignum> &factors)
	{
		if (bn.getDecimalCount() > 0)
			throw error_handler(__FILE__, __LINE__, "Cannot find the prime factorization of a decimal");

		//converts to base 10 first for faster prime checks, then converts base of all prime factors in the list
		if (bn.getBase() != 10)
		{
			bignum converted(bn);
			converted.convertBase(10);

			primeFactorization(converted, factors);

			for (vector<bignum>::iterator i = factors.begin(); i != factors.end(); i++)
				i->convertBase(bn.getBase());

			return;
		}

		if (bn < 0)
		{
			factors.push_back(-1);

			if (bn.absolute().isPrime())
			{
				factors.push_back(bn.absolute());
				return;
			}

			else return primeFactorization(bn.absolute(), factors);
		}

		if (bn.isPrime())
		{
			factors.push_back(1);
			factors.push_back(bn);
			return;
		}

		bignum temp(2);
		while (bn % temp != 0)
			temp++;

		if (!(bn / temp).isPrime())
			primeFactorization(bn / temp, factors);

		else factors.push_back(bn / temp);

		if (!temp.isPrime())
			primeFactorization(temp, factors);

		else factors.push_back(temp);
	}
FastFormatUnicode &FastFormatUnicode::WriteV(const char *fmt, va_list argptr)
{
    wxString converted(fromUTF8(FastFormatAscii().WriteV(fmt, argptr)));

    const uint inspos = m_Length;
    const uint convLen = converted.Length();
    m_dest.MakeRoomFor((inspos + convLen + 64) * sizeof(wxChar));
    memcpy(&((wxChar *)m_dest.GetPtr())[inspos], converted.wc_str(), (convLen + 1) * sizeof(wxChar));
    m_Length += convLen;

    return *this;
}
Beispiel #9
0
NS_IMETHODIMP
URLSearchParams::GetSendInfo(nsIInputStream** aBody, uint64_t* aContentLength,
                             nsACString& aContentType, nsACString& aCharset)
{
  aContentType.AssignLiteral("application/x-www-form-urlencoded");
  aCharset.AssignLiteral("UTF-8");

  nsAutoString serialized;
  Serialize(serialized);
  NS_ConvertUTF16toUTF8 converted(serialized);
  *aContentLength = converted.Length();
  return NS_NewCStringInputStream(aBody, converted);
}
Beispiel #10
0
void test_CNamedPipeWrap_simple(IUnitTest* _ts)
{
	//TEST_SUITE(_ts,);
	TEST_SUITE(_ts,_T("Pipe"),_T("CNamedPipeWrap class tests"));

	CNamedPipeWrap serverpipe;
	CNamedPipeWrap clientpipe;

	const LPCTSTR szPipeName = _T("test_pipe");

	CEvent stopevnt(FALSE,TRUE);

	ok(serverpipe.create(szPipeName,stopevnt,PIPE_ACCESS_INBOUND,PIPE_READMODE_BYTE|PIPE_TYPE_BYTE,false),_T("server pipe create error"));
	ok(clientpipe.open(_T("."),szPipeName,GENERIC_WRITE,NMPWAIT_USE_DEFAULT_WAIT,PIPE_READMODE_BYTE,false),_T("client pipe open error"));

	bool bstoped = false;
	ok(serverpipe.connect(bstoped) && !bstoped,_T("server pipe connect error"));

	CString data(_T("0123456789"));

	string_converter<TCHAR,WCHAR> converted(data);
	DWORD dwMetaData = PDM_Data;
	ok(clientpipe.write_pipe((LPVOID)(LPCWSTR)converted,converted.get_length()*sizeof(WCHAR),dwMetaData),_T("client pipe write failed"));

	LPVOID pbuf = NULL;
	DWORD sz = 0;
	DWORD dwReadedMetaData = PDM_Null;
	ok(serverpipe.read_pipe(pbuf,sz,dwReadedMetaData,true),_T("server pipe read data failed"));
	ok(sz!=0,_T("server pipe read data failed (size == 0)"));
	ok(EQL(dwReadedMetaData,dwMetaData),_T("server pipe data differnt in meta type"));

	CString readed = string_converter<WCHAR,TCHAR>((WCHAR*)pbuf,sz/sizeof(WCHAR));
	ok(!readed.Compare(data),_T("readed by server pipe data not equal to written by client pipe data"));

	delete[] trace_free(pbuf);

	pbuf = NULL;
	ok(clientpipe.write_pipe(pbuf,0,PDM_Data),_T("client pipe write error"));

	pbuf = NULL;
	sz = 0;
	dwReadedMetaData = PDM_Null;
	ok(serverpipe.read_pipe(pbuf,sz,dwReadedMetaData,true),_T("server pipe read data failed"));

	delete[] trace_free(pbuf);

	ok(serverpipe.disconnect(),_T("service pipe disconnect error"));

	clientpipe.close();
	serverpipe.close();
}
Beispiel #11
0
fastuidraw::ivec2
load_image_to_array(const SDL_Surface *img,
		    std::vector<fastuidraw::u8vec4> &out_bytes,
		    bool flip)
{

  SDL_Surface *converted(NULL);
  SDL_Surface *q;
  fastuidraw::ivec2 R;

  if(img==NULL)
    {
      return fastuidraw::ivec2(0,0);
    }

  if( (img->format->BytesPerPixel != 4 ) || // Different bpp
      (img->format->Rshift > img->format->Bshift)) // ABGR/BGR
    {
      SDL_PixelFormat tgt_fmt;

      std::memset(&tgt_fmt, 0, sizeof(tgt_fmt));
      tgt_fmt.palette = NULL;
      tgt_fmt.BytesPerPixel = 4;
      tgt_fmt.BitsPerPixel =  tgt_fmt.BytesPerPixel * 8;

      tgt_fmt.Rshift = 0;
      tgt_fmt.Gshift = 8;
      tgt_fmt.Bshift = 16;
      tgt_fmt.Ashift = 24;
      tgt_fmt.Rmask = 0x000000FF;
      tgt_fmt.Gmask = 0x0000FF00;
      tgt_fmt.Bmask = 0x00FF0000;
      tgt_fmt.Amask = 0xFF000000;
      converted = SDL_ConvertSurface(const_cast<SDL_Surface*>(img), &tgt_fmt, SDL_SWSURFACE);
      q=converted;
    }
  else
    {
      q=const_cast<SDL_Surface*>(img);
    }

  R=load_image_worker(q, out_bytes, flip);

  if(converted!=NULL)
    {
      SDL_FreeSurface(converted);
    }

  return R;
}
Beispiel #12
0
void QRCodeScanner::NewFrameSampled(void *buffer, int width, int height, long size)
{
	Image img(width, height, "YUY2", buffer, size);
	Image converted(img.convert(Y800));

	int result = scanner->scan(converted);
	if(result == 0) lastResult = std::string();

	for (Image::SymbolIterator symbol = converted.symbol_begin(); symbol != converted.symbol_end(); ++symbol) {
		if(symbol->get_data() != lastResult)
		{
			lastResult = symbol->get_data();
			ShellExecuteA(NULL, "open", lastResult.c_str(), NULL, NULL, SW_SHOWNORMAL);
		}
	}
}
ofxRPiCameraVideoGrabber::ofxRPiCameraVideoGrabber()
{
	OMX_Maps::getInstance(); 
    resetValues();
    
    int zoomStepsSource[61] = 
    {
        65536,  68157,  70124,  72745,
        75366,  77988,  80609,  83231,
        86508,  89784,  92406,  95683,
        99615,  102892, 106168, 110100,
        114033, 117965, 122552, 126484,
        131072, 135660, 140247, 145490,
        150733, 155976, 161219, 167117,
        173015, 178913, 185467, 192020,
        198574, 205783, 212992, 220201,
        228065, 236585, 244449, 252969,
        262144, 271319, 281149, 290980,
        300810, 311951, 322437, 334234,
        346030, 357827, 370934, 384041,
        397148, 411566, 425984, 441057,
        456131, 472515, 488899, 506593,
        524288
    };
    vector<int> converted(zoomStepsSource, 
                          zoomStepsSource + sizeof zoomStepsSource / sizeof zoomStepsSource[0]);
    zoomLevels = converted;

    
    cropRectangle.set(0,0,100,100);

    hasAddedExithandler = false;
	updateFrameCounter = 0;
	frameCounter = 0;
	hasNewFrame = false;
	textureEngine = NULL;
	directEngine = NULL;
    camera = NULL;
	pixelsRequested = false;
    recordingRequested = false;
	ofAddListener(ofEvents().update, this, &ofxRPiCameraVideoGrabber::onUpdate);    
}
Beispiel #14
0
void RGBAImage::write_to_file(const std::string &filename) const
{
    const auto file_type = FreeImage_GetFIFFromFilename(filename.c_str());
    if (FIF_UNKNOWN == file_type)
    {
        throw RGBImageException("Can't save to unknown filetype '" +
                                filename + "'");
    }

    auto bitmap = to_free_image(*this);

    FreeImage_SetTransparent(bitmap.get(), false);
    std::unique_ptr<FIBITMAP, FreeImageDeleter> converted(
        FreeImage_ConvertTo24Bits(bitmap.get()));

    const bool result =
        !!FreeImage_Save(file_type, converted.get(), filename.c_str());
    if (not result)
    {
        throw RGBImageException("Failed to save to '" + filename + "'");
    }
}
Beispiel #15
0
void plugin::eventPeriodic ( const QString& id_, const QString& sceneid_, const QString& time, const QVariantList& days) {
    if (sceneid_.isEmpty()) {
        removeEvent(id_);
        return;
    }

    if (days.size()<7)
        return;

    QBitArray converted(7);
    for (int i=0; i < 7; ++i) {
        converted.setBit(i, days.at(i).toBool());
    }

    // recalculate next event
    EventTimeStructure s;
    s.eventid = id_;
    s.sceneid = sceneid_;
    s.time = QTime::fromString(time, QLatin1String("h:m"));
    s.days = converted;
    calculate_next_periodic_timeout(s);
}
Beispiel #16
0
// TODO: similar functions already exist in .cpp file for tgt::FileSystem within an
// anonymous namespace. Keeping these functions somewhere where they would be more
// accessible and recyclable would be preferable... (dirk)
//
std::string ZipArchive::adjustDirectoryStyle(const std::string& directory) const {
    if (directory.empty() == true)
        return "";

    std::string converted(directory);
    size_t offsetStart = 0;
    size_t numChars = directory.size();

    // Convert backslashes '\\' to slashes '/'
    //
    for (size_t i = 0; i < directory.size(); ++i) {
        if (converted[i] == '\\')
            converted[i] = '/';
        else if (converted[i] == ':')
            offsetStart = (i + 2);

        // Remove leading slashes
        //
        if ((converted[i] == '/') && (i == offsetStart))
            ++offsetStart;
    }

    // Append trailing slash if not present.
    //
    if ((numChars > 0) && (converted[numChars - 1] != '/')) {
        converted += "/";
        ++numChars;
    }

    // Remove drive letter, colon and slash if present in windows OS
    //
    if ((offsetStart > 0) && (offsetStart < numChars))
        converted = converted.substr(offsetStart, numChars);

    // Convert to lower case
    //
    std::transform(converted.begin(), converted.end(), converted.begin(), tolower);
    return converted;
}
Beispiel #17
0
std::string convert_from_string16(const android::String16& string16) {
  android::String8 string8(string16);
  std::string converted(string8.string());
  return converted;
}
void                                                                               
install_deb(const char *deb,
            void (*converted)(double *percent, void *arg, const char *filename),
            void (*problem)(char *prob, void *arg),
            void *arg)
{
    double percent = .0;
    char *meta = NULL;
	char *v1 = NULL, *v2 = NULL, *v3 = NULL;
	gchar *package = NULL;
    gchar *version = NULL;
    gchar *arch = NULL;
    char out[PATH_MAX] = { '\0' };

    m_arg = arg;
    m_problem = problem;

	m_buildroot = tmpnam(NULL);
	meta = tmpnam(NULL);
    if (!m_buildroot || !meta) {
        printf("ERROR: failed to create temporary directory\n");
        m_problem(_("ERROR: failed to create temporary directory"), arg);
        goto exit;
    }
#ifdef DEBUG
    printf("buildroot: %s\nmeta: %s\n", m_buildroot, meta);
#endif

	deb_extract(deb, m_buildroot);
	percent = 0.2;
    converted(&percent, m_arg, out);
    deb_control(deb, meta);
    percent = 0.4;
    converted(&percent, m_arg, out);

	v1 = malloc(256);
	v2 = malloc(256);
	v3 = malloc(256);
    if (!v1 || !v2 || !v3) {
        printf("ERROR: failed to allocate memory\n");
        m_problem(_("ERROR: failed to allocate memory"), arg);
        goto exit;
    }

	if (deb_info(deb, meta, "Package", v1) == -1)
        goto exit;
    package = g_utf8_substring(v1, 9, strlen(v1) - 1);
    if (deb_info(deb, meta, "Version", v2) == -1)
        goto exit;
    version = g_utf8_substring(v2, 9, strlen(v2) - 1);
	if (deb_info(deb, meta, "Architecture", v3) == -1)
        goto exit;
    arch = g_utf8_substring(v3, 14, strlen(v3) - 1);

    m_apkg = app_pkg_new();
    if (!m_apkg) {
        printf("ERROR: failed to instance AppPkg object\n");
        goto exit;
    }
    app_pkg_set_name(m_apkg, package);
    app_pkg_set_version(m_apkg, version);
    app_pkg_set_release(m_apkg, "1");
    if (strstr(v3, "amd64"))
        app_pkg_set_arch(m_apkg, "x86_64");
    else
        app_pkg_set_arch(m_apkg, arch);

	deb_info(deb, meta, "Homepage", v1);
	app_pkg_set_url(m_apkg, v1);

	deb_info(deb, meta, "Section", v1);
	app_pkg_set_group(m_apkg, v1);

	deb_info(deb, meta, "Description", v1);
	char *p = strchr(v1, '\n');
	*p = '\0';
	app_pkg_set_summary(m_apkg, v1);
	app_pkg_set_description(m_apkg, p+1);

	app_pkg_set_packager(m_apkg, "isoft-packager");
    percent = 0.6;
    converted(&percent, m_arg, out);

    for (int i = 0; m_dirtyfiles[i]; i++) {
        memset(out, 0, sizeof(out));
        snprintf(out, sizeof(out) - 1, "%s/%s", m_buildroot, m_dirtyfiles[i]);
        unlink(out);
    }
	traverse_directory(m_buildroot);
    memset(out, 0, sizeof(out));
    snprintf(out, sizeof(out) - 1, "%s.rpm", deb);
    app_pkg_write(m_apkg, m_buildroot, out);
    percent = 0.8;
    converted(&percent, m_arg, out);

    percent = 1.0;
    converted(&percent, m_arg, out);

exit:
    if (package) {
        g_free(package);
        package = NULL;
    }

    if (version) {
        g_free(version);
        version = NULL;
    }

    if (arch) {
        g_free(arch);
        arch = NULL;
    }

    if (m_apkg) {
        app_pkg_free(m_apkg);
        m_apkg = NULL;
    }
}
Beispiel #19
0
 virtual NumericType fromInternalValue(boost::units::quantity<InternalUnit, NumericType> internalValue) const
 {
     boost::units::quantity<Unit, NumericType> converted(internalValue);
     return converted.value();
 }
void
ServiceWorkerJob::Finish(nsresult aRv)
{
  ErrorResult converted(aRv);
  Finish(converted);
}
Quantity QuantityConverterSingleton::m_convertFromSI(const Quantity &original,
                                                     const UnitSystem targetSys) const
{
  Quantity working(original);

  // Make sure to work unscaled: 10^0
  int scaleExponent = working.scale().exponent;
  if (working.scale().exponent != 0) {
    working.setScale(0);
  }
  Quantity converted(working.value(),targetSys);

  UnitSystemConversionMultiMap::const_iterator factorItr;
  // m_fromSImap is a multi-map, so get the range of values that match the key 'targetSys'
  std::pair<UnitSystemConversionMultiMap::const_iterator, UnitSystemConversionMultiMap::const_iterator> systemFactors;
  systemFactors = m_fromSIBySystemMap.equal_range( targetSys );
  for( factorItr = systemFactors.first; factorItr != systemFactors.second; ++factorItr) {
    baseUnitConversionFactor fromFactor = (*factorItr).second;
    int workingExp = working.baseUnitExponent(fromFactor.originalUnit);
    if (fromFactor.offset != 0.0) {
      for( int i=0; i < std::abs(workingExp); ++i ) {
        if( workingExp > 0 ) {
          converted.setValue( (converted.value() * fromFactor.factor) + fromFactor.offset );
        }
        else {
          converted.setValue( (converted.value() / fromFactor.factor) + fromFactor.offset );
        }
      }
    }
    else {
      converted.setValue(converted.value() * std::pow(fromFactor.factor,workingExp) );
    }
    // Parse the conversion string incase the SI unit converts to more than one target base unit
    Unit targetBase = parseUnitString(fromFactor.targetUnit);
    std::vector<std::string> targetStrings = targetBase.baseUnits();
    std::vector<std::string>::const_iterator targetItr = targetStrings.begin();
    std::vector<std::string>::const_iterator targetEnd = targetStrings.end();
    while( targetItr != targetEnd ) {
      int exp = targetBase.baseUnitExponent( *targetItr );
      if( exp != 0) {
        converted.setBaseUnitExponent(*targetItr,converted.baseUnitExponent(*targetItr) + 
                                                 workingExp*exp);
      }
      ++targetItr;
    }//End while( convItr != targetEnd )
  }

  // Set result scale to match original scale
  if( scaleExponent != 0 ) {
    converted.setScale(scaleExponent);
  }

  // Check if there is a pretty string for the result
  std::string pretty = UnitFactory::instance().lookupPrettyString(
    converted.standardUnitsString(false) );
  if( !(pretty.empty()) ) {
    converted.setPrettyUnitsString( pretty );
  }

  return converted;
}
Beispiel #22
0
/**
   \note This implementation cannot be used because the extension is omitted
   when the exploer hides the extension of registered file types.
   \todo Support the case where the exploer hides the extension of registered file types.
*/
std::string toActualPathName(const std::string& path)
{
    int codepage = _getmbcp();
    size_t length = ::MultiByteToWideChar(codepage, 0, path.c_str(), path.size(), NULL, 0);
    if(length >= 0){
        wchar_t wpath[MAX_PATH];
        ::MultiByteToWideChar(codepage, 0, path.c_str(), path.size(), wpath, MAX_PATH);
        
        // The following code was based on the code posted at
        // http://stackoverflow.com/questions/74451/getting-actual-file-name-with-proper-casing-on-windowsis
        // Thank you.
        
        const wchar_t kSeparator = L'\\';
        size_t i = 0;
        std::wstring result;
        
        // for network paths (\\server\share\RestOfPath), getting the display
        // name mangles it into unusable form (e.g. "\\server\share" turns
        // into "share on server (server)"). So detect this case and just skip
        // up to two path components
        if( length >= 2 && wpath[0] == kSeparator && wpath[1] == kSeparator ) {
            int skippedCount = 0;
            i = 2; // start after '\\'
            while( i < length && skippedCount < 2 ) {
                if( wpath[i] == kSeparator ){
                    ++skippedCount;
                }
                ++i;
            }
            result.append( wpath, i );
        }
        // for drive names, just add it uppercased
        else if( length >= 2 && wpath[1] == L':' ) {
            result += towupper(wpath[0]);
            result += L':';
            if( length >= 3 && wpath[2] == kSeparator ){
                result += kSeparator;
                i = 3; // start after drive, colon and separator
            } else {
                i = 2; // start after drive and colon
            }
        }
        
        size_t lastComponentStart = i;
        bool addSeparator = false;
        
        while( i < length ) {
            // skip until path separator
            while( i < length && wpath[i] != kSeparator ) {
                ++i;
            }
            if( addSeparator ) {
                result += kSeparator;
            }
            
            // if we found path separator, get real filename of this
            // last path name component
            bool foundSeparator = (i < length);
            wpath[i] = 0;
            SHFILEINFOW info;
            
            // nuke the path separator so that we get real name of current path component
            info.szDisplayName[0] = 0;
            if( SHGetFileInfoW( wpath, 0, &info, sizeof(info), SHGFI_DISPLAYNAME ) ) {
                result += info.szDisplayName;
            } else {
                // most likely file does not exist.
                // So just append original path name component.
                result.append( wpath + lastComponentStart, i - lastComponentStart );
            }
            
            // restore path separator that we might have nuked before
            if( foundSeparator ){
                wpath[i] = kSeparator;
            }
            
            ++i;
            lastComponentStart = i;
            addSeparator = true;
        }
        
        length = ::WideCharToMultiByte(codepage, 0,  &result[0], result.size(), NULL, 0, NULL, NULL);
        if(length >= 0){
            std::vector<char> converted(length + 1);
            ::WideCharToMultiByte(codepage, 0,  &result[0], result.size(), &converted[0], length + 1, NULL, NULL);
            return std::string(&converted[0], length);
        }
    }
    return path; // failed
}
boost::optional<Quantity> QuantityConverterSingleton::m_convertToTargetFromSI(
    const Quantity& original,const Unit& targetUnits) const
{
  Quantity working(original);

  // Make sure to work unscaled: 10^0
  if (working.scale().exponent != 0) {
    working.setScale(0);
  }
  Quantity converted(working.value(),targetUnits.system());

  if ((working.units() == targetUnits) &&
      (working.system() == targetUnits.system()))
  {
    converted = working;
  }
  else {
    // Get the base units of targetUnits
    std::vector<std::string> baseOfTarget = targetUnits.baseUnits();
    // Loop over base units in original and apply (inverse of) conversions in m_toSImap
    std::vector<std::string>::const_iterator it = baseOfTarget.begin();
    std::vector<std::string>::const_iterator end = baseOfTarget.end();
    while( it != end ) {
      int baseExponent = targetUnits.baseUnitExponent(*it);
      // apply conversion factor
      BaseUnitConversionMap::const_iterator mapItr = m_toSImap.find(*it);
      if (mapItr == m_toSImap.end()) {
        LOG(Error,"Cannot convert to a target Unit containing base unit '" << *it
            << "', because it is not registered with the QuantityConverter.");
        return boost::none;
      }
      baseUnitConversionFactor factor = m_toSImap.find(*it)->second;
      if (factor.offset != 0.0) {
        for( int i = 0; i < std::abs(baseExponent); ++i) {
          if( baseExponent > 0 ){
            converted.setValue( (converted.value() - factor.offset) / factor.factor);
          }else {
            converted.setValue( (converted.value() - factor.offset) * factor.factor);
          }
        }
      }
      else {
        converted.setValue( converted.value() * std::pow(factor.factor,-baseExponent) );
      }
      // Set units in converted
      converted.setBaseUnitExponent(*it,
                                    converted.baseUnitExponent(*it) + baseExponent);
      // Monitor left over units in working
      // Parse the conversion string in case the target converts to more than one SI base unit
      Unit sourceBase = parseUnitString(factor.targetUnit);
      std::vector<std::string> sourceStrings = sourceBase.baseUnits();
      std::vector<std::string>::const_iterator sourceItr = sourceStrings.begin();
      std::vector<std::string>::const_iterator sourceEnd = sourceStrings.end();
      while( sourceItr != sourceEnd ) {
        int exp = sourceBase.baseUnitExponent( *sourceItr );
        if( exp != 0 ) {
          working.setBaseUnitExponent(*sourceItr,
                                      working.baseUnitExponent(*sourceItr) - baseExponent*exp);
        }
        ++sourceItr;
      } // end while( sourceItr != sourceEnd )
      ++it;
    }

    if (!working.standardUnitsString().empty()) {
      LOG(Error,"Could not convert " << original << " to " << targetUnits
          << ". Have " << working.standardUnitsString() << "left over.");
      return boost::none;
    }
  }

  // Set result scale to match targetUnits scale
  if (targetUnits.scale().exponent != 0) {
    converted.setScale(targetUnits.scale().exponent);
  }

  // Check if there is a pretty string for the result
  std::string pretty = UnitFactory::instance().lookupPrettyString(
    converted.standardUnitsString(false) );
  if( !(pretty.empty()) ) {
    converted.setPrettyUnitsString( pretty );
  }

  return converted;
}
void
ServiceWorkerJob::InvokeResultCallbacks(nsresult aRv)
{
  ErrorResult converted(aRv);
  InvokeResultCallbacks(converted);
}