<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkEntropyMatrixWeighting.cxx

-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkCommand.h"
#include "vtkDenseArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkSmartPointer.h"
#include "vtkEntropyMatrixWeighting.h"

#include <vtkstd/stdexcept>

#ifdef WIN32

static inline double log2(double n)
{
  return log(n) / log(2.);
}

#endif // WIN32

///////////////////////////////////////////////////////////////////////////////
// vtkEntropyMatrixWeighting

vtkStandardNewMacro(vtkEntropyMatrixWeighting);

vtkEntropyMatrixWeighting::vtkEntropyMatrixWeighting() :
  FeatureDimension(0)
{
}

vtkEntropyMatrixWeighting::~vtkEntropyMatrixWeighting()
{
}

void vtkEntropyMatrixWeighting::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "FeatureDimension: " << this->FeatureDimension << endl;
}

int vtkEntropyMatrixWeighting::RequestData(
  vtkInformation*,
  vtkInformationVector** inputVector,
  vtkInformationVector* outputVector)
{
  try
    {
    // Test our preconditions ...
    vtkArrayData* const input_data = vtkArrayData::GetData(inputVector[0]);
    if(!input_data)
      throw vtkstd::runtime_error("Missing input vtkArrayData on port 0.");
    if(input_data->GetNumberOfArrays() != 1)
      throw vtkstd::runtime_error("Input vtkArrayData must contain exactly one array.");
    vtkTypedArray<double>* const input_array = vtkTypedArray<double>::SafeDownCast(input_data->GetArray(0));
    if(!input_array)
      throw vtkstd::runtime_error("Input array must be a vtkTypedArray<double>.");
    if(input_array->GetDimensions() != 2)
      throw vtkstd::runtime_error("Input array must be a matrix.");

    vtkIdType feature_dimension;
    vtkIdType object_dimension;
    switch(this->FeatureDimension)
      {
      case 0:
        feature_dimension = 0;
        object_dimension = 1;
        break;
      case 1:
        feature_dimension = 1;
        object_dimension = 0;
        break;
      default:
        throw vtkstd::runtime_error("FeatureDimension out-of-bounds.");
      }

    const vtkArrayRange features = input_array->GetExtent(feature_dimension);
    const vtkArrayRange objects = input_array->GetExtent(object_dimension);

    // Setup our output ...
    vtkDenseArray<double>* const output_array = vtkDenseArray<double>::New();
    output_array->Resize(features);
    output_array->Fill(0.0);

    vtkArrayData* const output = vtkArrayData::GetData(outputVector);
    output->ClearArrays();
    output->AddArray(output_array);
    output_array->Delete();

    // Make it happen ...
    output_array->SetName("entropy_weight");

    // Cache log2( number of documents ) ...
    const double logN = log2(static_cast<double>(objects.GetSize()));

    // Cache the frequency of each feature across the entire corpus ...
    vtkstd::vector<double> Fi(features.GetSize(), 0);
    vtkArrayCoordinates coordinates;
    const vtkIdType non_null_count = input_array->GetNonNullSize();
    for(vtkIdType n = 0; n != non_null_count; ++n)
      {
      input_array->GetCoordinatesN(n, coordinates);
      const vtkIdType i = coordinates[feature_dimension];
      const double fij = input_array->GetValueN(n);
      Fi[i - features.GetBegin()] += fij;
      }

    // Compute weights ...
    for(vtkIdType n = 0; n != non_null_count; ++n)
      {
      input_array->GetCoordinatesN(n, coordinates);
      const vtkIdType i = coordinates[feature_dimension];
      const double fij = input_array->GetValueN(n);
      const double pij = fij / Fi[i - features.GetBegin()];
      output_array->SetValue(i, output_array->GetValue(i) + (pij * log2(pij) / logN));
      }

    // Add 1 to each weight ...
    for(vtkIdType i = features.GetBegin(); i != features.GetEnd(); ++i)
      {
      output_array->SetValue(i, output_array->GetValue(i) + 1);
      }

    }
  catch(vtkstd::exception& e)
    {
    vtkErrorMacro(<< "unhandled exception: " << e.what());
    return 0;
    }
  catch(...)
    {
    vtkErrorMacro(<< "unknown exception");
    return 0;
    }

  return 1;
}

<commit_msg>Minor change to allow mingw builds to work better.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkEntropyMatrixWeighting.cxx

-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkCommand.h"
#include "vtkDenseArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkSmartPointer.h"
#include "vtkEntropyMatrixWeighting.h"

#include <vtkstd/stdexcept>

#if defined(WIN32) && !defined(__MINGW32__)

static inline double log2(double n)
{
  return log(n) / log(2.);
}

#endif // WIN32

///////////////////////////////////////////////////////////////////////////////
// vtkEntropyMatrixWeighting

vtkStandardNewMacro(vtkEntropyMatrixWeighting);

vtkEntropyMatrixWeighting::vtkEntropyMatrixWeighting() :
  FeatureDimension(0)
{
}

vtkEntropyMatrixWeighting::~vtkEntropyMatrixWeighting()
{
}

void vtkEntropyMatrixWeighting::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "FeatureDimension: " << this->FeatureDimension << endl;
}

int vtkEntropyMatrixWeighting::RequestData(
  vtkInformation*,
  vtkInformationVector** inputVector,
  vtkInformationVector* outputVector)
{
  try
    {
    // Test our preconditions ...
    vtkArrayData* const input_data = vtkArrayData::GetData(inputVector[0]);
    if(!input_data)
      throw vtkstd::runtime_error("Missing input vtkArrayData on port 0.");
    if(input_data->GetNumberOfArrays() != 1)
      throw vtkstd::runtime_error("Input vtkArrayData must contain exactly one array.");
    vtkTypedArray<double>* const input_array = vtkTypedArray<double>::SafeDownCast(input_data->GetArray(0));
    if(!input_array)
      throw vtkstd::runtime_error("Input array must be a vtkTypedArray<double>.");
    if(input_array->GetDimensions() != 2)
      throw vtkstd::runtime_error("Input array must be a matrix.");

    vtkIdType feature_dimension;
    vtkIdType object_dimension;
    switch(this->FeatureDimension)
      {
      case 0:
        feature_dimension = 0;
        object_dimension = 1;
        break;
      case 1:
        feature_dimension = 1;
        object_dimension = 0;
        break;
      default:
        throw vtkstd::runtime_error("FeatureDimension out-of-bounds.");
      }

    const vtkArrayRange features = input_array->GetExtent(feature_dimension);
    const vtkArrayRange objects = input_array->GetExtent(object_dimension);

    // Setup our output ...
    vtkDenseArray<double>* const output_array = vtkDenseArray<double>::New();
    output_array->Resize(features);
    output_array->Fill(0.0);

    vtkArrayData* const output = vtkArrayData::GetData(outputVector);
    output->ClearArrays();
    output->AddArray(output_array);
    output_array->Delete();

    // Make it happen ...
    output_array->SetName("entropy_weight");

    // Cache log2( number of documents ) ...
    const double logN = log2(static_cast<double>(objects.GetSize()));

    // Cache the frequency of each feature across the entire corpus ...
    vtkstd::vector<double> Fi(features.GetSize(), 0);
    vtkArrayCoordinates coordinates;
    const vtkIdType non_null_count = input_array->GetNonNullSize();
    for(vtkIdType n = 0; n != non_null_count; ++n)
      {
      input_array->GetCoordinatesN(n, coordinates);
      const vtkIdType i = coordinates[feature_dimension];
      const double fij = input_array->GetValueN(n);
      Fi[i - features.GetBegin()] += fij;
      }

    // Compute weights ...
    for(vtkIdType n = 0; n != non_null_count; ++n)
      {
      input_array->GetCoordinatesN(n, coordinates);
      const vtkIdType i = coordinates[feature_dimension];
      const double fij = input_array->GetValueN(n);
      const double pij = fij / Fi[i - features.GetBegin()];
      output_array->SetValue(i, output_array->GetValue(i) + (pij * log2(pij) / logN));
      }

    // Add 1 to each weight ...
    for(vtkIdType i = features.GetBegin(); i != features.GetEnd(); ++i)
      {
      output_array->SetValue(i, output_array->GetValue(i) + 1);
      }

    }
  catch(vtkstd::exception& e)
    {
    vtkErrorMacro(<< "unhandled exception: " << e.what());
    return 0;
    }
  catch(...)
    {
    vtkErrorMacro(<< "unknown exception");
    return 0;
    }

  return 1;
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2006 Apple Computer, Inc.  All rights reserved.
 * Copyright (C) 2008 Collabora, Ltd.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"

#include <stdio.h>
#include <stdlib.h>
#include <float.h>

#include "AffineTransform.h"
#include "AXObjectCache.h"
#include "BitmapImage.h"
#include "CachedResource.h"
#include "Clipboard.h"
#include "ContextMenu.h"
#include "ContextMenuItem.h"
#include "CookieJar.h"
#include "Cursor.h"
#include "DocumentFragment.h"
#include "DocumentLoader.h"
#include "DragController.h"
#include "Editor.h"
#include "EditCommand.h"
#include "EventHandler.h"
#include "FileChooser.h"
#include "Font.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameView.h"
#include "Icon.h"
#include "IconDatabase.h"
#include "IconLoader.h"
#include "IntPoint.h"
#include "GraphicsContext.h"
#include "History.h"
#include "KURL.h"
#include "Language.h"
#include "loader.h"
#include "Node.h"
#include "NotImplemented.h"
#include "Pasteboard.h"
#include "Path.h"
#include "PlatformMenuDescription.h"
#include "PlatformMouseEvent.h"
#include "PlatformScrollBar.h"
#include "PopupMenu.h"
#include "RenderTheme.h"
#include "ResourceHandle.h"
#include "ResourceHandleInternal.h"
#include "ResourceLoader.h"
#include "Screen.h"
#include "ScrollbarTheme.h"
#include "SearchPopupMenu.h"
#include "ScrollBar.h"
#include "SharedBuffer.h"
#include "SharedTimer.h"
#include "TextBoundaries.h"
#include "Widget.h"

using namespace WebCore;

Vector<char> loadResourceIntoArray(const char* resourceName)
{
    Vector<char> resource;
    return resource;
}

void Widget::removeFromParent() { notImplemented(); }

int findNextSentenceFromIndex(UChar const*,int,int,bool) { notImplemented(); return 0; }
void findSentenceBoundary(UChar const*,int,int,int*,int*) { notImplemented(); }

int WebCore::findNextWordFromIndex(UChar const*,int,int,bool) { notImplemented(); return 0; }

DragImageRef Frame::dragImageForSelection() { notImplemented(); return 0; }

void GraphicsContext::addInnerRoundedRectClip(const IntRect& rect, int thickness) { notImplemented(); }

// cookies (we'll need a place to store these
void WebCore::setCookies(Document* document, const KURL& url, const KURL& policyURL, const String& value) { notImplemented(); }
String WebCore::cookies(const Document* document, const KURL& url) { notImplemented(); return String(); }
bool WebCore::cookiesEnabled(const Document* document) { notImplemented(); return false; }

/********************************************************/
/* Completely empty stubs (mostly to allow DRT to run): */
/********************************************************/
static WebCore::Cursor localCursor;
const WebCore::Cursor& WebCore::moveCursor() { return localCursor; }

void WebCore::findWordBoundary(UChar const* str,int len,int position,int* start, int* end) { notImplemented(); *start=position; *end=position; }

void Widget::setIsSelected(bool) { notImplemented(); }

void GraphicsContext::setPlatformShadow(IntSize const&,int,Color const&) { notImplemented(); }
void GraphicsContext::clearPlatformShadow() { notImplemented(); }
void GraphicsContext::beginTransparencyLayer(float) { notImplemented(); }
void GraphicsContext::endTransparencyLayer() { notImplemented(); }
void GraphicsContext::clearRect(const FloatRect&) { notImplemented(); }
void GraphicsContext::strokeRect(const FloatRect&, float) { notImplemented(); }
void GraphicsContext::setLineCap(LineCap) { notImplemented(); }
void GraphicsContext::setLineJoin(LineJoin) { notImplemented(); }
void GraphicsContext::setMiterLimit(float) { notImplemented(); }
void GraphicsContext::setAlpha(float) { notImplemented(); }

Color WebCore::focusRingColor() { return 0xFF0000FF; }
void WebCore::setFocusRingColorChangeFunction(void (*)()) { }

void Image::drawPattern(GraphicsContext*, const FloatRect& srcRect, const AffineTransform& patternTransform, const FloatPoint& phase, CompositeOperator, const FloatRect& destRect) { notImplemented(); }

PlatformScrollbar::PlatformScrollbar(ScrollbarClient* client, ScrollbarOrientation orientation, ScrollbarControlSize controlSize) : Scrollbar(client, orientation, controlSize) { notImplemented(); }
PlatformScrollbar::~PlatformScrollbar() { notImplemented(); }
int PlatformScrollbar::width() const { notImplemented(); return 0; }
int PlatformScrollbar::height() const { notImplemented(); return 0; }
void PlatformScrollbar::setEnabled(bool) { notImplemented(); }
void PlatformScrollbar::paint(GraphicsContext*, const IntRect& damageRect) { notImplemented(); }
void PlatformScrollbar::updateThumbPosition() { notImplemented(); }
void PlatformScrollbar::updateThumbProportion() { notImplemented(); }
void PlatformScrollbar::setRect(const IntRect&) { notImplemented(); }

void ScrollbarTheme::nativeTheme() { notImplemented(); static ScrollbarTheme theme; return &theme; }

void FileChooser::openFileChooser(Document*) { notImplemented(); }
String FileChooser::basenameForWidth(const Font&, int width) const { notImplemented(); return String(); }

Icon::~Icon() { }
PassRefPtr<Icon> Icon::newIconForFile(const String& filename) { notImplemented(); return 0; }
void Icon::paint(GraphicsContext*, const IntRect&) { notImplemented(); }

ContextMenu::ContextMenu(const HitTestResult& result) : m_hitTestResult(result) { notImplemented(); }
ContextMenu::~ContextMenu() { notImplemented(); }
void ContextMenu::appendItem(ContextMenuItem&) { notImplemented(); }
void ContextMenu::setPlatformDescription(PlatformMenuDescription) { notImplemented(); }

ContextMenuItem::ContextMenuItem(PlatformMenuItemDescription) { notImplemented(); }
ContextMenuItem::ContextMenuItem(ContextMenu*) { notImplemented(); }
ContextMenuItem::ContextMenuItem(ContextMenuItemType type, ContextMenuAction action, const String& title, ContextMenu* subMenu) { notImplemented(); }
ContextMenuItem::~ContextMenuItem() { notImplemented(); }
PlatformMenuItemDescription ContextMenuItem::releasePlatformDescription() { notImplemented(); return m_platformDescription; }
ContextMenuItemType ContextMenuItem::type() const { notImplemented(); return ActionType; }
void ContextMenuItem::setType(ContextMenuItemType) { notImplemented(); }
ContextMenuAction ContextMenuItem::action() const { notImplemented(); return ContextMenuItemTagNoAction; }
void ContextMenuItem::setAction(ContextMenuAction) { notImplemented(); }
String ContextMenuItem::title() const { notImplemented(); return String(); }
void ContextMenuItem::setTitle(const String&) { notImplemented(); }
//PlatformMenuDescription ContextMenuItem::platformSubMenu() const { notImplemented(); return 0; }
void ContextMenuItem::setSubMenu(ContextMenu*) { notImplemented(); }
void ContextMenuItem::setChecked(bool) { notImplemented(); }
void ContextMenuItem::setEnabled(bool) { notImplemented(); }

void Editor::showColorPanel() { notImplemented(); }
void Editor::showFontPanel() { notImplemented(); }
void Editor::showStylesPanel() { notImplemented(); }

bool EventHandler::tabsToAllControls(KeyboardEvent* event) const { notImplemented(); return false; }
bool EventHandler::passSubframeEventToSubframe(MouseEventWithHitTestResults&, Frame* subframe, HitTestResult*) { notImplemented(); return false; }
bool EventHandler::passMouseDownEventToWidget(Widget*) { notImplemented(); return false; }
bool EventHandler::passWheelEventToWidget(PlatformWheelEvent&, Widget*) { notImplemented(); return false; }

void SearchPopupMenu::saveRecentSearches(const AtomicString& name, const Vector<String>& searchItems) { notImplemented(); }
void SearchPopupMenu::loadRecentSearches(const AtomicString& name, Vector<String>& searchItems) { notImplemented(); }
SearchPopupMenu::SearchPopupMenu(PopupMenuClient* client) : PopupMenu(client) { notImplemented(); }
bool SearchPopupMenu::enabled() { return true; }

namespace WebCore {
float userIdleTime() { notImplemented(); return FLT_MAX; } // return an arbitrarily high userIdleTime so that releasing pages from the page cache isn't postponed
Vector<String> supportedKeySizes() { notImplemented(); return Vector<String>(); }
String signedPublicKeyAndChallengeString(unsigned keySizeIndex, const String &challengeString, const KURL &url) { return String(); }
const char* currentTextBreakLocaleID() { notImplemented(); return "en_us"; }

String KURL::fileSystemPath() const { notImplemented(); return String(); }

PassRefPtr<SharedBuffer> SharedBuffer::createWithContentsOfFile(const String&) { notImplemented(); return 0; }
}
<commit_msg>Fix wx bustage.<commit_after>/*
 * Copyright (C) 2006 Apple Computer, Inc.  All rights reserved.
 * Copyright (C) 2008 Collabora, Ltd.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"

#include <stdio.h>
#include <stdlib.h>
#include <float.h>

#include "AffineTransform.h"
#include "AXObjectCache.h"
#include "BitmapImage.h"
#include "CachedResource.h"
#include "Clipboard.h"
#include "ContextMenu.h"
#include "ContextMenuItem.h"
#include "CookieJar.h"
#include "Cursor.h"
#include "DocumentFragment.h"
#include "DocumentLoader.h"
#include "DragController.h"
#include "Editor.h"
#include "EditCommand.h"
#include "EventHandler.h"
#include "FileChooser.h"
#include "Font.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameView.h"
#include "Icon.h"
#include "IconDatabase.h"
#include "IconLoader.h"
#include "IntPoint.h"
#include "GraphicsContext.h"
#include "History.h"
#include "KURL.h"
#include "Language.h"
#include "loader.h"
#include "Node.h"
#include "NotImplemented.h"
#include "Pasteboard.h"
#include "Path.h"
#include "PlatformMenuDescription.h"
#include "PlatformMouseEvent.h"
#include "PlatformScrollBar.h"
#include "PopupMenu.h"
#include "RenderTheme.h"
#include "ResourceHandle.h"
#include "ResourceHandleInternal.h"
#include "ResourceLoader.h"
#include "Screen.h"
#include "ScrollbarTheme.h"
#include "SearchPopupMenu.h"
#include "ScrollBar.h"
#include "SharedBuffer.h"
#include "SharedTimer.h"
#include "TextBoundaries.h"
#include "Widget.h"

using namespace WebCore;

Vector<char> loadResourceIntoArray(const char* resourceName)
{
    Vector<char> resource;
    return resource;
}

void Widget::removeFromParent() { notImplemented(); }

int findNextSentenceFromIndex(UChar const*,int,int,bool) { notImplemented(); return 0; }
void findSentenceBoundary(UChar const*,int,int,int*,int*) { notImplemented(); }

int WebCore::findNextWordFromIndex(UChar const*,int,int,bool) { notImplemented(); return 0; }

DragImageRef Frame::dragImageForSelection() { notImplemented(); return 0; }

void GraphicsContext::addInnerRoundedRectClip(const IntRect& rect, int thickness) { notImplemented(); }

// cookies (we'll need a place to store these
void WebCore::setCookies(Document* document, const KURL& url, const KURL& policyURL, const String& value) { notImplemented(); }
String WebCore::cookies(const Document* document, const KURL& url) { notImplemented(); return String(); }
bool WebCore::cookiesEnabled(const Document* document) { notImplemented(); return false; }

/********************************************************/
/* Completely empty stubs (mostly to allow DRT to run): */
/********************************************************/
static WebCore::Cursor localCursor;
const WebCore::Cursor& WebCore::moveCursor() { return localCursor; }

void WebCore::findWordBoundary(UChar const* str,int len,int position,int* start, int* end) { notImplemented(); *start=position; *end=position; }

void Widget::setIsSelected(bool) { notImplemented(); }

void GraphicsContext::setPlatformShadow(IntSize const&,int,Color const&) { notImplemented(); }
void GraphicsContext::clearPlatformShadow() { notImplemented(); }
void GraphicsContext::beginTransparencyLayer(float) { notImplemented(); }
void GraphicsContext::endTransparencyLayer() { notImplemented(); }
void GraphicsContext::clearRect(const FloatRect&) { notImplemented(); }
void GraphicsContext::strokeRect(const FloatRect&, float) { notImplemented(); }
void GraphicsContext::setLineCap(LineCap) { notImplemented(); }
void GraphicsContext::setLineJoin(LineJoin) { notImplemented(); }
void GraphicsContext::setMiterLimit(float) { notImplemented(); }
void GraphicsContext::setAlpha(float) { notImplemented(); }

Color WebCore::focusRingColor() { return 0xFF0000FF; }
void WebCore::setFocusRingColorChangeFunction(void (*)()) { }

void Image::drawPattern(GraphicsContext*, const FloatRect& srcRect, const AffineTransform& patternTransform, const FloatPoint& phase, CompositeOperator, const FloatRect& destRect) { notImplemented(); }

PlatformScrollbar::PlatformScrollbar(ScrollbarClient* client, ScrollbarOrientation orientation, ScrollbarControlSize controlSize) : Scrollbar(client, orientation, controlSize) { notImplemented(); }
PlatformScrollbar::~PlatformScrollbar() { notImplemented(); }
int PlatformScrollbar::width() const { notImplemented(); return 0; }
int PlatformScrollbar::height() const { notImplemented(); return 0; }
void PlatformScrollbar::setEnabled(bool) { notImplemented(); }
void PlatformScrollbar::paint(GraphicsContext*, const IntRect& damageRect) { notImplemented(); }
void PlatformScrollbar::updateThumbPosition() { notImplemented(); }
void PlatformScrollbar::updateThumbProportion() { notImplemented(); }
void PlatformScrollbar::setRect(const IntRect&) { notImplemented(); }

ScrollbarTheme* ScrollbarTheme::nativeTheme() { notImplemented(); static ScrollbarTheme theme; return &theme; }

void FileChooser::openFileChooser(Document*) { notImplemented(); }
String FileChooser::basenameForWidth(const Font&, int width) const { notImplemented(); return String(); }

Icon::~Icon() { }
PassRefPtr<Icon> Icon::newIconForFile(const String& filename) { notImplemented(); return 0; }
void Icon::paint(GraphicsContext*, const IntRect&) { notImplemented(); }

ContextMenu::ContextMenu(const HitTestResult& result) : m_hitTestResult(result) { notImplemented(); }
ContextMenu::~ContextMenu() { notImplemented(); }
void ContextMenu::appendItem(ContextMenuItem&) { notImplemented(); }
void ContextMenu::setPlatformDescription(PlatformMenuDescription) { notImplemented(); }

ContextMenuItem::ContextMenuItem(PlatformMenuItemDescription) { notImplemented(); }
ContextMenuItem::ContextMenuItem(ContextMenu*) { notImplemented(); }
ContextMenuItem::ContextMenuItem(ContextMenuItemType type, ContextMenuAction action, const String& title, ContextMenu* subMenu) { notImplemented(); }
ContextMenuItem::~ContextMenuItem() { notImplemented(); }
PlatformMenuItemDescription ContextMenuItem::releasePlatformDescription() { notImplemented(); return m_platformDescription; }
ContextMenuItemType ContextMenuItem::type() const { notImplemented(); return ActionType; }
void ContextMenuItem::setType(ContextMenuItemType) { notImplemented(); }
ContextMenuAction ContextMenuItem::action() const { notImplemented(); return ContextMenuItemTagNoAction; }
void ContextMenuItem::setAction(ContextMenuAction) { notImplemented(); }
String ContextMenuItem::title() const { notImplemented(); return String(); }
void ContextMenuItem::setTitle(const String&) { notImplemented(); }
//PlatformMenuDescription ContextMenuItem::platformSubMenu() const { notImplemented(); return 0; }
void ContextMenuItem::setSubMenu(ContextMenu*) { notImplemented(); }
void ContextMenuItem::setChecked(bool) { notImplemented(); }
void ContextMenuItem::setEnabled(bool) { notImplemented(); }

void Editor::showColorPanel() { notImplemented(); }
void Editor::showFontPanel() { notImplemented(); }
void Editor::showStylesPanel() { notImplemented(); }

bool EventHandler::tabsToAllControls(KeyboardEvent* event) const { notImplemented(); return false; }
bool EventHandler::passSubframeEventToSubframe(MouseEventWithHitTestResults&, Frame* subframe, HitTestResult*) { notImplemented(); return false; }
bool EventHandler::passMouseDownEventToWidget(Widget*) { notImplemented(); return false; }
bool EventHandler::passWheelEventToWidget(PlatformWheelEvent&, Widget*) { notImplemented(); return false; }

void SearchPopupMenu::saveRecentSearches(const AtomicString& name, const Vector<String>& searchItems) { notImplemented(); }
void SearchPopupMenu::loadRecentSearches(const AtomicString& name, Vector<String>& searchItems) { notImplemented(); }
SearchPopupMenu::SearchPopupMenu(PopupMenuClient* client) : PopupMenu(client) { notImplemented(); }
bool SearchPopupMenu::enabled() { return true; }

namespace WebCore {
float userIdleTime() { notImplemented(); return FLT_MAX; } // return an arbitrarily high userIdleTime so that releasing pages from the page cache isn't postponed
Vector<String> supportedKeySizes() { notImplemented(); return Vector<String>(); }
String signedPublicKeyAndChallengeString(unsigned keySizeIndex, const String &challengeString, const KURL &url) { return String(); }
const char* currentTextBreakLocaleID() { notImplemented(); return "en_us"; }

String KURL::fileSystemPath() const { notImplemented(); return String(); }

PassRefPtr<SharedBuffer> SharedBuffer::createWithContentsOfFile(const String&) { notImplemented(); return 0; }
}
<|endoftext|>


<commit_before>/**
 * \file AnnConsole.hpp
 * \brief Represent the output console that can be shown by calling AnnEngine::toggleOnScreenConsole()
 *		  This class create handle the texture buffer and text rendering for text display
 * \author A. Brainville (Ybalrid)
 */

#ifndef	ANNCONSOLE
#define ANNCONSOLE

#include "systemMacro.h"
#include "AnnTypes.h"
#include "AnnKeyCode.h"
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <Ogre.h>
#include <Overlay/OgreFont.h>
#include <Overlay/OgreFontManager.h>
#include <OgreRenderOperation.h>
#include <Hlms/Unlit/OgreHlmsUnlitDatablock.h>
#include <OgreHardwarePixelBuffer.h>

#include "AnnSubsystem.hpp"

namespace Annwvyn
{
	///In engine - On screen floating console
	class AnnDllExport AnnConsole : public AnnSubSystem
	{
	public:

		static constexpr auto CONSOLE_BUFFER = 17;
		static constexpr auto MAX_CONSOLE_LOG_WIDTH = 72;
		static constexpr auto BASE = 256;
		static constexpr auto MARGIN = 4;
		static constexpr auto CONSOLE_HISTORY = 10;

		///Construct the console. This should only be called by AnnEngine itself when the camera and ogre are operational
		AnnConsole();
		virtual ~AnnConsole();

		///Add text to the console buffer. The console buffer will keep CONSOLE_BUFFER lines of messages in memory only
		/// \param string text to append to the console
		void append(std::string string);

		///Set arbitrary the visibility state of the console. Visible if no arg given, hide it if visibility = false
		void setVisible(bool visibility = true);

		///Toggle the console.
		void toggle();

		///True if text has been updated on the console and the console is visible.
		bool needUpdate() override;

		///Update the console by filling it with background texture then blitting text on it.
		///Can take some computing time depending on the size/resolution of the textures and buffer
		void update() override;

		///Move the console where it should
		void syncConsolePosition() const;

		///Clear the text draw buffer of the console
		void bufferClear();

		///Array of forbidden keyword to check
		std::array<const char*, 2> forbidden = { {"var", "auto"} };

		///This piece of code if from the Ogre Wiki. Write text to a texture using Ogre::FontManager to create glyphs
		static void WriteToTexture(const Ogre::String& str, Ogre::TexturePtr destTexture, Ogre::Image::Box destRectangle, Ogre::Font* font, const Ogre::ColourValue &color, char justify = 'l', bool wordwrap = false);

		///return true if pointed to an empty slot
		bool setFromPointedHistory();

		void notifyNavigationKey(KeyCode::code code);
	private:

		///Cleanup and run the user input.
		void runInput(std::string& input);

		void addToHistory(const std::string& input);

		///Run input that are not regular script commands
		bool runSpecialInput(const std::string& input);

		///Return true if the given string match with any of the forbidden keyword int the array
		bool isForbdiden(const std::string& keyword);

		///True if content of the buffer has been modified
		bool modified;

		///Array of 3D points to construct the render plane
		AnnVect3 points[4];

		///Array of UV coordinates to constructed the render plane
		AnnVect2 textCoord[4];

		///Buffer of string objects
		std::string buffer[CONSOLE_BUFFER];

		///The surface used to display (aka the render plane)
		Ogre::ManualObject* displaySurface;

		///Node where the console is attached
		Ogre::SceneNode* consoleNode;

		///The actual texture of the display
		Ogre::TexturePtr texture;

		///Position of the plane using the camera as reference
		AnnVect3 offset;

		///Background texture, should be a random PNG file from the CORE resources
		Ogre::TexturePtr background;

		///OpenGL Texture IDs, to use glCopyImageSubData to clone texture quickly.
		GLuint backgroundID, textureID;

		///There's a small optimization we can do on the way we copy a texture to another, but the opengl function is available on GL4.3+ hardware only.
		bool openGL43plus;

		///The font object used, should be Vera Mono in true type format from the Gnome project, included in CORE resources
		Ogre::FontPtr font;

		///If false, the console is not visible
		bool visibility;

		///Timestamp in seconds since the start of the game the last console refresh was performed
		double lastUpdate;

		///Delay in seconds to re-refresh the console.
		const double refreshRate;

		std::array<std::string, CONSOLE_HISTORY> commandHistory;
		int historyStatus;
	};

	using AnnConsolePtr = std::shared_ptr<AnnConsole>;
}

#endif<commit_msg>add missing doc comments<commit_after>/**
 * \file AnnConsole.hpp
 * \brief Represent the output console that can be shown by calling AnnEngine::toggleOnScreenConsole()
 *		  This class create handle the texture buffer and text rendering for text display
 * \author A. Brainville (Ybalrid)
 */

#ifndef	ANNCONSOLE
#define ANNCONSOLE

#include "systemMacro.h"
#include "AnnTypes.h"
#include "AnnKeyCode.h"
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <Ogre.h>
#include <Overlay/OgreFont.h>
#include <Overlay/OgreFontManager.h>
#include <OgreRenderOperation.h>
#include <Hlms/Unlit/OgreHlmsUnlitDatablock.h>
#include <OgreHardwarePixelBuffer.h>

#include "AnnSubsystem.hpp"

namespace Annwvyn
{
	///In engine - On screen floating console
	class AnnDllExport AnnConsole : public AnnSubSystem
	{
	public:

		static constexpr auto CONSOLE_BUFFER = 17;
		static constexpr auto MAX_CONSOLE_LOG_WIDTH = 72;
		static constexpr auto BASE = 256;
		static constexpr auto MARGIN = 4;
		static constexpr auto CONSOLE_HISTORY = 10;

		///Construct the console. This should only be called by AnnEngine itself when the camera and ogre are operational
		AnnConsole();
		virtual ~AnnConsole();

		///Add text to the console buffer. The console buffer will keep CONSOLE_BUFFER lines of messages in memory only
		/// \param string text to append to the console
		void append(std::string string);

		///Set arbitrary the visibility state of the console. Visible if no arg given, hide it if visibility = false
		void setVisible(bool visibility = true);

		///Toggle the console.
		void toggle();

		///True if text has been updated on the console and the console is visible.
		bool needUpdate() override;

		///Update the console by filling it with background texture then blitting text on it.
		///Can take some computing time depending on the size/resolution of the textures and buffer
		void update() override;

		///Move the console where it should
		void syncConsolePosition() const;

		///Clear the text draw buffer of the console
		void bufferClear();

		///Array of forbidden keyword to check
		std::array<const char*, 2> forbidden = { {"var", "auto"} };

		///This piece of code if from the Ogre Wiki. Write text to a texture using Ogre::FontManager to create glyphs
		static void WriteToTexture(const Ogre::String& str, Ogre::TexturePtr destTexture, Ogre::Image::Box destRectangle, Ogre::Font* font, const Ogre::ColourValue &color, char justify = 'l', bool wordwrap = false);

		///return true if pointed to an empty slot
		bool setFromPointedHistory();

		///Method to be called for navigation keys
		void notifyNavigationKey(KeyCode::code code);
	private:

		///Cleanup and run the user input.
		void runInput(std::string& input);

		///Push the inputed text into the command history
		void addToHistory(const std::string& input);

		///Run input that are not regular script commands
		bool runSpecialInput(const std::string& input);

		///Return true if the given string match with any of the forbidden keyword int the array
		bool isForbdiden(const std::string& keyword);

		///True if content of the buffer has been modified
		bool modified;

		///Array of 3D points to construct the render plane
		AnnVect3 points[4];

		///Array of UV coordinates to constructed the render plane
		AnnVect2 textCoord[4];

		///Buffer of string objects
		std::string buffer[CONSOLE_BUFFER];

		///The surface used to display (aka the render plane)
		Ogre::ManualObject* displaySurface;

		///Node where the console is attached
		Ogre::SceneNode* consoleNode;

		///The actual texture of the display
		Ogre::TexturePtr texture;

		///Position of the plane using the camera as reference
		AnnVect3 offset;

		///Background texture, should be a random PNG file from the CORE resources
		Ogre::TexturePtr background;

		///OpenGL Texture IDs, to use glCopyImageSubData to clone texture quickly.
		GLuint backgroundID, textureID;

		///There's a small optimization we can do on the way we copy a texture to another, but the opengl function is available on GL4.3+ hardware only.
		bool openGL43plus;

		///The font object used, should be Vera Mono in true type format from the Gnome project, included in CORE resources
		Ogre::FontPtr font;

		///If false, the console is not visible
		bool visibility;

		///Timestamp in seconds since the start of the game the last console refresh was performed
		double lastUpdate;

		///Delay in seconds to re-refresh the console.
		const double refreshRate;

		///Buffer of strings containing past run commands
		std::array<std::string, CONSOLE_HISTORY> commandHistory;

		///Status of the history
		int historyStatus;
	};

	using AnnConsolePtr = std::shared_ptr<AnnConsole>;
}

#endif<|endoftext|>


<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

#include "MonitorStore.h"
#include "common/Clock.h"

#include "config.h"

#define DOUT_SUBSYS mon
#undef dout_prefix
#define dout_prefix _prefix(dir)
static ostream& _prefix(const string& dir) {
  return *_dout << "store(" << dir << ") ";
}

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <sstream>
#include <sys/file.h>

MonitorStore::Error MonitorStore::Error::
FromErrno(const char *prefix, const char *prefix2, int errno_)
{
  char buf[128];
  const char *b2 = strerror_r(errno_, buf, sizeof(buf));
  ostringstream oss;
  oss << prefix << prefix2 << ": " << b2 << " (" << errno_ << ")";
  return MonitorStore::Error(oss.str());
}

MonitorStore::Error::
Error(const std::string &str_) : str(str_) { }

MonitorStore::Error::
~Error() throw () { }

const char *MonitorStore::Error::
what() const throw ()
{
  return str.c_str();
}

int MonitorStore::mount()
{
  char t[1024];

  dout(1) << "mount" << dendl;
  // verify dir exists
  DIR *d = ::opendir(dir.c_str());
  if (!d) {
    dout(1) << "basedir " << dir << " dne" << dendl;
    return -ENOENT;
  }
  ::closedir(d);

  // open lockfile
  snprintf(t, sizeof(t), "%s/lock", dir.c_str());
  lock_fd = ::open(t, O_CREAT|O_RDWR, 0600);
  if (lock_fd < 0)
    return -errno;
  struct flock l;
  memset(&l, 0, sizeof(l));
  l.l_type = F_WRLCK;
  l.l_whence = SEEK_SET;
  l.l_start = 0;
  l.l_len = 0;
  int r = ::fcntl(lock_fd, F_SETLK, &l);
  if (r < 0) {
    dout(0) << "failed to lock " << t << ", is another cmon still running?" << dendl;
    return -errno;
  }

  if (g_conf.chdir && g_conf.chdir[0] && dir[0] != '/') {
    // combine it with the cwd, in case fuse screws things up (i.e. fakefuse)
    string old = dir;
    char cwd[1024];
    getcwd(cwd, sizeof(cwd));
    dir = cwd;
    dir += "/";
    dir += old;
  }
  return 0;
}

int MonitorStore::umount()
{
  ::close(lock_fd);
  return 0;
}

int MonitorStore::mkfs()
{
  char cmd[1024];
  snprintf(cmd, sizeof(cmd), "test -d %s && /bin/rm -rf %s ; mkdir -p %s",
	   dir.c_str(), dir.c_str(), dir.c_str());
  dout(6) << "MonitorStore::mkfs: running command '" << cmd << "'" << dendl;
  int res = system(cmd);
  int r = WEXITSTATUS(res);
  if (r) {
    dout(0) << "FAILED to create monfs at " << dir.c_str() << " for "
	    << g_conf.id << ": cmd '" << cmd << "'" << dendl;
    return r;
  }

  dout(0) << "created monfs at " << dir.c_str() << " for " << g_conf.id << dendl;
  return 0;
}

void MonitorStore::sync()
{
  dout(10) << "sync" << dendl;
  ::sync();
}

version_t MonitorStore::get_int(const char *a, const char *b)
{
  char fn[1024];
  if (b)
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  else
    snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);

  FILE *f = ::fopen(fn, "r");
  if (!f)
    return 0;

  char buf[20];
  ::fgets(buf, 20, f);
  ::fclose(f);

  version_t val = atoi(buf);

  if (b) {
    dout(15) << "get_int " << a << "/" << b << " = " << val << dendl;
  } else {
    dout(15) << "get_int " << a << " = " << val << dendl;
  }
  return val;
}

void MonitorStore::put_int(version_t val, const char *a, const char *b, bool sync)
{
  char fn[1024];
  snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  if (b) {
    ::mkdir(fn, 0755);
    dout(15) << "set_int " << a << "/" << b << " = " << val << dendl;
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    dout(15) << "set_int " << a << " = " << val << dendl;
  }

  char vs[30];
  snprintf(vs, sizeof(vs), "%lld\n", (unsigned long long)val);

  char tfn[1024];
  snprintf(tfn, sizeof(tfn), "%s.new", fn);

  int fd = ::open(tfn, O_WRONLY|O_CREAT, 0644);
  assert(fd >= 0);
  ::write(fd, vs, strlen(vs));
  if (sync)
    ::fsync(fd);
  ::close(fd);
  ::rename(tfn, fn);
}

// ----------------------------------------
// buffers

bool MonitorStore::exists_bl_ss(const char *a, const char *b)
{
  char fn[1024];
  if (b) {
    dout(15) << "exists_bl " << a << "/" << b << dendl;
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    dout(15) << "exists_bl " << a << dendl;
    snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  }

  struct stat st;
  int r = ::stat(fn, &st);
  //char buf[80];
  //dout(15) << "exists_bl stat " << fn << " r=" << r << " errno " << errno << " " << strerror_r(errno, buf, sizeof(buf)) << dendl;
  return r == 0;
}

int MonitorStore::erase_ss(const char *a, const char *b)
{
  char fn[1024];
  if (b) {
    dout(15) << "erase_ss " << a << "/" << b << dendl;
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    dout(15) << "erase_ss " << a << dendl;
    snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  }
  return ::unlink(fn);
}

int MonitorStore::get_bl_ss(bufferlist& bl, const char *a, const char *b)
{
  char fn[1024];
  if (b) {
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  }

  int fd = ::open(fn, O_RDONLY);
  if (fd < 0) {
    char buf[80];
    if (b) {
      dout(15) << "get_bl " << a << "/" << b << " " << strerror_r(errno, buf, sizeof(buf)) << dendl;
    } else {
      dout(15) << "get_bl " << a << " " << strerror_r(errno, buf, sizeof(buf)) << dendl;
    }
    return -errno;
  }

  // get size
  struct stat st;
  int rc = ::fstat(fd, &st);
  assert(rc == 0);
  __int32_t len = st.st_size;

  // read buffer
  bl.clear();
  bufferptr bp(len);
  int off = 0;
  while (off < len) {
    dout(20) << "reading at off " << off << " of " << len << dendl;
    int r = ::read(fd, bp.c_str()+off, len-off);
    if (r < 0) {
      char buf[80];
      dout(0) << "errno on read " << strerror_r(errno, buf, sizeof(buf)) << dendl;
    }
    assert(r>0);
    off += r;
  }
  bl.append(bp);
  ::close(fd);

  if (b) {
    dout(15) << "get_bl " << a << "/" << b << " = " << bl.length() << " bytes" << dendl;
  } else {
    dout(15) << "get_bl " << a << " = " << bl.length() << " bytes" << dendl;
  }

  return len;
}

int MonitorStore::write_bl_ss(bufferlist& bl, const char *a, const char *b, bool append, bool sync)
{
  char fn[1024];
  snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  if (b) {
    ::mkdir(fn, 0755);
    dout(15) << "put_bl " << a << "/" << b << " = " << bl.length() << " bytes" << dendl;
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    dout(15) << "put_bl " << a << " = " << bl.length() << " bytes" << dendl;
  }

  char tfn[1024];
  int err = 0;
  int fd;
  if (append) {
    fd = ::open(fn, O_WRONLY|O_CREAT|O_APPEND, 0644);
    if (fd < 0)
      throw Error::FromErrno("failed to open for append: ", fn, errno);
  } else {
    snprintf(tfn, sizeof(tfn), "%s.new", fn);
    fd = ::open(tfn, O_WRONLY|O_CREAT, 0644);
    if (fd < 0)
      throw Error::FromErrno("failed to open: ", tfn, errno);
  }

  err = bl.write_fd(fd);

  if (sync && !err)
    ::fsync(fd);
  ::close(fd);
  if (!append && !err) {
    ::rename(tfn, fn);
  }

  assert(!err);  // for now

  return err;
}

<commit_msg>mon: MonitorStore::mkfs: use run_cmd<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

#include "MonitorStore.h"
#include "common/Clock.h"
#include "common/run_cmd.h"

#include "config.h"

#define DOUT_SUBSYS mon
#undef dout_prefix
#define dout_prefix _prefix(dir)
static ostream& _prefix(const string& dir) {
  return *_dout << "store(" << dir << ") ";
}

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <sstream>
#include <sys/file.h>

MonitorStore::Error MonitorStore::Error::
FromErrno(const char *prefix, const char *prefix2, int errno_)
{
  char buf[128];
  const char *b2 = strerror_r(errno_, buf, sizeof(buf));
  ostringstream oss;
  oss << prefix << prefix2 << ": " << b2 << " (" << errno_ << ")";
  return MonitorStore::Error(oss.str());
}

MonitorStore::Error::
Error(const std::string &str_) : str(str_) { }

MonitorStore::Error::
~Error() throw () { }

const char *MonitorStore::Error::
what() const throw ()
{
  return str.c_str();
}

int MonitorStore::mount()
{
  char t[1024];

  dout(1) << "mount" << dendl;
  // verify dir exists
  DIR *d = ::opendir(dir.c_str());
  if (!d) {
    dout(1) << "basedir " << dir << " dne" << dendl;
    return -ENOENT;
  }
  ::closedir(d);

  // open lockfile
  snprintf(t, sizeof(t), "%s/lock", dir.c_str());
  lock_fd = ::open(t, O_CREAT|O_RDWR, 0600);
  if (lock_fd < 0)
    return -errno;
  struct flock l;
  memset(&l, 0, sizeof(l));
  l.l_type = F_WRLCK;
  l.l_whence = SEEK_SET;
  l.l_start = 0;
  l.l_len = 0;
  int r = ::fcntl(lock_fd, F_SETLK, &l);
  if (r < 0) {
    dout(0) << "failed to lock " << t << ", is another cmon still running?" << dendl;
    return -errno;
  }

  if (g_conf.chdir && g_conf.chdir[0] && dir[0] != '/') {
    // combine it with the cwd, in case fuse screws things up (i.e. fakefuse)
    string old = dir;
    char cwd[1024];
    getcwd(cwd, sizeof(cwd));
    dir = cwd;
    dir += "/";
    dir += old;
  }
  return 0;
}

int MonitorStore::umount()
{
  ::close(lock_fd);
  return 0;
}

int MonitorStore::mkfs()
{
  int ret = run_cmd("rm", "-rf", dir.c_str(), NULL);
  if (ret) {
    derr << "MonitorStore::mkfs: failed to remove " << dir
	 << ": rm returned " << ret << dendl;
    return ret;
  }

  ret = run_cmd("mkdir", "-p", dir.c_str(), NULL);
  if (ret) {
    derr << "MonitorStore::mkfs: failed to mkdir -p " << dir
	 << ": mkdir returned " << ret << dendl;
    return ret;
  }

  dout(0) << "created monfs at " << dir.c_str() << " for " << g_conf.id << dendl;
  return 0;
}

void MonitorStore::sync()
{
  dout(10) << "sync" << dendl;
  ::sync();
}

version_t MonitorStore::get_int(const char *a, const char *b)
{
  char fn[1024];
  if (b)
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  else
    snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);

  FILE *f = ::fopen(fn, "r");
  if (!f)
    return 0;

  char buf[20];
  ::fgets(buf, 20, f);
  ::fclose(f);

  version_t val = atoi(buf);

  if (b) {
    dout(15) << "get_int " << a << "/" << b << " = " << val << dendl;
  } else {
    dout(15) << "get_int " << a << " = " << val << dendl;
  }
  return val;
}

void MonitorStore::put_int(version_t val, const char *a, const char *b, bool sync)
{
  char fn[1024];
  snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  if (b) {
    ::mkdir(fn, 0755);
    dout(15) << "set_int " << a << "/" << b << " = " << val << dendl;
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    dout(15) << "set_int " << a << " = " << val << dendl;
  }

  char vs[30];
  snprintf(vs, sizeof(vs), "%lld\n", (unsigned long long)val);

  char tfn[1024];
  snprintf(tfn, sizeof(tfn), "%s.new", fn);

  int fd = ::open(tfn, O_WRONLY|O_CREAT, 0644);
  assert(fd >= 0);
  ::write(fd, vs, strlen(vs));
  if (sync)
    ::fsync(fd);
  ::close(fd);
  ::rename(tfn, fn);
}

// ----------------------------------------
// buffers

bool MonitorStore::exists_bl_ss(const char *a, const char *b)
{
  char fn[1024];
  if (b) {
    dout(15) << "exists_bl " << a << "/" << b << dendl;
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    dout(15) << "exists_bl " << a << dendl;
    snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  }

  struct stat st;
  int r = ::stat(fn, &st);
  //char buf[80];
  //dout(15) << "exists_bl stat " << fn << " r=" << r << " errno " << errno << " " << strerror_r(errno, buf, sizeof(buf)) << dendl;
  return r == 0;
}

int MonitorStore::erase_ss(const char *a, const char *b)
{
  char fn[1024];
  if (b) {
    dout(15) << "erase_ss " << a << "/" << b << dendl;
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    dout(15) << "erase_ss " << a << dendl;
    snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  }
  return ::unlink(fn);
}

int MonitorStore::get_bl_ss(bufferlist& bl, const char *a, const char *b)
{
  char fn[1024];
  if (b) {
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  }

  int fd = ::open(fn, O_RDONLY);
  if (fd < 0) {
    char buf[80];
    if (b) {
      dout(15) << "get_bl " << a << "/" << b << " " << strerror_r(errno, buf, sizeof(buf)) << dendl;
    } else {
      dout(15) << "get_bl " << a << " " << strerror_r(errno, buf, sizeof(buf)) << dendl;
    }
    return -errno;
  }

  // get size
  struct stat st;
  int rc = ::fstat(fd, &st);
  assert(rc == 0);
  __int32_t len = st.st_size;

  // read buffer
  bl.clear();
  bufferptr bp(len);
  int off = 0;
  while (off < len) {
    dout(20) << "reading at off " << off << " of " << len << dendl;
    int r = ::read(fd, bp.c_str()+off, len-off);
    if (r < 0) {
      char buf[80];
      dout(0) << "errno on read " << strerror_r(errno, buf, sizeof(buf)) << dendl;
    }
    assert(r>0);
    off += r;
  }
  bl.append(bp);
  ::close(fd);

  if (b) {
    dout(15) << "get_bl " << a << "/" << b << " = " << bl.length() << " bytes" << dendl;
  } else {
    dout(15) << "get_bl " << a << " = " << bl.length() << " bytes" << dendl;
  }

  return len;
}

int MonitorStore::write_bl_ss(bufferlist& bl, const char *a, const char *b, bool append, bool sync)
{
  char fn[1024];
  snprintf(fn, sizeof(fn), "%s/%s", dir.c_str(), a);
  if (b) {
    ::mkdir(fn, 0755);
    dout(15) << "put_bl " << a << "/" << b << " = " << bl.length() << " bytes" << dendl;
    snprintf(fn, sizeof(fn), "%s/%s/%s", dir.c_str(), a, b);
  } else {
    dout(15) << "put_bl " << a << " = " << bl.length() << " bytes" << dendl;
  }

  char tfn[1024];
  int err = 0;
  int fd;
  if (append) {
    fd = ::open(fn, O_WRONLY|O_CREAT|O_APPEND, 0644);
    if (fd < 0)
      throw Error::FromErrno("failed to open for append: ", fn, errno);
  } else {
    snprintf(tfn, sizeof(tfn), "%s.new", fn);
    fd = ::open(tfn, O_WRONLY|O_CREAT, 0644);
    if (fd < 0)
      throw Error::FromErrno("failed to open: ", tfn, errno);
  }

  err = bl.write_fd(fd);

  if (sync && !err)
    ::fsync(fd);
  ::close(fd);
  if (!append && !err) {
    ::rename(tfn, fn);
  }

  assert(!err);  // for now

  return err;
}

<|endoftext|>


<commit_before>/* Copyright (C) 2005-2011, Thorvald Natvig <thorvald@natvig.com>

   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   - Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   - Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.
   - Neither the name of the Mumble Developers nor the names of its
     contributors may be used to endorse or promote products derived from this
     software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "mumble_pch.hpp"

#include "UserView.h"

#include "Channel.h"
#include "ClientUser.h"
#include "Log.h"
#include "Global.h"
#include "MainWindow.h"
#include "ServerHandler.h"
#include "UserModel.h"

/*!
  \fn bool UserView::event(QEvent *evt)
  This implementation contains a special handler to display
  custom what's this entries for items. All other events are
  passed on.
*/

/*!
  \fn void UserView::mouseReleaseEvent(QMouseEvent *evt)
  This function is used to create custom behaviour when clicking
  on user/channel flags (e.g. showing the comment)
*/

/*!
  \fn void UserView::activated(const QModelIndex &idx)
  Depending on whether idx points to a channel or user this function
  either moves the player to the channel or opens a message window.
  This Slot connected to the objects activated signal. The activated
  signal could, for example, be triggered by doubleclick.
*/

/*!
  \fn void UserView::keyboardSearch(const QString &search)
  This implementation provides a recursive realtime search over
  the whole channel tree. It also features delayed selection
  with with automatic expanding of folded channels.
*/

UserDelegate::UserDelegate(QObject *p) : QStyledItemDelegate(p) {
}

void UserDelegate::paint(QPainter * painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
	const QAbstractItemModel *m = index.model();
	const QModelIndex idxc1 = index.sibling(index.row(), 1);
	QVariant data = m->data(idxc1);
	QList<QVariant> ql = data.toList();

	painter->save();

	QStyleOptionViewItemV4 o = option;
	initStyleOption(&o, index);

	QStyle *style = o.widget->style();
	QIcon::Mode iconMode = QIcon::Normal;

	QPalette::ColorRole colorRole = ((o.state & QStyle::State_Selected) ? QPalette::HighlightedText : QPalette::Text);
#ifdef Q_OS_WIN
	// Qt's Vista Style has the wrong highlight color for treeview items
	// We can't check for QStyleSheetStyle so we have to search the children list search for a QWindowsVistaStyle
	if (qobject_cast<QWindowsVistaStyle *>(style) || style->findChild<QWindowsVistaStyle *>()) {
		colorRole = QPalette::Text;
	}
#endif

	// draw background
	style->drawPrimitive(QStyle::PE_PanelItemViewItem, &o, painter, o.widget);

	// resize rect to exclude the flag icons
	o.rect = option.rect.adjusted(0, 0, -18 * ql.count(), 0);

	// draw icon
	QRect decorationRect = style->subElementRect(QStyle::SE_ItemViewItemDecoration, &o, o.widget);
	o.icon.paint(painter, decorationRect, o.decorationAlignment, iconMode, QIcon::On);

	// draw text
	QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &o, o.widget);
	QString itemText = o.fontMetrics.elidedText(o.text, o.textElideMode, textRect.width());
	painter->setFont(o.font);
	style->drawItemText(painter, textRect, o.displayAlignment, o.palette, true, itemText, colorRole);

	// draw flag icons to original rect
	QRect ps = QRect(option.rect.right() - (ql.size() * 18), option.rect.y(), ql.size() * 18, option.rect.height());
	for (int i = 0; i < ql.size(); ++i) {
		QRect r = ps;
		r.setSize(QSize(16, 16));
		r.translate(i * 18 + 1, 1);
		QRect p = QStyle::alignedRect(option.direction, option.decorationAlignment, r.size(), r);
		qvariant_cast<QIcon>(ql[i]).paint(painter, p, option.decorationAlignment, iconMode, QIcon::On);
	}

	painter->restore();
}

bool UserDelegate::helpEvent(QHelpEvent *evt, QAbstractItemView *view, const QStyleOptionViewItem &option, const QModelIndex &index) {
	if (index.isValid()) {
		const QAbstractItemModel *m = index.model();
		const QModelIndex idxc1 = index.sibling(index.row(), 1);
		QVariant data = m->data(idxc1);
		QList<QVariant> ql = data.toList();
		int offset = 0;
		offset = ql.size() * 18;
		offset = option.rect.topRight().x() - offset;

		if (evt->pos().x() >= offset) {
			return QStyledItemDelegate::helpEvent(evt, view, option, idxc1);
		}
	}
	return QStyledItemDelegate::helpEvent(evt, view, option, index);
}

UserView::UserView(QWidget *p) : QTreeView(p) {
	setItemDelegate(new UserDelegate(this));

	qtSearch = new QTimer(this);
	qtSearch->setInterval(QApplication::keyboardInputInterval());
	qtSearch->setSingleShot(true);

	connect(this, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(nodeActivated(const QModelIndex &)));

	connect(qtSearch, SIGNAL(timeout()), this, SLOT(selectSearchResult()));
}

bool UserView::event(QEvent *evt) {
	if (evt->type() == QEvent::WhatsThisClicked) {
		QWhatsThisClickedEvent *qwtce = static_cast<QWhatsThisClickedEvent *>(evt);
		QDesktopServices::openUrl(qwtce->href());
		evt->accept();
		return true;
	}
	return QTreeView::event(evt);
}

void UserView::mouseReleaseEvent(QMouseEvent *evt) {
	QPoint qpos = evt->pos();

	QModelIndex idx = indexAt(qpos);
	if ((evt->button() == Qt::LeftButton) && idx.isValid()) {
		UserModel *um = static_cast<UserModel *>(model());
		ClientUser *cu = um->getUser(idx);
		Channel * c = um->getChannel(idx);
		if ((cu && ! cu->qbaCommentHash.isEmpty()) ||
		        (! cu && c && ! c->qbaDescHash.isEmpty())) {
			QRect r = visualRect(idx);

			int offset = 18;

			if (cu) {
				// Calculate pixel offset of comment flag
				if (cu->bRecording)
					offset += 18;
				if (cu->bPrioritySpeaker)
					offset += 18;
				if (cu->bMute)
					offset += 18;
				if (cu->bSuppress)
					offset += 18;
				if (cu->bSelfMute)
					offset += 18;
				if (cu->bLocalMute)
					offset += 18;
				if (cu->bSelfDeaf)
					offset += 18;
				if (cu->bDeaf)
					offset += 18;
				if (! cu->qsFriendName.isEmpty())
					offset += 18;
				if (cu->iId >= 0)
					offset += 18;
			}

			offset = r.topRight().x() - offset;

			if ((qpos.x() >= offset) && (qpos.x() <= (offset+18))) {
				QString str = um->data(idx, Qt::ToolTipRole).toString();
				if (str.isEmpty()) {
					um->bClicked = true;
				} else {
					QWhatsThis::showText(viewport()->mapToGlobal(r.bottomRight()), str, this);
					um->seenComment(idx);
				}
				return;
			}
		}
	}
	QTreeView::mouseReleaseEvent(evt);
}

void UserView::keyPressEvent(QKeyEvent *ev) {
	if (ev->key() == Qt::Key_Return || ev->key() == Qt::Key_Enter)
		UserView::nodeActivated(currentIndex());
	QTreeView::keyPressEvent(ev);
}

void UserView::nodeActivated(const QModelIndex &idx) {
	UserModel *um = static_cast<UserModel *>(model());
	ClientUser *p = um->getUser(idx);
	if (p) {
		g.mw->openTextMessageDialog(p);
		return;
	}

	Channel *c = um->getChannel(idx);
	if (c) {
		// if a channel is activated join it
		g.sh->joinChannel(c->iId);
	}
}

void UserView::keyboardSearch(const QString &search) {

	if (qtSearch->isActive()) {
		qpmiSearch = QPersistentModelIndex();
		qtSearch->stop();
	}

	bool forceSkip = false;

	if (tSearch.restart() > (QApplication::keyboardInputInterval() * 1000ULL)) {
		qsSearch = QString();
		forceSkip = true;
	}

	bool isBackspace = (search.length() == 1) && (search.at(0).row() == 0) && (search.at(0).cell() == 8);
	if (isBackspace) {
		if (! qsSearch.isEmpty())
			qsSearch = qsSearch.left(qsSearch.length()-1);
	} else {
		qsSearch += search;
	}

	// Try default search (which doesn't recurse non-expanded items) and see if it returns something "valid"
	QTreeView::keyboardSearch(search);
	QModelIndex start = currentIndex();
	if (start.isValid() && model()->data(start, Qt::DisplayRole).toString().startsWith(qsSearch, Qt::CaseInsensitive))
		return;

	if (forceSkip && start.isValid())
		start = indexBelow(start);

	if (! start.isValid())
		start = model()->index(0, 0, QModelIndex());

	QModelIndexList qmil = model()->match(start, Qt::DisplayRole, qsSearch, 1, Qt::MatchFlags(Qt::MatchStartsWith | Qt::MatchWrap | Qt::MatchRecursive));
	if (qmil.count() == 0)
		qmil = model()->match(start, Qt::DisplayRole, qsSearch, 1, Qt::MatchFlags(Qt::MatchContains | Qt::MatchWrap | Qt::MatchRecursive));

	if (qmil.isEmpty())
		return;

	QModelIndex qmi = qmil.at(0);

	QModelIndex p = qmi.parent();
	bool visible = true;
	while (visible && p.isValid()) {
		visible = visible && isExpanded(p);
		p = p.parent();
	}

	if (visible)
		selectionModel()->setCurrentIndex(qmi, QItemSelectionModel::ClearAndSelect);
	else {
		qpmiSearch = qmi;
		qtSearch->start();
	}
}

void UserView::selectSearchResult() {
	if (qpmiSearch.isValid()) {
		selectionModel()->setCurrentIndex(qpmiSearch, QItemSelectionModel::ClearAndSelect);
	}
	qpmiSearch = QPersistentModelIndex();
}
<commit_msg>UserView: fix comment icon click target if ignore text messages is enabled<commit_after>/* Copyright (C) 2005-2011, Thorvald Natvig <thorvald@natvig.com>

   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   - Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   - Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.
   - Neither the name of the Mumble Developers nor the names of its
     contributors may be used to endorse or promote products derived from this
     software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "mumble_pch.hpp"

#include "UserView.h"

#include "Channel.h"
#include "ClientUser.h"
#include "Log.h"
#include "Global.h"
#include "MainWindow.h"
#include "ServerHandler.h"
#include "UserModel.h"

/*!
  \fn bool UserView::event(QEvent *evt)
  This implementation contains a special handler to display
  custom what's this entries for items. All other events are
  passed on.
*/

/*!
  \fn void UserView::mouseReleaseEvent(QMouseEvent *evt)
  This function is used to create custom behaviour when clicking
  on user/channel flags (e.g. showing the comment)
*/

/*!
  \fn void UserView::activated(const QModelIndex &idx)
  Depending on whether idx points to a channel or user this function
  either moves the player to the channel or opens a message window.
  This Slot connected to the objects activated signal. The activated
  signal could, for example, be triggered by doubleclick.
*/

/*!
  \fn void UserView::keyboardSearch(const QString &search)
  This implementation provides a recursive realtime search over
  the whole channel tree. It also features delayed selection
  with with automatic expanding of folded channels.
*/

UserDelegate::UserDelegate(QObject *p) : QStyledItemDelegate(p) {
}

void UserDelegate::paint(QPainter * painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
	const QAbstractItemModel *m = index.model();
	const QModelIndex idxc1 = index.sibling(index.row(), 1);
	QVariant data = m->data(idxc1);
	QList<QVariant> ql = data.toList();

	painter->save();

	QStyleOptionViewItemV4 o = option;
	initStyleOption(&o, index);

	QStyle *style = o.widget->style();
	QIcon::Mode iconMode = QIcon::Normal;

	QPalette::ColorRole colorRole = ((o.state & QStyle::State_Selected) ? QPalette::HighlightedText : QPalette::Text);
#ifdef Q_OS_WIN
	// Qt's Vista Style has the wrong highlight color for treeview items
	// We can't check for QStyleSheetStyle so we have to search the children list search for a QWindowsVistaStyle
	if (qobject_cast<QWindowsVistaStyle *>(style) || style->findChild<QWindowsVistaStyle *>()) {
		colorRole = QPalette::Text;
	}
#endif

	// draw background
	style->drawPrimitive(QStyle::PE_PanelItemViewItem, &o, painter, o.widget);

	// resize rect to exclude the flag icons
	o.rect = option.rect.adjusted(0, 0, -18 * ql.count(), 0);

	// draw icon
	QRect decorationRect = style->subElementRect(QStyle::SE_ItemViewItemDecoration, &o, o.widget);
	o.icon.paint(painter, decorationRect, o.decorationAlignment, iconMode, QIcon::On);

	// draw text
	QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &o, o.widget);
	QString itemText = o.fontMetrics.elidedText(o.text, o.textElideMode, textRect.width());
	painter->setFont(o.font);
	style->drawItemText(painter, textRect, o.displayAlignment, o.palette, true, itemText, colorRole);

	// draw flag icons to original rect
	QRect ps = QRect(option.rect.right() - (ql.size() * 18), option.rect.y(), ql.size() * 18, option.rect.height());
	for (int i = 0; i < ql.size(); ++i) {
		QRect r = ps;
		r.setSize(QSize(16, 16));
		r.translate(i * 18 + 1, 1);
		QRect p = QStyle::alignedRect(option.direction, option.decorationAlignment, r.size(), r);
		qvariant_cast<QIcon>(ql[i]).paint(painter, p, option.decorationAlignment, iconMode, QIcon::On);
	}

	painter->restore();
}

bool UserDelegate::helpEvent(QHelpEvent *evt, QAbstractItemView *view, const QStyleOptionViewItem &option, const QModelIndex &index) {
	if (index.isValid()) {
		const QAbstractItemModel *m = index.model();
		const QModelIndex idxc1 = index.sibling(index.row(), 1);
		QVariant data = m->data(idxc1);
		QList<QVariant> ql = data.toList();
		int offset = 0;
		offset = ql.size() * 18;
		offset = option.rect.topRight().x() - offset;

		if (evt->pos().x() >= offset) {
			return QStyledItemDelegate::helpEvent(evt, view, option, idxc1);
		}
	}
	return QStyledItemDelegate::helpEvent(evt, view, option, index);
}

UserView::UserView(QWidget *p) : QTreeView(p) {
	setItemDelegate(new UserDelegate(this));

	qtSearch = new QTimer(this);
	qtSearch->setInterval(QApplication::keyboardInputInterval());
	qtSearch->setSingleShot(true);

	connect(this, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(nodeActivated(const QModelIndex &)));

	connect(qtSearch, SIGNAL(timeout()), this, SLOT(selectSearchResult()));
}

bool UserView::event(QEvent *evt) {
	if (evt->type() == QEvent::WhatsThisClicked) {
		QWhatsThisClickedEvent *qwtce = static_cast<QWhatsThisClickedEvent *>(evt);
		QDesktopServices::openUrl(qwtce->href());
		evt->accept();
		return true;
	}
	return QTreeView::event(evt);
}

void UserView::mouseReleaseEvent(QMouseEvent *evt) {
	QPoint qpos = evt->pos();

	QModelIndex idx = indexAt(qpos);
	if ((evt->button() == Qt::LeftButton) && idx.isValid()) {
		UserModel *um = static_cast<UserModel *>(model());
		ClientUser *cu = um->getUser(idx);
		Channel * c = um->getChannel(idx);
		if ((cu && ! cu->qbaCommentHash.isEmpty()) ||
		        (! cu && c && ! c->qbaDescHash.isEmpty())) {
			QRect r = visualRect(idx);

			int offset = 18;

			if (cu) {
				// Calculate pixel offset of comment flag
				if (cu->bLocalIgnore)
					offset += 18;
				if (cu->bRecording)
					offset += 18;
				if (cu->bPrioritySpeaker)
					offset += 18;
				if (cu->bMute)
					offset += 18;
				if (cu->bSuppress)
					offset += 18;
				if (cu->bSelfMute)
					offset += 18;
				if (cu->bLocalMute)
					offset += 18;
				if (cu->bSelfDeaf)
					offset += 18;
				if (cu->bDeaf)
					offset += 18;
				if (! cu->qsFriendName.isEmpty())
					offset += 18;
				if (cu->iId >= 0)
					offset += 18;
			}

			offset = r.topRight().x() - offset;

			if ((qpos.x() >= offset) && (qpos.x() <= (offset+18))) {
				QString str = um->data(idx, Qt::ToolTipRole).toString();
				if (str.isEmpty()) {
					um->bClicked = true;
				} else {
					QWhatsThis::showText(viewport()->mapToGlobal(r.bottomRight()), str, this);
					um->seenComment(idx);
				}
				return;
			}
		}
	}
	QTreeView::mouseReleaseEvent(evt);
}

void UserView::keyPressEvent(QKeyEvent *ev) {
	if (ev->key() == Qt::Key_Return || ev->key() == Qt::Key_Enter)
		UserView::nodeActivated(currentIndex());
	QTreeView::keyPressEvent(ev);
}

void UserView::nodeActivated(const QModelIndex &idx) {
	UserModel *um = static_cast<UserModel *>(model());
	ClientUser *p = um->getUser(idx);
	if (p) {
		g.mw->openTextMessageDialog(p);
		return;
	}

	Channel *c = um->getChannel(idx);
	if (c) {
		// if a channel is activated join it
		g.sh->joinChannel(c->iId);
	}
}

void UserView::keyboardSearch(const QString &search) {

	if (qtSearch->isActive()) {
		qpmiSearch = QPersistentModelIndex();
		qtSearch->stop();
	}

	bool forceSkip = false;

	if (tSearch.restart() > (QApplication::keyboardInputInterval() * 1000ULL)) {
		qsSearch = QString();
		forceSkip = true;
	}

	bool isBackspace = (search.length() == 1) && (search.at(0).row() == 0) && (search.at(0).cell() == 8);
	if (isBackspace) {
		if (! qsSearch.isEmpty())
			qsSearch = qsSearch.left(qsSearch.length()-1);
	} else {
		qsSearch += search;
	}

	// Try default search (which doesn't recurse non-expanded items) and see if it returns something "valid"
	QTreeView::keyboardSearch(search);
	QModelIndex start = currentIndex();
	if (start.isValid() && model()->data(start, Qt::DisplayRole).toString().startsWith(qsSearch, Qt::CaseInsensitive))
		return;

	if (forceSkip && start.isValid())
		start = indexBelow(start);

	if (! start.isValid())
		start = model()->index(0, 0, QModelIndex());

	QModelIndexList qmil = model()->match(start, Qt::DisplayRole, qsSearch, 1, Qt::MatchFlags(Qt::MatchStartsWith | Qt::MatchWrap | Qt::MatchRecursive));
	if (qmil.count() == 0)
		qmil = model()->match(start, Qt::DisplayRole, qsSearch, 1, Qt::MatchFlags(Qt::MatchContains | Qt::MatchWrap | Qt::MatchRecursive));

	if (qmil.isEmpty())
		return;

	QModelIndex qmi = qmil.at(0);

	QModelIndex p = qmi.parent();
	bool visible = true;
	while (visible && p.isValid()) {
		visible = visible && isExpanded(p);
		p = p.parent();
	}

	if (visible)
		selectionModel()->setCurrentIndex(qmi, QItemSelectionModel::ClearAndSelect);
	else {
		qpmiSearch = qmi;
		qtSearch->start();
	}
}

void UserView::selectSearchResult() {
	if (qpmiSearch.isValid()) {
		selectionModel()->setCurrentIndex(qpmiSearch, QItemSelectionModel::ClearAndSelect);
	}
	qpmiSearch = QPersistentModelIndex();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>

using namespace std;

#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1

typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;

const double eps = 1e-6;
const ll  LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;

#define x first
#define y second

#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);

int p[2017],dp[2017];
int n;
void Init(){

	menMet(p,2017*sizeof(int),0);
	menset(dp,2017*sizeof(int),0);

	REP(i,1,n)
		scanf("%d",p+i);

	sort(p+1,p+1+n);
	return ;
}

void Solve(){

	int Max=p[n];
	int m;
	scanf("%d",&m);

	m-=5;

	REP(i,1,n-1)
	REP(j,m,p[i])
	dp[j]=max(dp[j],dp[j-p[i]]+p[i]);

	print(m+5-dp[m]-Max);

	return ;
}

int main(){

	freopen("hdu2546.in","r",stdin);

	while(scanf("%d",&n)&&n)
	Init(),Solve();
	return 0;
}<commit_msg>update hdu2546<commit_after>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>

using namespace std;

#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1

typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;

const double eps = 1e-6;
const ll  LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;

#define x first
#define y second

#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);

int p[2017],dp[2017];
int n;
void Init(){

	menset(p,2017*sizeof(int),0);
	memset(dp,2017*sizeof(int),0);

	REP(i,1,n)
		scanf("%d",p+i);

	sort(p+1,p+1+n);
	return ;
}

void Solve(){

	int Max=p[n];
	int m;
	scanf("%d",&m);

	m-=5;

	REP(i,1,n-1)
	REP(j,m,p[i])
	dp[j]=max(dp[j],dp[j-p[i]]+p[i]);

	print(m+5-dp[m]-Max);

	return ;
}

int main(){

	freopen("hdu2546.in","r",stdin);

	while(scanf("%d",&n)&&n)
	Init(),Solve();
	return 0;
}<|endoftext|>


<commit_before>//
// bigram_anal.cc --- Created at 2014-01-30
//
// The MIT License (MIT)
//
// Copyright 2014 ling0322 <ling032x@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include <unordered_map>
#include <string>
#include <map>
#include <vector>
#include <utility>
#include <math.h>
#include <stdio.h>
#include "utils/readable_file.h"
#include "utils/status.h"
#include "milkcat/milkcat.h"

struct Adjacent {
  std::map<int, int> left;
  std::map<int, int> right;
};

constexpr int NOT_CJK = 1000000000;

int GetOrInsert(std::unordered_map<std::string, int> &dict, const std::string &word) {
  auto it = dict.find(word);
  if (it == dict.end()) {
    dict.insert(std::pair<std::string, int>(word, dict.size()));
    return dict.size();
  } else {
    return it->second;
  }
}

// Segment a string specified by text and return as a vector of int, which
// is the id of word defined in dict. And update the vocabulary
std::vector<int> SegmentTextAndUpdateVocabulary(
      const char *text,
      milkcat_t *analyzer,
      std::unordered_map<std::string, int> &dict,
      std::unordered_map<std::string, int> &vocab) {

  std::vector<int> line_words;

  milkcat_cursor_t cursor = milkcat_analyze(analyzer, text);
  milkcat_item_t item;

  while (milkcat_cursor_get_next(&cursor, &item) == MC_OK) {
    if (item.word_type == MC_CHINESE_WORD) {
      line_words.push_back(GetOrInsert(dict, item.word));
      vocab[item.word] += 1;
    } else {
      line_words.push_back(NOT_CJK);
      vocab["-NOT-CJK-"] += 1;
    }
  }

  return line_words;
}

// Update the word_adjacent data from words specified by line_words
void UpdateAdjacent(std::vector<Adjacent> &word_adjacent,
                    std::vector<int> &line_words,
                    int candidate_size) {
  int word_id;
  for (auto it = line_words.begin(); it != line_words.end(); ++it) {
    word_id = *it;
    if (word_id < candidate_size) {
      // OK, find a candidate word

      if (it != line_words.begin())
        word_adjacent[word_id].left[*(it - 1)] += 1;

      if (it != line_words.end() - 1)
        word_adjacent[word_id].right[*(it + 1)] += 1;
    }
  }
}

// Calculates the adjacent entropy from word's adjacent word data
// specified by adjacent
double CalculateAdjacentEntropy(const std::map<int, int> &adjacent) {
  double entropy = 0, probability;
  int total_count = 0;
  for (auto &x: adjacent) {
    total_count += x.second;
  }

  for (auto &x: adjacent) {
    probability = static_cast<double>(x.second) / total_count;
    entropy += -probability * log(probability);
  }

  return entropy;
}

// Use bigram segmentation to analyze a corpus. Candidate to analyze is specified by
// candidate, and the corpus is specified by corpus_path. It would use a temporary file
// called 'candidate_cost.txt' as user dictionary file for MilkCat.
// On success, stores the adjecent entropy in adjacent_entropy, and stores the vocabulary
// of segmentation's result in vocab. On failed set status != Status::OK()
void BigramAnalyze(const std::unordered_map<std::string, float> &candidate,
                   const char *corpus_path,
                   std::unordered_map<std::string, double> &adjacent_entropy,
                   std::unordered_map<std::string, int> &vocab,
                   Status &status) {

  std::unordered_map<std::string, int> dict;
  dict.reserve(500000);

  int candidate_size = candidate.size();
  std::vector<Adjacent> word_adjacent(candidate_size);

  // Put each candidate word into dictionary and assign its word-id
  for (auto &x: candidate) {
    dict.insert(std::pair<std::string, int>(x.first, dict.size()));
  }

  milkcat_model_t *model = milkcat_model_new(nullptr);
  milkcat_model_set_userdict(model, "candidate_cost.txt");
  milkcat_t *analyzer = milkcat_new(model, BIGRAM_SEGMENTER);
  if (analyzer == NULL) status = Status::Corruption(milkcat_last_error());

  ReadableFile *fd = nullptr;
  if (status.ok()) {
    fd = ReadableFile::New(corpus_path, status);
  }

  int buf_size = 1024 * 1024;
  char *buf = new char[buf_size];
  int word_id, left_word_id, right_word_id;
  std::vector<int> line_words;
  while (status.ok() && !fd->Eof()) {
    fd->ReadLine(buf, buf_size, status);

    if (status.ok()) {
      // Analyze the line from corpus, store it in line_words
      line_words = SegmentTextAndUpdateVocabulary(buf, analyzer, dict, vocab);

      // Scan the line_words, find the adjacent word-ids of candidate word
      UpdateAdjacent(word_adjacent, line_words, candidate_size);
    }
  }

  if (status.ok()) {
    std::vector<std::string> id_to_str(dict.size());
    for (auto &x: dict) id_to_str[x.second] = x.first;

    // Calculate the candidates' adjacent entropy and store in adjacent_entropy
    for (auto it = word_adjacent.begin(); it != word_adjacent.end(); ++it) {
      double left_entropy = CalculateAdjacentEntropy(it->left);
      double right_entropy = CalculateAdjacentEntropy(it->right);
      adjacent_entropy[id_to_str[it - word_adjacent.begin()]] = std::min(left_entropy, right_entropy);
    }
  }

  delete fd;
  delete[] buf;
  milkcat_destroy(analyzer);
  milkcat_model_destroy(model);
}<commit_msg>multi-threading in neko<commit_after>//
// bigram_anal.cc --- Created at 2014-01-30
//
// The MIT License (MIT)
//
// Copyright 2014 ling0322 <ling032x@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include <unordered_map>
#include <string>
#include <map>
#include <vector>
#include <mutex>
#include <thread>
#include <utility>
#include <math.h>
#include <stdio.h>
#include "utils/readable_file.h"
#include "utils/status.h"
#include "milkcat/milkcat.h"

struct Adjacent {
  std::map<int, int> left;
  std::map<int, int> right;
};

int GetOrInsert(std::unordered_map<std::string, int> &dict, const std::string &word) {
  auto it = dict.find(word);
  if (it == dict.end()) {
    dict.insert(std::pair<std::string, int>(word, dict.size()));
    return dict.size();
  } else {
    return it->second;
  }
}

// Segment a string specified by text and return as a vector.
std::vector<std::string> SegmentText(
      const char *text,
      milkcat_t *analyzer) {

  std::vector<std::string> line_words;

  milkcat_cursor_t cursor = milkcat_analyze(analyzer, text);
  milkcat_item_t item;

  while (milkcat_cursor_get_next(&cursor, &item) == MC_OK) {
    if (item.word_type == MC_CHINESE_WORD) {
      line_words.push_back(item.word);
    } else {
      line_words.push_back("-NOT-CJK-");
    }
  }

  return line_words;
}

// Update the word_adjacent data from words specified by line_words
void UpdateAdjacent(const std::vector<int> &line_words,
                    int candidate_size,
                    std::vector<Adjacent> &word_adjacent) {
  int word_id;
  for (auto it = line_words.begin(); it != line_words.end(); ++it) {
    word_id = *it;
    if (word_id < candidate_size) {
      // OK, find a candidate word

      if (it != line_words.begin())
        word_adjacent[word_id].left[*(it - 1)] += 1;

      if (it != line_words.end() - 1)
        word_adjacent[word_id].right[*(it + 1)] += 1;
    }
  }
}

// Calculates the adjacent entropy from word's adjacent word data
// specified by adjacent
double CalculateAdjacentEntropy(const std::map<int, int> &adjacent) {
  double entropy = 0, probability;
  int total_count = 0;
  for (auto &x: adjacent) {
    total_count += x.second;
  }

  for (auto &x: adjacent) {
    probability = static_cast<double>(x.second) / total_count;
    entropy += -probability * log(probability);
  }

  return entropy;
}

// Its a thread that using bigram to segment the text from fd, and update the
// adjacent_entropy and the vocab data
void BigramAnalyzeThread(milkcat_model_t *model,
                         ReadableFile *fd,
                         int candidate_size,
                         std::mutex &fd_mutex,
                         std::vector<Adjacent> &word_adjacent,
                         std::unordered_map<std::string, int> &vocab,
                         std::unordered_map<std::string, int> &dict,
                         std::mutex &update_mutex,
                         Status &status) {

  milkcat_t *analyzer = milkcat_new(model, BIGRAM_SEGMENTER);
  if (analyzer == nullptr) status = Status::Corruption(milkcat_last_error());

  int buf_size = 1024 * 1024;
  char *buf = new char[buf_size];

  bool eof = false;
  std::vector<std::string> words;
  std::vector<int> word_ids;
  while (status.ok() && !eof) {
    fd_mutex.lock();
    eof = fd->Eof();
    if (!eof) fd->ReadLine(buf, buf_size, status);
    fd_mutex.unlock();

    if (status.ok() && !eof) {

      // Using bigram model to segment the corpus
      words = SegmentText(buf, analyzer);

      // Now start to update the data
      word_ids.clear();
      update_mutex.lock();
      for (auto &word: words) {
        vocab[word] += 1;
        word_ids.push_back(GetOrInsert(dict, word));
      }
      UpdateAdjacent(word_ids, candidate_size, word_adjacent);
      update_mutex.unlock();
    }
  }

  milkcat_destroy(analyzer);
  delete buf;
}

// Use bigram segmentation to analyze a corpus. Candidate to analyze is specified by
// candidate, and the corpus is specified by corpus_path. It would use a temporary file
// called 'candidate_cost.txt' as user dictionary file for MilkCat.
// On success, stores the adjecent entropy in adjacent_entropy, and stores the vocabulary
// of segmentation's result in vocab. On failed set status != Status::OK()
void BigramAnalyze(const std::unordered_map<std::string, float> &candidate,
                   const char *corpus_path,
                   std::unordered_map<std::string, double> &adjacent_entropy,
                   std::unordered_map<std::string, int> &vocab,
                   Status &status) {

  std::unordered_map<std::string, int> dict;
  dict.reserve(500000);

  int candidate_size = candidate.size();
  std::vector<Adjacent> word_adjacent(candidate_size);

  // Put each candidate word into dictionary and assign its word-id
  for (auto &x: candidate) {
    dict.insert(std::pair<std::string, int>(x.first, dict.size()));
  }

  // The model file
  milkcat_model_t *model = milkcat_model_new(nullptr);
  milkcat_model_set_userdict(model, "candidate_cost.txt");

  ReadableFile *fd = nullptr;
  if (status.ok()) {
    fd = ReadableFile::New(corpus_path, status);
  }

  if (status.ok()) {
    int n_threads = std::thread::hardware_concurrency();
    std::vector<Status> status_vec(n_threads);
    std::vector<std::thread> threads;
    std::mutex update_mutex, fd_mutex;

    for (int i = 0; i < n_threads; ++i) {
      threads.push_back(std::thread(BigramAnalyzeThread,
                                    model,
                                    fd,
                                    candidate_size,
                                    std::ref(fd_mutex),
                                    std::ref(word_adjacent),
                                    std::ref(vocab),
                                    std::ref(dict),
                                    std::ref(update_mutex),
                                    std::ref(status_vec[i])));
    }

    // Synchronizing all threads
    for (auto &th: threads) th.join();

    // Set the status
    for (auto &st: status_vec) {
      if (!st.ok()) status = st;
    }
  }

  if (status.ok()) {
    std::vector<std::string> id_to_str(dict.size());
    for (auto &x: dict) id_to_str[x.second] = x.first;

    // Calculate the candidates' adjacent entropy and store in adjacent_entropy
    for (auto it = word_adjacent.begin(); it != word_adjacent.end(); ++it) {
      double left_entropy = CalculateAdjacentEntropy(it->left);
      double right_entropy = CalculateAdjacentEntropy(it->right);
      adjacent_entropy[id_to_str[it - word_adjacent.begin()]] = std::min(left_entropy, right_entropy);
    }
  }

  delete fd;
  milkcat_model_destroy(model);
}
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <net/inet_common.hpp>

namespace net {

uint16_t checksum(uint32_t sum, const void* data, size_t length) noexcept
{
  const char* buffer = (const char*) data;

  while (length >= 4)
  {
    auto v = *(uint32_t*) buffer;
    sum += v;
    if (sum < v) sum++;
    length -= 4; buffer += 4;
  }
  if (length & 2)
  {
    auto v = *(uint16_t*) buffer;
    sum += v;
    if (sum < v) sum++;
    buffer += 2;
  }
  if (length & 1)
  {
    auto v = *(uint8_t*) buffer;
    sum += v;
    if (sum < v) sum++;
  }
  // Fold to 16-bit
  uint16_t a = sum & 0xffff;
  uint16_t b = sum >> 16;
  a += b;
  if (a < b) a++;
  return ~a;
}

} //< namespace net
<commit_msg>net: Improve IP checksum performance<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <net/inet_common.hpp>

namespace net {

uint16_t checksum(uint32_t tsum, const void* data, size_t length) noexcept
{
  const char* buffer = (const char*) data;
  int64_t sum = tsum;
  // unrolled 32 bytes at once
  while (length >= 32)
  {
    auto* v = (uint32_t*) buffer;
    sum += v[0];
    sum += v[1];
    sum += v[2];
    sum += v[3];
    sum += v[4];
    sum += v[5];
    sum += v[6];
    sum += v[7];
    length -= 32; buffer += 32;
  }
  while (length >= 4)
  {
    auto v = *(uint32_t*) buffer;
    sum += v;
    length -= 4; buffer += 4;
  }
  if (length & 2)
  {
    auto v = *(uint16_t*) buffer;
    sum += v;
    buffer += 2;
  }
  if (length & 1)
  {
    auto v = *(uint8_t*) buffer;
    sum += v;
  }
  // fold to 32-bit
  uint32_t a32 = sum & 0xffffffff;
  uint32_t b32 = sum >> 32;
  a32 += b32;
  if (a32 < b32) a32++;
  // fold again to 16-bit
  uint16_t a16 = a32 & 0xffff;
  uint16_t b16 = a32 >> 16;
  a16 += b16;
  if (a16 < b16) a16++;
  // return 2s complement
  return ~a16;
}

} //< namespace net
<|endoftext|>


<commit_before>#pragma once

#include <vector>
#include <pair>

#include "Vector.hpp"
#include "APIQuadcopter.hpp"
#include "APIFormation.hpp"
#include "APICamera.hpp"
#include "APICameraSystem.hpp"
#include "APIMessageListener.hpp"

#include "api_application/Announce.h"

namespace kitrokopter {

    class API {

    public:

	API(int argc, char **argv);

	bool announce(
	    api_application::Announce::Request &req,
	    api_application::Announce::Response &res);

	/* Quadcopter mutation */
	APIQuadcopter getQuadcopter(int id);
	void removeQuadcopter(int id);

	/* Formation */
	void setFormation(APIFormation formation);
	APIFormation getFormation();

	/* Cameras */
	APICameraSystem getCameraSystem();
	std::vector<APICamera> getCameras();
	std::vector<APICamera> getCalibratedCameras();
	std::vector<APICamera> getUncalibratedCameras();
	int getCameraAmount();
	int getCalibratedCameraAmount();
	int getUncalibratedCameraAmount();

	/* Quadcopter getters */
	std::vector<APIQuadcopter> getQuadcopters();
	std::vector<APIQuadcopter> getQuadcoptersFlying();
	std::vector<APIQuadcopter> getQuadcoptersOnGround();
	std::vector<APIQuadcopter> getQuadcoptersTracked();
	std::vector<APIQuadcopter> getQuadcoptersUntracked();
	std::vector<APIQuadcopter> getQuadcoptersInFormation();
	std::vector<APIQuadcopter> getQuadcoptersNotInFormation();

	/* Quadcopter amount */
	int getQuadcopterAmount();
	int getQuadcoptersFlyingAmount();
	int getQuadcoptersOnGroundAmount();
	int getQuadcoptersTrackedAmount();
	int getQuadcoptersUntrackedAmount();
	int getQuadcoptersInFormationAmount();
	int getQuadcoptersNotInFormationAmount();

	/* message listeners */
	void addMessageListener(APIMessageListener*);
	void removeMessageListener(APIMessageListener*);

	/* Launch / Land */
	void launchQuadcopters(int height);
	double getLaunchProgress();
	bool quadcoptersLaunched();
	void landQuadcopters();

	void shutdownSystem();

	/* Settings */
	Cuboid getMaximumOperatingArea();
	bool setOperatingArea(Cuboid);
	int getMaximumHorizontalSpeed();
	int getMaximumVerticalSpeed();
	int getMaximumHorizontalAcceleration();
	int getMaximumVerticalAcceleration();
	void setReceiveTargetMovementData(bool);
	void setReceiveActualMovementData(bool);
	void setReceiveQuadcopterState(bool);

	/* Movement */
	void moveFormation(Vector);
	void rotateFormation(Vector);

    private:
	int idCounter;

	//the ids of modules by category
	std::vector<std::pair<int, int>> cameras; //first value is the module id, second the camera id
	std::vector<int> quadcopters;
	std::vector<int> controllers;
	std::vector<int> positions;
    };
}
<commit_msg>Removed pair import<commit_after>#pragma once

#include <vector>

#include "Vector.hpp"
#include "APIQuadcopter.hpp"
#include "APIFormation.hpp"
#include "APICamera.hpp"
#include "APICameraSystem.hpp"
#include "APIMessageListener.hpp"

#include "api_application/Announce.h"

namespace kitrokopter {

    class API {

    public:

	API(int argc, char **argv);

	bool announce(
	    api_application::Announce::Request &req,
	    api_application::Announce::Response &res);

	/* Quadcopter mutation */
	APIQuadcopter getQuadcopter(int id);
	void removeQuadcopter(int id);

	/* Formation */
	void setFormation(APIFormation formation);
	APIFormation getFormation();

	/* Cameras */
	APICameraSystem getCameraSystem();
	std::vector<APICamera> getCameras();
	std::vector<APICamera> getCalibratedCameras();
	std::vector<APICamera> getUncalibratedCameras();
	int getCameraAmount();
	int getCalibratedCameraAmount();
	int getUncalibratedCameraAmount();

	/* Quadcopter getters */
	std::vector<APIQuadcopter> getQuadcopters();
	std::vector<APIQuadcopter> getQuadcoptersFlying();
	std::vector<APIQuadcopter> getQuadcoptersOnGround();
	std::vector<APIQuadcopter> getQuadcoptersTracked();
	std::vector<APIQuadcopter> getQuadcoptersUntracked();
	std::vector<APIQuadcopter> getQuadcoptersInFormation();
	std::vector<APIQuadcopter> getQuadcoptersNotInFormation();

	/* Quadcopter amount */
	int getQuadcopterAmount();
	int getQuadcoptersFlyingAmount();
	int getQuadcoptersOnGroundAmount();
	int getQuadcoptersTrackedAmount();
	int getQuadcoptersUntrackedAmount();
	int getQuadcoptersInFormationAmount();
	int getQuadcoptersNotInFormationAmount();

	/* message listeners */
	void addMessageListener(APIMessageListener*);
	void removeMessageListener(APIMessageListener*);

	/* Launch / Land */
	void launchQuadcopters(int height);
	double getLaunchProgress();
	bool quadcoptersLaunched();
	void landQuadcopters();

	void shutdownSystem();

	/* Settings */
	Cuboid getMaximumOperatingArea();
	bool setOperatingArea(Cuboid);
	int getMaximumHorizontalSpeed();
	int getMaximumVerticalSpeed();
	int getMaximumHorizontalAcceleration();
	int getMaximumVerticalAcceleration();
	void setReceiveTargetMovementData(bool);
	void setReceiveActualMovementData(bool);
	void setReceiveQuadcopterState(bool);

	/* Movement */
	void moveFormation(Vector);
	void rotateFormation(Vector);

    private:
	int idCounter;

	//the ids of modules by category
	std::vector<std::pair<int, int>> cameras; //first value is the module id, second the camera id
	std::vector<int> quadcopters;
	std::vector<int> controllers;
	std::vector<int> positions;
    };
}
<|endoftext|>