double FayyadMdlDiscretizer::_calculateEntropy(int start, int size)
  {
    assert(start + size <= (int)_classes->size());
    assert(start >= 0);
    const std::vector<int>& classes = *_classes;

    HashMap<int, int> frequency;

    HashMap<int, int>::const_iterator it;
    for (int i = start; i < start + size; i++)
    {
      it = frequency.find(classes[i]);
      if (it == frequency.end())
      {
        frequency[classes[i]] = 1;
      }
      else
      {
        int tmp = it->second;
        frequency[classes[i]] = tmp + 1;
      }
    }

    double entropy = 0.0;
    for (it = frequency.begin(); it != frequency.end(); it++)
    {
      double proportion = (double)it->second / (double)size;
      entropy += proportion * log(proportion) / log2;
    }

    return -entropy;
  }
  void testIterator ()
  {
    map->put ((char*)"zero", 0);
    map->put ((char*)"one", 1);
    map->put ((char*)"two", 2);
    map->put ((char*)"three", 3);
    map->put ((char*)"four", 4);
    map->put ((char*)"five", 5);
    map->put ((char*)"six", 6);
    map->put ((char*)"seven", 7);
    map->put ((char*)"eight", 8);
    map->put ((char*)"nine", 9);
    map->put ((char*)"ten", 10);

    int values[11];

    for (int i = 0; i < 11; i++)
      values[i] = 0;

    for (HashMap<char*, int>::Iterator it = map->begin (); it != map->end (); it++)
    {
      values[*it] = 1;
    }

    for (int i = 0; i < 11; i++)
      CPPUNIT_ASSERT_EQUAL (values[i], 1);
  }
Esempio n. 3
0
PassRefPtr<Widget> SubframeLoader::createJavaAppletWidget(const IntSize& size, HTMLAppletElement* element, const HashMap<String, String>& args)
{
    String baseURLString;
    String codeBaseURLString;
    Vector<String> paramNames;
    Vector<String> paramValues;
    HashMap<String, String>::const_iterator end = args.end();
    for (HashMap<String, String>::const_iterator it = args.begin(); it != end; ++it) {
        if (equalIgnoringCase(it->first, "baseurl"))
            baseURLString = it->second;
        else if (equalIgnoringCase(it->first, "codebase"))
            codeBaseURLString = it->second;
        paramNames.append(it->first);
        paramValues.append(it->second);
    }

    if (!codeBaseURLString.isEmpty()) {
        KURL codeBaseURL = completeURL(codeBaseURLString);
        if (!SecurityOrigin::canLoad(codeBaseURL, String(), element->document())) {
            FrameLoader::reportLocalLoadFailed(m_frame, codeBaseURL.string());
            return 0;
        }
    }

    if (baseURLString.isEmpty())
        baseURLString = m_frame->document()->baseURL().string();
    KURL baseURL = completeURL(baseURLString);

    RefPtr<Widget> widget = m_frame->loader()->client()->createJavaAppletWidget(size, element, baseURL, paramNames, paramValues);
    if (!widget)
        return 0;

    m_containsPlugins = true;
    return widget;
}
void WebNotificationManagerProxy::providerDidCloseNotifications(API::Array* globalNotificationIDs)
{
    HashMap<WebPageProxy*, Vector<uint64_t>> pageNotificationIDs;
    
    size_t size = globalNotificationIDs->size();
    for (size_t i = 0; i < size; ++i) {
        auto it = m_globalNotificationMap.find(globalNotificationIDs->at<API::UInt64>(i)->value());
        if (it == m_globalNotificationMap.end())
            continue;

        if (WebPageProxy* webPage = WebProcessProxy::webPage(it->value.first)) {
            auto pageIt = pageNotificationIDs.find(webPage);
            if (pageIt == pageNotificationIDs.end()) {
                Vector<uint64_t> newVector;
                newVector.reserveInitialCapacity(size);
                pageIt = pageNotificationIDs.add(webPage, WTF::move(newVector)).iterator;
            }

            uint64_t pageNotificationID = it->value.second;
            pageIt->value.append(pageNotificationID);
        }

        m_notifications.remove(it->value);
        m_globalNotificationMap.remove(it);
    }

    for (auto it = pageNotificationIDs.begin(), end = pageNotificationIDs.end(); it != end; ++it)
        it->key->process().send(Messages::WebNotificationManager::DidCloseNotifications(it->value), 0);
}
Esempio n. 5
0
void LocalStorageDatabase::updateDatabaseWithChangedItems(const HashMap<String, String>& changedItems)
{
    if (!m_database.isOpen())
        openDatabase(CreateIfNonExistent);
    if (!m_database.isOpen())
        return;

    if (m_shouldClearItems) {
        m_shouldClearItems = false;

        SQLiteStatement clearStatement(m_database, "DELETE FROM ItemTable");
        if (clearStatement.prepare() != SQLITE_OK) {
            LOG_ERROR("Failed to prepare clear statement - cannot write to local storage database");
            return;
        }

        int result = clearStatement.step();
        if (result != SQLITE_DONE) {
            LOG_ERROR("Failed to clear all items in the local storage database - %i", result);
            return;
        }
    }

    SQLiteStatement insertStatement(m_database, "INSERT INTO ItemTable VALUES (?, ?)");
    if (insertStatement.prepare() != SQLITE_OK) {
        LOG_ERROR("Failed to prepare insert statement - cannot write to local storage database");
        return;
    }

    SQLiteStatement deleteStatement(m_database, "DELETE FROM ItemTable WHERE key=?");
    if (deleteStatement.prepare() != SQLITE_OK) {
        LOG_ERROR("Failed to prepare delete statement - cannot write to local storage database");
        return;
    }

    SQLiteTransaction transaction(m_database);
    transaction.begin();

    for (auto it = changedItems.begin(), end = changedItems.end(); it != end; ++it) {
        // A null value means that the key/value pair should be deleted.
        SQLiteStatement& statement = it->value.isNull() ? deleteStatement : insertStatement;

        statement.bindText(1, it->key);

        // If we're inserting a key/value pair, bind the value as well.
        if (!it->value.isNull())
            statement.bindBlob(2, it->value);

        int result = statement.step();
        if (result != SQLITE_DONE) {
            LOG_ERROR("Failed to update item in the local storage database - %i", result);
            break;
        }

        statement.reset();
    }

    transaction.commit();
}
void StorageAreaSync::performImport()
{
    ASSERT(!isMainThread());
    ASSERT(!m_database.isOpen());

    String databaseFilename = m_syncManager->fullDatabaseFilename(m_storageArea->securityOrigin());

    if (databaseFilename.isEmpty()) {
        LOG_ERROR("Filename for local storage database is empty - cannot open for persistent storage");
        markImported();
        return;
    }

    if (!m_database.open(databaseFilename)) {
        LOG_ERROR("Failed to open database file %s for local storage", databaseFilename.utf8().data());
        markImported();
        return;
    }

    if (!m_database.executeCommand("CREATE TABLE IF NOT EXISTS ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value TEXT NOT NULL ON CONFLICT FAIL)")) {
        LOG_ERROR("Failed to create table ItemTable for local storage");
        markImported();
        return;
    }
    
    SQLiteStatement query(m_database, "SELECT key, value FROM ItemTable");
    if (query.prepare() != SQLResultOk) {
        LOG_ERROR("Unable to select items from ItemTable for local storage");
        markImported();
        return;
    }
    
    HashMap<String, String> itemMap;

    int result = query.step();
    while (result == SQLResultRow) {
        itemMap.set(query.getColumnText(0), query.getColumnText(1));
        result = query.step();
    }

    if (result != SQLResultDone) {
        LOG_ERROR("Error reading items from ItemTable for local storage");
        markImported();
        return;
    }

    MutexLocker locker(m_importLock);
    
    HashMap<String, String>::iterator it = itemMap.begin();
    HashMap<String, String>::iterator end = itemMap.end();
    
    for (; it != end; ++it)
        m_storageArea->importItem(it->first, it->second);
    
    // Break the (ref count) cycle.
    m_storageArea = 0;
    m_importComplete = true;
    m_importCondition.signal();
}
Esempio n. 7
0
void findGoodTouchTargets(const IntRect& touchBox, LocalFrame* mainFrame, Vector<IntRect>& goodTargets, Vector<Node*>& highlightNodes)
{
    goodTargets.clear();

    int touchPointPadding = ceil(max(touchBox.width(), touchBox.height()) * 0.5);

    IntPoint touchPoint = touchBox.center();
    IntPoint contentsPoint = mainFrame->view()->windowToContents(touchPoint);

    HitTestResult result = mainFrame->eventHandler().hitTestResultAtPoint(contentsPoint, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent, IntSize(touchPointPadding, touchPointPadding));
    const ListHashSet<RefPtr<Node> >& hitResults = result.rectBasedTestResult();

    // Blacklist nodes that are container of disambiguated nodes.
    // It is not uncommon to have a clickable <div> that contains other clickable objects.
    // This heuristic avoids excessive disambiguation in that case.
    HashSet<Node*> blackList;
    for (ListHashSet<RefPtr<Node> >::const_iterator it = hitResults.begin(); it != hitResults.end(); ++it) {
        // Ignore any Nodes that can't be clicked on.
        RenderObject* renderer = it->get()->renderer();
        if (!renderer || !it->get()->willRespondToMouseClickEvents())
            continue;

        // Blacklist all of the Node's containers.
        for (RenderBlock* container = renderer->containingBlock(); container; container = container->containingBlock()) {
            Node* containerNode = container->node();
            if (!containerNode)
                continue;
            if (!blackList.add(containerNode).isNewEntry)
                break;
        }
    }

    HashMap<Node*, TouchTargetData> touchTargets;
    float bestScore = 0;
    for (ListHashSet<RefPtr<Node> >::const_iterator it = hitResults.begin(); it != hitResults.end(); ++it) {
        for (Node* node = it->get(); node; node = node->parentNode()) {
            if (blackList.contains(node))
                continue;
            if (node->isDocumentNode() || isHTMLHtmlElement(*node) || isHTMLBodyElement(*node))
                break;
            if (node->willRespondToMouseClickEvents()) {
                TouchTargetData& targetData = touchTargets.add(node, TouchTargetData()).storedValue->value;
                targetData.windowBoundingBox = boundingBoxForEventNodes(node);
                targetData.score = scoreTouchTarget(touchPoint, touchPointPadding, targetData.windowBoundingBox);
                bestScore = max(bestScore, targetData.score);
                break;
            }
        }
    }

    for (HashMap<Node*, TouchTargetData>::iterator it = touchTargets.begin(); it != touchTargets.end(); ++it) {
        // Currently the scoring function uses the overlap area with the fat point as the score.
        // We ignore the candidates that has less than 1/2 overlap (we consider not really ambiguous enough) than the best candidate to avoid excessive popups.
        if (it->value.score < bestScore * 0.5)
            continue;
        goodTargets.append(it->value.windowBoundingBox);
        highlightNodes.append(it->key);
    }
}
Esempio n. 8
0
File: hashmap.cpp Progetto: kayw/mnb
HashMap<Key, T, Hasher, EqualKey, Alloc>::HashMap(const HashMap& rhs)
  :bucket_list_(nullptr)
  ,bucket_count_(rhs.bucket_count() )
  ,size_(rhs.size() )
  ,mlf_(rhs.max_load_factor() )
  ,hash_function_pred_(rhs.hash_function(), rhs.key_equal() ){
    rehash(rhs.bucket_count() );
    insert(rhs.begin(), rhs.end() );
  }
Esempio n. 9
0
    ~_Ewk_Context()
    {
        if (cookieManager)
            ewk_cookie_manager_free(cookieManager);

        HashMap<uint64_t, Ewk_Download_Job*>::iterator it = downloadJobs.begin();
        HashMap<uint64_t, Ewk_Download_Job*>::iterator end = downloadJobs.end();
        for ( ; it != end; ++it)
            ewk_download_job_unref(it->second);
    }
ScriptValue DictionaryTest::getDictionaryMemberProperties(ScriptState* scriptState)
{
    if (!m_dictionaryMemberProperties)
        return ScriptValue();
    V8ObjectBuilder builder(scriptState);
    HashMap<String, String> properties = m_dictionaryMemberProperties.get();
    for (HashMap<String, String>::iterator it = properties.begin(); it != properties.end(); ++it)
        builder.addString(it->key, it->value);
    return builder.scriptValue();
}
void StorageAreaSync::sync(bool clearItems, const HashMap<String, String>& items)
{
    ASSERT(!isMainThread());

    if (!m_database.isOpen())
        return;

    // If the clear flag is set, then we clear all items out before we write any new ones in.
    if (clearItems) {
        SQLiteStatement clear(m_database, "DELETE FROM ItemTable");
        if (clear.prepare() != SQLResultOk) {
            LOG_ERROR("Failed to prepare clear statement - cannot write to local storage database");
            return;
        }
        
        int result = clear.step();
        if (result != SQLResultDone) {
            LOG_ERROR("Failed to clear all items in the local storage database - %i", result);
            return;
        }
    }

    SQLiteStatement insert(m_database, "INSERT INTO ItemTable VALUES (?, ?)");
    if (insert.prepare() != SQLResultOk) {
        LOG_ERROR("Failed to prepare insert statement - cannot write to local storage database");
        return;
    }

    SQLiteStatement remove(m_database, "DELETE FROM ItemTable WHERE key=?");
    if (remove.prepare() != SQLResultOk) {
        LOG_ERROR("Failed to prepare delete statement - cannot write to local storage database");
        return;
    }

    HashMap<String, String>::const_iterator end = items.end();

    for (HashMap<String, String>::const_iterator it = items.begin(); it != end; ++it) {
        // Based on the null-ness of the second argument, decide whether this is an insert or a delete.
        SQLiteStatement& query = it->second.isNull() ? remove : insert;        

        query.bindText(1, it->first);

        // If the second argument is non-null, we're doing an insert, so bind it as the value. 
        if (!it->second.isNull())
            query.bindText(2, it->second);

        int result = query.step();
        if (result != SQLResultDone) {
            LOG_ERROR("Failed to update item in the local storage database - %i", result);
            break;
        }

        query.reset();
    }
}
static void cleanWeakMap(HashMap<K, WeakPtr<M> >& map)
{
    HashMap<K, WeakPtr<M> > other;
    other.swap(map);

    typename HashMap<K, WeakPtr<M> >::const_iterator iter = other.begin();
    while (iter != other.end()) {
        if (iter->value.get())
            map.set(iter->key, iter->value);
        ++iter;
    }
}
void DOMWindowExtensionBasic::willDestroyPage(WKBundleRef, WKBundlePageRef)
{
    HashMap<WKBundleDOMWindowExtensionRef, int>::iterator it = m_extensionToRecordMap.begin();
    HashMap<WKBundleDOMWindowExtensionRef, int>::iterator end = m_extensionToRecordMap.end();
    for (; it != end; ++it) {
        updateExtensionStateRecord(it->key, Removed);
        WKRelease(it->key);
    }

    m_extensionToRecordMap.clear();

    sendExtensionStateMessage();
    sendBundleMessage("TestComplete");
}
Esempio n. 14
0
void PointsToTracksOp::_sortTracks(shared_ptr<OsmMap>& map, HashMap<QString, deque<long> >& tracks)
{

  SortFunctor sf;
  sf.map = map;

  for (HashMap<QString, deque<long> >::iterator it = tracks.begin(); it != tracks.end();
    ++it)
  {
    deque<long>& d = it->second;

    sort(d.begin(), d.end(), sf);
  }
}
Esempio n. 15
0
		/**
		 * Default Destructor.
		 * 
		 * The {@link ParallelSystem} object is destructed when connection with the remote system is closed or this
		 * {@link ParallelSystem} object is {@link ParallelSystemArray.erase erased} from its parent 
		 * {@link ParallelSystemArray} object.
		 * 
		 * You may think if there're some *parallel processes* have requested but not completed yet, then it would be a
		 * critical problem because the *parallel processes* will not complete forever. Do not worry. The critical problem
		 * does not happen. After the destruction, the remained *parallel processes* will be shifted to and proceeded in 
		 * other {@link ParallelSystem} objects.
		 */
		virtual ~ParallelSystem()
		{
			excluded_ = true;

			// SHIFT PARALLEL INVOKE MESSAGES HAD PROGRESSED TO OTHER SLAVES
			for (auto it = progress_list_.begin(); it != progress_list_.end(); it++)
			{
				// INVOKE MESSAGE AND ITS HISTORY ON PROGRESS
				std::shared_ptr<protocol::Invoke> invoke = it->second.first;
				std::shared_ptr<slave::InvokeHistory> history = it->second.second;

				// SEND THEM BACK
				_Send_back_history(invoke, history);
			}
		};
Esempio n. 16
0
void StorageMap::importItems(const HashMap<String, String>& items)
{
    for (HashMap<String, String>::const_iterator it = items.begin(), end = items.end(); it != end; ++it) {
        const String& key = it->key;
        const String& value = it->value;

        HashMap<String, String>::AddResult result = m_map.add(key, value);
        ASSERT_UNUSED(result, result.isNewEntry); // True if the key didn't exist previously.

        ASSERT(m_currentLength + key.length() >= m_currentLength);
        m_currentLength += key.length();
        ASSERT(m_currentLength + value.length() >= m_currentLength);
        m_currentLength += value.length();
    }
}
void WebSocketExtensionDispatcher::appendAcceptedExtension(const String& extensionToken, HashMap<String, String>& extensionParameters)
{
    if (!m_acceptedExtensionsBuilder.isEmpty())
        m_acceptedExtensionsBuilder.appendLiteral(", ");
    m_acceptedExtensionsBuilder.append(extensionToken);
    // FIXME: Should use ListHashSet to keep the order of the parameters.
    for (HashMap<String, String>::const_iterator iterator = extensionParameters.begin(); iterator != extensionParameters.end(); ++iterator) {
        m_acceptedExtensionsBuilder.appendLiteral("; ");
        m_acceptedExtensionsBuilder.append(iterator->key);
        if (!iterator->value.isNull()) {
            m_acceptedExtensionsBuilder.append('=');
            m_acceptedExtensionsBuilder.append(iterator->value);
        }
    }
}
Esempio n. 18
0
CSSSegmentedFontFace* CSSFontSelector::getFontFace(const FontDescription& fontDescription, const AtomicString& family)
{
    HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >* familyFontFaces = m_fontFaces.get(family);
    if (!familyFontFaces || familyFontFaces->isEmpty())
        return 0;

    OwnPtr<HashMap<unsigned, RefPtr<CSSSegmentedFontFace> > >& segmentedFontFaceCache = m_fonts.add(family, nullptr).iterator->value;
    if (!segmentedFontFaceCache)
        segmentedFontFaceCache = adoptPtr(new HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >);

    FontTraitsMask traitsMask = fontDescription.traitsMask();

    RefPtr<CSSSegmentedFontFace>& face = segmentedFontFaceCache->add(traitsMask, 0).iterator->value;
    if (!face) {
        for (HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >::const_iterator i = familyFontFaces->begin(); i != familyFontFaces->end(); ++i) {
            CSSSegmentedFontFace* candidate = i->value.get();
            unsigned candidateTraitsMask = candidate->traitsMask();
            if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
                continue;
            if ((traitsMask & FontVariantNormalMask) && !(candidateTraitsMask & FontVariantNormalMask))
                continue;
#if ENABLE(SVG_FONTS)
            // For SVG Fonts that specify that they only support the "normal" variant, we will assume they are incapable
            // of small-caps synthesis and just ignore the font face as a candidate.
            if (candidate->hasSVGFontFaceSource() && (traitsMask & FontVariantSmallCapsMask) && !(candidateTraitsMask & FontVariantSmallCapsMask))
                continue;
#endif
            if (!face || compareFontFaces(candidate, face.get(), traitsMask))
                face = candidate;
        }

        if (Vector<RefPtr<CSSSegmentedFontFace> >* familyLocallyInstalledFontFaces = m_locallyInstalledFontFaces.get(family)) {
            unsigned numLocallyInstalledFontFaces = familyLocallyInstalledFontFaces->size();
            for (unsigned i = 0; i < numLocallyInstalledFontFaces; ++i) {
                CSSSegmentedFontFace* candidate = familyLocallyInstalledFontFaces->at(i).get();
                unsigned candidateTraitsMask = candidate->traitsMask();
                if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
                    continue;
                if ((traitsMask & FontVariantNormalMask) && !(candidateTraitsMask & FontVariantNormalMask))
                    continue;
                if (!face || compareFontFaces(candidate, face.get(), traitsMask))
                    face = candidate;
            }
        }
    }
    return face.get();
}
Esempio n. 19
0
void syntaxTest_HashMap()
{
    {
        std::pair<int, int> a[] = { std::make_pair(3, 4)};
        HashMap<int, int> m(a, a + 1);
        assert(m.size() == 1);
        assert(!m.empty());
        assert(!m.contain(2));
        assert(m.count(3) == 1);

        HashMap<int, int> m2;
        m2 = m;
        assert(m2.size() == 1);
        assert(m2 == m);
        assert(!(m2 != m));
        m2.erase(3);
        assert(m2.empty());
        assert(m.find(5) == m.end());
        m.erase(m.find(3));
        assert(m.empty());

        HashMap<int, int> m3(a, a + 1);
        assert(m3.size() == 1);
        std::swap(m, m3);
        assert(m3.empty());
        assert(m.size() == 1);
        assert(*m.begin() == std::make_pair(3, 4));
        assert(m.begin()->second == 4);
    }
    {
        HashMap<int, int> m;
        for (int i = 0; i < 100; ++i) {
            ++m[i % 10];
        }
        assert(m[0] == 10);
        assert(m[1] == 10);
    }
    {
        std::pair<int, int> a[] = {std::pair<int, int>(1, 2)};
        const HashMap<int, int> m(a, a + 1);
        assert(m.size() == 1);
        for (HashMap<int, int>::ConstIterator i = m.begin();
                i != m.end();
                ++i) assert(i->first == 1);
    }
}
Esempio n. 20
0
void InspectorTimelineAgent::setNativeHeapStatistics(InspectorObject* record)
{
    if (!m_memoryAgent)
        return;
    if (!m_state->getBoolean(TimelineAgentState::includeNativeMemoryStatistics))
        return;
    HashMap<String, size_t> map;
    m_memoryAgent->getProcessMemoryDistributionMap(&map);
    RefPtr<InspectorObject> stats = InspectorObject::create();
    for (HashMap<String, size_t>::iterator it = map.begin(); it != map.end(); ++it)
        stats->setNumber(it->key, it->value);
    size_t privateBytes = 0;
    size_t sharedBytes = 0;
    MemoryUsageSupport::processMemorySizesInBytes(&privateBytes, &sharedBytes);
    stats->setNumber("PrivateBytes", privateBytes);
    record->setObject("nativeHeapStatistics", stats.release());
}
Esempio n. 21
0
String MIMETypeRegistry::getPreferredExtensionForMIMEType(const String& type)
{
    if (type.isEmpty())
        return String();

    // Avoid conflicts with "ttf" and "otf"
    if (equalIgnoringCase(type, "text/plain"))
        return "txt";

    initMIMETypeEntensionMap();

    for (HashMap<String, String>::iterator i = mimetypeMap.begin(); i != mimetypeMap.end(); ++i) {
        if (equalIgnoringCase(i->value, type))
            return i->key;
    }

    return String();
}
bool MeshSerializerTests::isHashMapClone(const HashMap<K, V>& a, const HashMap<K, V>& b)
{
	// if you recreate a HashMap with same elements, then iteration order may differ!
	// So isContainerClone is not always working on HashMap.
	if (a.size() != b.size()) {
		return false;
	}
	typename HashMap<K, V>::const_iterator it, itFind, itEnd;
	it = a.begin();
	itEnd = a.end();
	for (; it != itEnd; it++) {
		itFind = b.find(it->first);
		if (itFind == b.end() || itFind->second != it->second) {
			return false;
		}
	}
	return true;
}
Esempio n. 23
0
void Registry::ResetProfiles()
{
	ProfileThreadsVec allThreads;
	{
		std::lock_guard<std::mutex> lock(m_ThreadsMutex);
		allThreads = m_ProfiledThreads;
	}

	std::function<void (ProfileScope*)> resetProfilesRecursive = [&](ProfileScope* scope) {
		HashMap childrenCopy = scope->Children();
		std::for_each(childrenCopy.begin(), childrenCopy.end(), [&](ProfileScope* scope){
			resetProfilesRecursive(scope);
		});
		scope->ResetProfile();
	};

	std::for_each(allThreads.begin(), allThreads.end(), [&](ProfileThread* thread){
		resetProfilesRecursive(thread);
	});
}
Esempio n. 24
0
void StorageAreaSync::performImport()
{
    ASSERT(!isMainThread());
    ASSERT(!m_database.isOpen());

    openDatabase(SkipIfNonExistent);
    if (!m_database.isOpen()) {
        markImported();
        return;
    }

    SQLiteStatement query(m_database, "SELECT key, value FROM ItemTable");
    if (query.prepare() != SQLResultOk) {
        LOG_ERROR("Unable to select items from ItemTable for local storage");
        markImported();
        return;
    }

    HashMap<String, String> itemMap;

    int result = query.step();
    while (result == SQLResultRow) {
        itemMap.set(query.getColumnText(0), query.getColumnBlobAsString(1));
        result = query.step();
    }

    if (result != SQLResultDone) {
        LOG_ERROR("Error reading items from ItemTable for local storage");
        markImported();
        return;
    }

    HashMap<String, String>::iterator it = itemMap.begin();
    HashMap<String, String>::iterator end = itemMap.end();

    for (; it != end; ++it)
        m_storageArea->importItem(it->first, it->second);

    markImported();
}
Esempio n. 25
0
void PointsToTracksOp::_createWays(shared_ptr<OsmMap>& map, HashMap<QString, deque<long> >& tracks)
{
  for (HashMap<QString, deque<long> >::const_iterator it = tracks.begin(); it != tracks.end();
    ++it)
  {
    const deque<long>& d = it->second;
    shared_ptr<Node> firstNode = map->getNode(d[0]);

    LOG_INFO("Circular Error: " << firstNode->getCircularError());
    shared_ptr<Way> w(new Way(firstNode->getStatus(), map->createNextWayId(),
      firstNode->getCircularError()));

    // check to see if all the nodes have the same non-empty highway tag.
    QString highway = firstNode->getTags()["highway"];
    for (deque<long>::const_iterator it = d.begin(); highway != "" && it != d.end(); ++it)
    {
      if (map->getNode(*it)->getTags()["highway"] != highway)
      {
        highway = "";
      }
    }

    // if all the nodes have the same non-empty highway tag
    if (highway != "")
    {
      // move the highway tag from the nodes into the way.
      w->getTags()["highway"] = highway;
      for (deque<long>::const_iterator it = d.begin(); highway != "" && it != d.end(); ++it)
      {
        map->getNode(*it)->getTags().remove("highway");
      }
    }

    w->addNodes(d.begin(), d.end());

    map->addWay(w);
  }
}
Esempio n. 26
0
void BenchHashMap(const char *file)
{
	HashMap imap;
	BenchSTL(imap, file);
	vector< const HashMap::value_type * > order;
	for(HashMap::const_iterator i = imap.begin(); i != imap.end(); i++)
		order.push_back(&*i);
	sort(order.begin(), order.end(), h_less);

#ifndef NO_OUTPUT
	vector< const HashMap::value_type * >::const_iterator e = order.end();
	for(vector< const HashMap::value_type * >::const_iterator i = order.begin(); i != e; i++) {
		std::cout << (*i)->first << ": ";
		vector<int>::const_iterator e = (*i)->second.end();
		vector<int>::const_iterator b = (*i)->second.begin();
		for(vector<int>::const_iterator j = b; j != e; j++) {
			if(j != b) std::cout << ", ";
			std::cout << *j;
		}
		std::cout << '\n';
	}
#endif
}
Esempio n. 27
0
void
MaterialPropertyStorageDump(const HashMap<const libMesh::Elem *, HashMap<unsigned int, MaterialProperties> > & props)
{
  // Define the iterators
  HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> >::const_iterator elem_it;
  HashMap<unsigned int, MaterialProperties>::const_iterator side_it;
  MaterialProperties::const_iterator prop_it;

  // Loop through the elements
  for (elem_it = props.begin(); elem_it != props.end(); ++elem_it)
  {
    Moose::out << "Element " << elem_it->first->id() << '\n';

    // Loop through the sides
    for (side_it = elem_it->second.begin(); side_it != elem_it->second.end(); ++side_it)
    {
      Moose::out << "  Side " << side_it->first << '\n';

      // Loop over properties
      unsigned int cnt = 0;
      for (prop_it = side_it->second.begin(); prop_it != side_it->second.end(); ++prop_it)
      {
        MaterialProperty<Real> * mp = dynamic_cast<MaterialProperty<Real> *>(*prop_it);
        if (mp)
        {
          Moose::out << "    Property " << cnt << '\n';
          cnt++;

          // Loop over quadrature points
          for (unsigned int qp = 0; qp < mp->size(); ++qp)
            Moose::out << "      prop[" << qp << "] = " << (*mp)[qp] << '\n';
        }
      }
    }
  }
}
Esempio n. 28
0
void_t Main::controlUserBroker(uint32_t requestId, uint64_t entityId, uint32_t controlCode, const byte_t* data, size_t size)
{
  switch(controlCode)
  {
  case meguco_user_broker_control_refresh_orders:
    {
      List<meguco_user_broker_order_entity> newOrders;
      if(!broker->loadOrders(newOrders))
      {
        addLogMessage(meguco_log_error, broker->getLastError());
        return (void_t)connection.sendControlResponse(requestId, 0);
      }
      Map<int64_t, meguco_user_broker_order_entity*> sortedNewOrders;
      for(List<meguco_user_broker_order_entity>::Iterator i = newOrders.begin(), end = newOrders.end(); i != end; ++i)
        sortedNewOrders.insert((*i).entity.time, &*i);
      HashMap<uint64_t, meguco_user_broker_order_entity> ordersMapByRaw;
      for(HashMap<uint64_t, meguco_user_broker_order_entity>::Iterator i = orders2.begin(), end = orders2.end(); i != end; ++i)
      {
        meguco_user_broker_order_entity& order = *i;
        ordersMapByRaw.append(order.raw_id, order);
      }
      orders2.clear();
      for(Map<int64_t, meguco_user_broker_order_entity*>::Iterator i = sortedNewOrders.begin(), end = sortedNewOrders.end(); i != end; ++i)
      {
        meguco_user_broker_order_entity& order = **i;
        HashMap<uint64_t, meguco_user_broker_order_entity>::Iterator it = ordersMapByRaw.find(order.raw_id);
        if(it == ordersMapByRaw.end() || it->entity.id == 0)
        { // add
          uint64_t id;
          if(connection.add(userBrokerOrdersTableId, order.entity, id))
          {
            order.entity.id = id;
            orders2.append(order.entity.id, order);
          }
        }
        else
        { // update
          order.entity.id = it->entity.id;
          if(Memory::compare(&*it, &order, sizeof(order)) != 0 &&
             connection.update(userBrokerOrdersTableId, order.entity))
            orders2.append(order.entity.id, order);
          else
            orders2.append(order.entity.id, *it);
          ordersMapByRaw.remove(it);
        }
      }
      for(HashMap<uint64_t, meguco_user_broker_order_entity>::Iterator i = ordersMapByRaw.begin(), end = ordersMapByRaw.end(); i != end; ++i)
      { // remove
        meguco_user_broker_order_entity& order = *i;
        if(!connection.remove(userBrokerOrdersTableId, order.entity.id))
          orders2.append(order.entity.id, order);
      }
    }
    return (void_t)connection.sendControlResponse(requestId, 0, 0);
  case meguco_user_broker_control_refresh_transactions:
    {
      List<meguco_user_broker_transaction_entity> newTransactions;
      if(!broker->loadTransactions(newTransactions))
      {
        addLogMessage(meguco_log_error, broker->getLastError());
        return (void_t)connection.sendControlResponse(requestId, 0);
      }
      Map<int64_t, meguco_user_broker_transaction_entity*> sortedNewTransactions;
      for(List<meguco_user_broker_transaction_entity>::Iterator i = newTransactions.begin(), end = newTransactions.end(); i != end; ++i)
        sortedNewTransactions.insert((*i).entity.time, &*i);
      HashMap<uint64_t, meguco_user_broker_transaction_entity> transactionsapByRaw;
      for(HashMap<uint64_t, meguco_user_broker_transaction_entity>::Iterator i = transactions2.begin(), end = transactions2.end(); i != end; ++i)
      {
        meguco_user_broker_transaction_entity& transaction = *i;
        transactionsapByRaw.append(transaction.raw_id, transaction);
      }
      transactions2.clear();
      for(Map<int64_t, meguco_user_broker_transaction_entity*>::Iterator i = sortedNewTransactions.begin(), end = sortedNewTransactions.end(); i != end; ++i)
      {
        meguco_user_broker_transaction_entity& transaction = **i;
        HashMap<uint64_t, meguco_user_broker_transaction_entity>::Iterator it = transactionsapByRaw.find(transaction.raw_id);
        if(it == transactionsapByRaw.end() || it->entity.id == 0)
        { // add
          uint64_t id;
          if(connection.add(userBrokerTransactionsTableId, transaction.entity, id))
          {
            transaction.entity.id = id;
            transactions2.append(transaction.entity.id, transaction);
          }
        }
        else
        { // update
          transaction.entity.id = it->entity.id;
          if(Memory::compare(&*it, &transaction, sizeof(transaction)) != 0 &&
             connection.update(userBrokerTransactionsTableId, transaction.entity))
            transactions2.append(transaction.entity.id, transaction);
          else
            transactions2.append(transaction.entity.id, *it);
          transactionsapByRaw.remove(it);
        }
      }
      for(HashMap<uint64_t, meguco_user_broker_transaction_entity>::Iterator i = transactionsapByRaw.begin(), end = transactionsapByRaw.end(); i != end; ++i)
      { // remove
        meguco_user_broker_transaction_entity& transaction = *i;
        if(!connection.remove(userBrokerTransactionsTableId, transaction.entity.id))
          transactions2.append(transaction.entity.id, transaction);
      }
    }
    return (void_t)connection.sendControlResponse(requestId, 0, 0);
  case meguco_user_broker_control_refresh_balance:
    {
      meguco_user_broker_balance_entity newBalance;
      if(!broker->loadBalance(newBalance))
      {
        addLogMessage(meguco_log_error, broker->getLastError());
        return (void_t)connection.sendControlResponse(requestId, 0);
      }
      if(this->balance.entity.id == 0)
      {
        uint64_t id;
        if(connection.add(userBrokerBalanceTableId, newBalance.entity, id))
          newBalance.entity.id = id;
      }
      else
      {
        newBalance.entity.id = this->balance.entity.id;
        connection.update(userBrokerBalanceTableId, newBalance.entity);
      }
      this->balance = newBalance;
    }
    return (void_t)connection.sendControlResponse(requestId, (const byte_t*)&balance, sizeof(meguco_user_broker_balance_entity));
  case meguco_user_broker_control_create_order:
    if(size < sizeof(meguco_user_broker_order_entity))
      return (void_t)connection.sendControlResponse(requestId, zlimdb_error_invalid_request);
    {
      const meguco_user_broker_order_entity& args = *(const meguco_user_broker_order_entity*)data;
      meguco_user_broker_order_entity newOrder;
      if(!broker->createOrder((meguco_user_broker_order_type)args.type, args.price, args.amount, args.total, newOrder))
      {
        addLogMessage(meguco_log_error, broker->getLastError());
        return (void_t)connection.sendControlResponse(requestId, 0);
      }
      newOrder.state = meguco_user_broker_order_open;
      newOrder.timeout = args.timeout;

      // add entity to user brokers table
      uint64_t id;
      if(!connection.add(userBrokerOrdersTableId, newOrder.entity, id))
        return (void_t)connection.sendControlResponse(requestId, (uint16_t)connection.getErrno());
      newOrder.entity.id = id;
      orders2.append(id, newOrder);

      // return entity id
      return (void_t)connection.sendControlResponse(requestId, (const byte_t*)&newOrder, sizeof(meguco_user_broker_order_entity));
    }
  case meguco_user_broker_control_cancel_order:
  case meguco_user_broker_control_remove_order:
    {
      HashMap<uint64_t, meguco_user_broker_order_entity>::Iterator it = orders2.find(entityId);
      if(it == orders2.end())
        return (void_t)connection.sendControlResponse(requestId, zlimdb_error_entity_not_found);
      meguco_user_broker_order_entity& order = *it;

      // cancel order
      if(order.state == meguco_user_broker_order_open)
      {
        if(!broker->cancelOrder(order.raw_id))
        {
          addLogMessage(meguco_log_error, broker->getLastError());
          return (void_t)connection.sendControlResponse(requestId, 0);
        }
      }

      // update order state
      if(controlCode == meguco_user_broker_control_cancel_order)
      {
        order.state = meguco_user_broker_order_canceled;
        if(!connection.update(userBrokerOrdersTableId, order.entity))
          return (void_t)connection.sendControlResponse(requestId, (uint16_t)connection.getErrno());
      }
      else
      {
        if(!connection.remove(userBrokerOrdersTableId, order.entity.id))
          return (void_t)connection.sendControlResponse(requestId, (uint16_t)connection.getErrno());
        orders2.remove(it);
      }

      // send answer
      return (void_t)connection.sendControlResponse(requestId, 0, 0);
    }
  case meguco_user_broker_control_update_order:
    if(size < sizeof(meguco_user_broker_control_update_order_params))
      return (void_t)connection.sendControlResponse(requestId, zlimdb_error_invalid_request);
    {
      HashMap<uint64_t, meguco_user_broker_order_entity>::Iterator it = orders2.find(entityId);
      if(it == orders2.end())
        return (void_t)connection.sendControlResponse(requestId, zlimdb_error_entity_not_found);
      meguco_user_broker_order_entity& order = *it;

      const meguco_user_broker_control_update_order_params& params = *(const meguco_user_broker_control_update_order_params*)data;

      // cancel order
      if(!broker->cancelOrder(order.raw_id))
      {
        addLogMessage(meguco_log_error, broker->getLastError());
        return (void_t)connection.sendControlResponse(requestId, 0);
      }

      // create new order with same id
      meguco_user_broker_order_entity newOrder;
      if(!broker->createOrder((meguco_user_broker_order_type)order.type, params.price, params.amount, params.total, newOrder))
      {
        addLogMessage(meguco_log_error, broker->getLastError());
        order.state = meguco_user_broker_order_error;
      }
      else
      {
        newOrder.entity.id = order.entity.id;
        newOrder.timeout = order.timeout;
        order = newOrder;
        order.state = meguco_user_broker_order_open;
      }

      // update order state in table
      if(!connection.update(userBrokerOrdersTableId, order.entity))
        return (void_t)connection.sendControlResponse(requestId, (uint16_t)connection.getErrno());

      // send answer
      if(order.state == meguco_user_broker_order_error)
        return (void_t)connection.sendControlResponse(requestId, 0);
      else
        return (void_t)connection.sendControlResponse(requestId, 0, 0);
    }
  default:
    return (void_t)connection.sendControlResponse(requestId, zlimdb_error_invalid_request);
  }
}
void SamplingTool::dump(ExecState* exec)
{
    // Tidies up SunSpider output by removing short scripts - such a small number of samples would likely not be useful anyhow.
    if (m_sampleCount < 10)
        return;
    
    // (1) Build and sort 'opcodeSampleInfo' array.

    OpcodeSampleInfo opcodeSampleInfo[numOpcodeIDs];
    for (int i = 0; i < numOpcodeIDs; ++i) {
        opcodeSampleInfo[i].opcode = static_cast<OpcodeID>(i);
        opcodeSampleInfo[i].count = m_opcodeSamples[i];
        opcodeSampleInfo[i].countInCTIFunctions = m_opcodeSamplesInCTIFunctions[i];
    }

    qsort(opcodeSampleInfo, numOpcodeIDs, sizeof(OpcodeSampleInfo), compareOpcodeIndicesSampling);

    // (2) Print Opcode sampling results.

    printf("\nBytecode samples [*]\n");
    printf("                             sample   %% of       %% of     |   cti     cti %%\n");
    printf("opcode                       count     VM        total    |  count   of self\n");
    printf("-------------------------------------------------------   |  ----------------\n");

    for (int i = 0; i < numOpcodeIDs; ++i) {
        long long count = opcodeSampleInfo[i].count;
        if (!count)
            continue;

        OpcodeID opcodeID = opcodeSampleInfo[i].opcode;
        
        const char* opcodeName = opcodeNames[opcodeID];
        const char* opcodePadding = padOpcodeName(opcodeID, 28);
        double percentOfVM = (static_cast<double>(count) * 100) / m_opcodeSampleCount;
        double percentOfTotal = (static_cast<double>(count) * 100) / m_sampleCount;
        long long countInCTIFunctions = opcodeSampleInfo[i].countInCTIFunctions;
        double percentInCTIFunctions = (static_cast<double>(countInCTIFunctions) * 100) / count;
        fprintf(stdout, "%s:%s%-6lld %.3f%%\t%.3f%%\t  |   %-6lld %.3f%%\n", opcodeName, opcodePadding, count, percentOfVM, percentOfTotal, countInCTIFunctions, percentInCTIFunctions);
    }
    
    printf("\n[*] Samples inside host code are not charged to any Bytecode.\n\n");
    printf("\tSamples inside VM:\t\t%lld / %lld (%.3f%%)\n", m_opcodeSampleCount, m_sampleCount, (static_cast<double>(m_opcodeSampleCount) * 100) / m_sampleCount);
    printf("\tSamples inside host code:\t%lld / %lld (%.3f%%)\n\n", m_sampleCount - m_opcodeSampleCount, m_sampleCount, (static_cast<double>(m_sampleCount - m_opcodeSampleCount) * 100) / m_sampleCount);
    printf("\tsample count:\tsamples inside this opcode\n");
    printf("\t%% of VM:\tsample count / all opcode samples\n");
    printf("\t%% of total:\tsample count / all samples\n");
    printf("\t--------------\n");
    printf("\tcti count:\tsamples inside a CTI function called by this opcode\n");
    printf("\tcti %% of self:\tcti count / sample count\n");
    
#if ENABLE(CODEBLOCK_SAMPLING)

    // (3) Build and sort 'codeBlockSamples' array.

    int scopeCount = m_scopeSampleMap->size();
    Vector<ScopeSampleRecord*> codeBlockSamples(scopeCount);
    ScopeSampleRecordMap::iterator iter = m_scopeSampleMap->begin();
    for (int i = 0; i < scopeCount; ++i, ++iter)
        codeBlockSamples[i] = iter->second;

    qsort(codeBlockSamples.begin(), scopeCount, sizeof(ScopeSampleRecord*), compareScopeSampleRecords);

    // (4) Print data from 'codeBlockSamples' array.

    printf("\nCodeBlock samples\n\n"); 

    for (int i = 0; i < scopeCount; ++i) {
        ScopeSampleRecord* record = codeBlockSamples[i];
        CodeBlock* codeBlock = record->m_codeBlock;

        double blockPercent = (record->m_sampleCount * 100.0) / m_sampleCount;

        if (blockPercent >= 1) {
            //Instruction* code = codeBlock->instructions().begin();
            printf("#%d: %s:%d: %d / %lld (%.3f%%)\n", i + 1, record->m_scope->sourceURL().UTF8String().c_str(), codeBlock->lineNumberForBytecodeOffset(exec, 0), record->m_sampleCount, m_sampleCount, blockPercent);
            if (i < 10) {
                HashMap<unsigned,unsigned> lineCounts;
                codeBlock->dump(exec);

                printf("    Opcode and line number samples [*]\n\n");
                for (unsigned op = 0; op < record->m_size; ++op) {
                    int count = record->m_samples[op];
                    if (count) {
                        printf("    [% 4d] has sample count: % 4d\n", op, count);
                        unsigned line = codeBlock->lineNumberForBytecodeOffset(exec, op);
                        lineCounts.set(line, (lineCounts.contains(line) ? lineCounts.get(line) : 0) + count);
                    }
                }
                printf("\n");

                int linesCount = lineCounts.size();
                Vector<LineCountInfo> lineCountInfo(linesCount);
                int lineno = 0;
                for (HashMap<unsigned,unsigned>::iterator iter = lineCounts.begin(); iter != lineCounts.end(); ++iter, ++lineno) {
                    lineCountInfo[lineno].line = iter->first;
                    lineCountInfo[lineno].count = iter->second;
                }

                qsort(lineCountInfo.begin(), linesCount, sizeof(LineCountInfo), compareLineCountInfoSampling);

                for (lineno = 0; lineno < linesCount; ++lineno) {
                    printf("    Line #%d has sample count %d.\n", lineCountInfo[lineno].line, lineCountInfo[lineno].count);
                }
                printf("\n");
                printf("    [*] Samples inside host code are charged to the calling Bytecode.\n");
                printf("        Samples on a call / return boundary are not charged to a specific opcode or line.\n\n");
                printf("            Samples on a call / return boundary: %d / %d (%.3f%%)\n\n", record->m_sampleCount - record->m_opcodeSampleCount, record->m_sampleCount, (static_cast<double>(record->m_sampleCount - record->m_opcodeSampleCount) * 100) / record->m_sampleCount);
            }
        }
    }
#else
    UNUSED_PARAM(exec);
#endif
}
static bool parse(const Dictionary& constraintsDictionary, blink::WebVector<blink::WebMediaConstraint>& optional, blink::WebVector<blink::WebMediaConstraint>& mandatory)
{
    if (constraintsDictionary.isUndefinedOrNull())
        return true;

    Vector<String> names;
    constraintsDictionary.getOwnPropertyNames(names);

    String mandatoryName("mandatory");
    String optionalName("optional");

    for (Vector<String>::iterator it = names.begin(); it != names.end(); ++it) {
        if (*it != mandatoryName && *it != optionalName)
            return false;
    }

    Vector<blink::WebMediaConstraint> mandatoryConstraintsVector;
    if (names.contains(mandatoryName)) {
        Dictionary mandatoryConstraintsDictionary;
        bool ok = constraintsDictionary.get(mandatoryName, mandatoryConstraintsDictionary);
        if (!ok || mandatoryConstraintsDictionary.isUndefinedOrNull())
            return false;

        HashMap<String, String> mandatoryConstraintsHashMap;
        ok = mandatoryConstraintsDictionary.getOwnPropertiesAsStringHashMap(mandatoryConstraintsHashMap);
        if (!ok)
            return false;

        HashMap<String, String>::const_iterator iter = mandatoryConstraintsHashMap.begin();
        for (; iter != mandatoryConstraintsHashMap.end(); ++iter)
            mandatoryConstraintsVector.append(blink::WebMediaConstraint(iter->key, iter->value));
    }

    Vector<blink::WebMediaConstraint> optionalConstraintsVector;
    if (names.contains(optionalName)) {
        ArrayValue optionalConstraints;
        bool ok = constraintsDictionary.get(optionalName, optionalConstraints);
        if (!ok || optionalConstraints.isUndefinedOrNull())
            return false;

        size_t numberOfConstraints;
        ok = optionalConstraints.length(numberOfConstraints);
        if (!ok)
            return false;

        for (size_t i = 0; i < numberOfConstraints; ++i) {
            Dictionary constraint;
            ok = optionalConstraints.get(i, constraint);
            if (!ok || constraint.isUndefinedOrNull())
                return false;
            Vector<String> localNames;
            constraint.getOwnPropertyNames(localNames);
            if (localNames.size() != 1)
                return false;
            String key = localNames[0];
            String value;
            ok = constraint.get(key, value);
            if (!ok)
                return false;
            optionalConstraintsVector.append(blink::WebMediaConstraint(key, value));
        }
    }

    optional.assign(optionalConstraintsVector);
    mandatory.assign(mandatoryConstraintsVector);
    return true;
}