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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkDataNode.h"

#include <vtkWindow.h>
#include "mitkVtkPropRenderer.h"

#include "mitkTestingMacros.h"
#include "mitkGlobalInteraction.h"

#include <iostream>

//Basedata Test
#include <mitkGeometryData.h>
#include <mitkPlaneGeometryData.h>
#include <mitkManufacturerLogo.h>
#include <mitkPointSet.h>
#include <mitkImage.h>
#include <mitkSurface.h>

//Mapper Test
#include <mitkPlaneGeometryDataMapper2D.h>
#include <mitkImageVtkMapper2D.h>
#include <mitkSurfaceVtkMapper2D.h>

#include <mitkPlaneGeometryDataVtkMapper3D.h>
#include <mitkPointSetVtkMapper3D.h>
#include <mitkPointSetVtkMapper2D.h>
#include <mitkSurfaceVtkMapper3D.h>

//Interactors
#include <mitkPointSetDataInteractor.h>

//Propertylist Test
#include <mitkImageGenerator.h>

/**
 *  Simple example for a test for the (non-existent) class "DataNode".
 *
 *  argc and argv are the command line parameters which were passed to
 *  the ADD_TEST command in the CMakeLists.txt file. For the automatic
 *  tests, argv is either empty for the simple tests or contains the filename
 *  of a test image for the image tests (see CMakeLists.txt).
 */
class mitkDataNodeTestClass { public:

static void TestDataSetting(mitk::DataNode::Pointer dataNode)
{

  mitk::BaseData::Pointer baseData;

  //NULL pointer Test
  dataNode->SetData(baseData);
  MITK_TEST_CONDITION( baseData == dataNode->GetData(), "Testing if a NULL pointer was set correctly" )

  baseData = mitk::GeometryData::New();
  dataNode->SetData(baseData);
  MITK_TEST_CONDITION( baseData == dataNode->GetData(), "Testing if a GeometryData object was set correctly" )

  baseData = mitk::PlaneGeometryData::New();
  dataNode->SetData(baseData);
  MITK_TEST_CONDITION( baseData == dataNode->GetData(), "Testing if a PlaneGeometryData object was set correctly" )

  baseData = mitk::ManufacturerLogo::New();
  dataNode->SetData(baseData);
  MITK_TEST_CONDITION( baseData == dataNode->GetData(), "Testing if a ManufacturerLogo object was set correctly" )

  baseData = mitk::PointSet::New();
  dataNode->SetData(baseData);
  MITK_TEST_CONDITION( baseData == dataNode->GetData(), "Testing if a PointSet object was set correctly" )

  baseData = mitk::Image::New();
  dataNode->SetData(baseData);
  MITK_TEST_CONDITION( baseData == dataNode->GetData(), "Testing if a Image object was set correctly" )

  baseData = mitk::Surface::New();
  dataNode->SetData(baseData);
  MITK_TEST_CONDITION( baseData == dataNode->GetData(), "Testing if a Surface object was set correctly" )
}
static void TestMapperSetting(mitk::DataNode::Pointer dataNode)
{
  //tests the SetMapper() method
  //in dataNode is a mapper vector which can be accessed by index
  //in this test method we use only slot 0 (filled with null) and slot 1
  //so we also test the destructor of the mapper classes
  mitk::Mapper::Pointer mapper;

  dataNode->SetMapper(0,mapper);
  MITK_TEST_CONDITION( mapper == dataNode->GetMapper(0), "Testing if a NULL pointer was set correctly" )

  mapper = mitk::PlaneGeometryDataMapper2D::New();
  dataNode->SetMapper(1,mapper);
  MITK_TEST_CONDITION( mapper == dataNode->GetMapper(1), "Testing if a PlaneGeometryDataMapper2D was set correctly" )
  MITK_TEST_CONDITION( dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode" )

  mapper = mitk::ImageVtkMapper2D::New();
  dataNode->SetMapper(1,mapper);
  MITK_TEST_CONDITION( mapper == dataNode->GetMapper(1), "Testing if a ImageVtkMapper2D was set correctly" )
  MITK_TEST_CONDITION( dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode" )

  mapper = mitk::PointSetVtkMapper2D::New();
  dataNode->SetMapper(1,mapper);
  MITK_TEST_CONDITION( mapper == dataNode->GetMapper(1), "Testing if a PointSetVtkMapper2D was set correctly" )
  MITK_TEST_CONDITION( dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode" )

  mapper = mitk::SurfaceVtkMapper2D::New();
  dataNode->SetMapper(1,mapper);
  MITK_TEST_CONDITION( mapper == dataNode->GetMapper(1), "Testing if a SurfaceGLMapper2D was set correctly" )
  MITK_TEST_CONDITION( dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode" )

  mapper = mitk::PlaneGeometryDataVtkMapper3D::New();
  dataNode->SetMapper(1,mapper);
  MITK_TEST_CONDITION( mapper == dataNode->GetMapper(1), "Testing if a PlaneGeometryDataVtkMapper3D was set correctly" )
  MITK_TEST_CONDITION( dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode" )

  mapper = mitk::PointSetVtkMapper3D::New();
  dataNode->SetMapper(1,mapper);
  MITK_TEST_CONDITION( mapper == dataNode->GetMapper(1), "Testing if a PointSetVtkMapper3D was set correctly" )
  MITK_TEST_CONDITION( dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode" )

  mapper = mitk::SurfaceVtkMapper3D::New();
  dataNode->SetMapper(1,mapper);
  MITK_TEST_CONDITION( mapper == dataNode->GetMapper(1), "Testing if a SurfaceVtkMapper3D was set correctly" )
  MITK_TEST_CONDITION( dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode" )
}

static void TestInteractorSetting(mitk::DataNode::Pointer dataNode)
{

  //this method tests the SetInteractor() and GetInteractor methods
  //the DataInteractor base class calls the DataNode->SetInteractor method

  mitk::DataInteractor::Pointer interactor;

  MITK_TEST_CONDITION( interactor == dataNode->GetDataInteractor(), "Testing if a NULL pointer was set correctly (DataInteractor)" )

  interactor = mitk::PointSetDataInteractor::New();
  interactor->SetEventConfig("PointSetConfig.xml");
  interactor->SetDataNode(dataNode);
  MITK_TEST_CONDITION( interactor == dataNode->GetDataInteractor(), "Testing if a PointSetDataInteractor was set correctly" )

  interactor = mitk::PointSetDataInteractor::New();
  dataNode->SetDataInteractor(interactor);
  MITK_TEST_CONDITION( interactor == dataNode->GetDataInteractor(), "Testing if a PointSetDataInteractor was set correctly" )
}
static void TestPropertyList(mitk::DataNode::Pointer dataNode)
{

  mitk::PropertyList::Pointer propertyList =  dataNode->GetPropertyList();

  MITK_TEST_CONDITION(dataNode->GetPropertyList() != NULL, "Testing if the constructor set the propertylist" )

  dataNode->SetIntProperty("int", -31337);
  int x;
  dataNode->GetIntProperty("int", x);
  MITK_TEST_CONDITION(x == -31337, "Testing Set/GetIntProperty");

  dataNode->SetBoolProperty("bool", true);
  bool b;
  dataNode->GetBoolProperty("bool", b);
  MITK_TEST_CONDITION(b == true, "Testing Set/GetBoolProperty");
  dataNode->SetFloatProperty("float", -31.337);
  float y;
  dataNode->GetFloatProperty("float", y);
  MITK_TEST_CONDITION(y - -31.337 < 0.01, "Testing Set/GetFloatProperty");
  double yd = 0;
  dataNode->GetDoubleProperty("float", yd);
  MITK_TEST_CONDITION(mitk::Equal(yd, static_cast<double>(y)), "Testing GetDoubleProperty");
  dataNode->SetStringProperty("string", "MITK");
  std::string s = "GANZVIELPLATZ";
  dataNode->GetStringProperty("string", s);
  MITK_TEST_CONDITION(s == "MITK", "Testing Set/GetStringProperty");

  std::string name = "MyTestName";
  dataNode->SetName(name.c_str());
  MITK_TEST_CONDITION(dataNode->GetName() == name, "Testing Set/GetName");
  name = "MySecondTestName";
  dataNode->SetName(name);
  MITK_TEST_CONDITION(dataNode->GetName() == name, "Testing Set/GetName(std::string)");

  MITK_TEST_CONDITION(propertyList == dataNode->GetPropertyList(), "Testing if the propertylist has changed during the last tests" )
}

static void TestSelected(mitk::DataNode::Pointer dataNode)
{
  vtkRenderWindow *renderWindow = vtkRenderWindow::New();

  mitk::VtkPropRenderer::Pointer base = mitk::VtkPropRenderer::New( "the first renderer", renderWindow, mitk::RenderingManager::GetInstance() );

  //with BaseRenderer==Null
  MITK_TEST_CONDITION(!dataNode->IsSelected(), "Testing if this node is not set as selected" )

  dataNode->SetSelected(true);
  MITK_TEST_CONDITION(dataNode->IsSelected(), "Testing if this node is set as selected" )
  dataNode->SetSelected(false);

  dataNode->SetSelected(true,base);

  MITK_TEST_CONDITION(dataNode->IsSelected(base), "Testing if this node with right base renderer is set as selected" )

  //Delete RenderWindow correctly
  renderWindow->Delete();

}
static void TestGetMTime(mitk::DataNode::Pointer dataNode)
{
  unsigned long time;
  time = dataNode->GetMTime();
  mitk::PointSet::Pointer pointSet = mitk::PointSet::New();

  dataNode->SetData(pointSet);
  MITK_TEST_CONDITION( time != dataNode->GetMTime(), "Testing if the node timestamp is updated after adding data to the node" )

  mitk::Point3D point;
  point.Fill(3.0);
  pointSet->SetPoint(0,point);

  //less or equal because dataNode timestamp is little later then the basedata timestamp
  MITK_TEST_CONDITION( pointSet->GetMTime() <= dataNode->GetMTime(), "Testing if the node timestamp is updated after base data was modified" )

  // testing if changing anything in the property list also sets the node in a modified state
  unsigned long lastModified = dataNode->GetMTime();
  dataNode->SetIntProperty("testIntProp", 2344);
  MITK_TEST_CONDITION( lastModified <= dataNode->GetMTime(), "Testing if the node timestamp is updated after property list was modified" )

}
static void TestSetDataUnderPropertyChange()
{
  mitk::Image::Pointer image = mitk::Image::New();
  mitk::Image::Pointer additionalImage = mitk::Image::New();

  mitk::DataNode::Pointer dataNode = mitk::DataNode::New();

  image = mitk::ImageGenerator::GenerateRandomImage<unsigned char>(3u, 3u);

  dataNode->SetData(image);

  float outlineWidth = 0;
  dataNode->GetPropertyValue("outline width", outlineWidth);

  MITK_TEST_CONDITION(mitk::Equal(outlineWidth,1.0), "Testing if the SetData set the default propertylist" )

  dataNode->SetProperty("outline width", mitk::FloatProperty::New( 42.0 ));
  dataNode->SetData(image);
  dataNode->GetPropertyValue("outline width", outlineWidth);

  MITK_TEST_CONDITION(mitk::Equal(outlineWidth,42.0), "Testing if the SetData does not set anything if imagedata is identical" )

  dataNode->SetData(additionalImage);
  dataNode->GetPropertyValue("outline width", outlineWidth);

  MITK_TEST_CONDITION(mitk::Equal(outlineWidth,42.0), "Testing if the SetData does not set the default propertylist if imagedata is already set" )

  mitk::Surface::Pointer surface = mitk::Surface::New();
  dataNode->SetData(surface);

  MITK_TEST_CONDITION(dataNode->GetPropertyValue("outline width", outlineWidth) == false, "Testing if the SetData sets the default propertylist if some new datatype is loaded" )
}
}; //mitkDataNodeTestClass

int mitkDataNodeTest(int /* argc */, char* /*argv*/[])
{
  // always start with this!
  MITK_TEST_BEGIN("DataNode")

  // Global interaction must(!) be initialized
  mitk::GlobalInteraction::GetInstance()->Initialize("global");

  // let's create an object of our class
  mitk::DataNode::Pointer myDataNode = mitk::DataNode::New();

  // first test: did this work?
  // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since
  // it makes no sense to continue without an object.
  MITK_TEST_CONDITION_REQUIRED(myDataNode.IsNotNull(),"Testing instantiation")

  //test setData() Method
  mitkDataNodeTestClass::TestDataSetting(myDataNode);
  mitkDataNodeTestClass::TestMapperSetting(myDataNode);
  mitkDataNodeTestClass::TestSetDataUnderPropertyChange();
  //
  //note, that no data is set to the dataNode
  mitkDataNodeTestClass::TestInteractorSetting(myDataNode);
  mitkDataNodeTestClass::TestPropertyList(myDataNode);
  mitkDataNodeTestClass::TestSelected(myDataNode);
  mitkDataNodeTestClass::TestGetMTime(myDataNode);

  // write your own tests here and use the macros from mitkTestingMacros.h !!!
  // do not write to std::cout and do not return from this function yourself!

  // always end with this!
  MITK_TEST_END()
}

<commit_msg>Added check for nullptr before accessing baseData. Only clear property list if data types differ but base data is not null.<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkDataNode.h"

#include <vtkWindow.h>
#include "mitkVtkPropRenderer.h"

#include "mitkTestingMacros.h"
#include "mitkGlobalInteraction.h"

#include <iostream>

//Basedata Test
#include <mitkGeometryData.h>
#include <mitkPlaneGeometryData.h>
#include <mitkManufacturerLogo.h>
#include <mitkPointSet.h>
#include <mitkImage.h>
#include <mitkSurface.h>

//Mapper Test
#include <mitkPlaneGeometryDataMapper2D.h>
#include <mitkImageVtkMapper2D.h>
#include <mitkSurfaceVtkMapper2D.h>

#include <mitkPlaneGeometryDataVtkMapper3D.h>
#include <mitkPointSetVtkMapper3D.h>
#include <mitkPointSetVtkMapper2D.h>
#include <mitkSurfaceVtkMapper3D.h>

//Interactors
#include <mitkPointSetDataInteractor.h>

//Propertylist Test
#include <mitkImageGenerator.h>

/**
 *  Simple example for a test for the (non-existent) class "DataNode".
 *
 *  argc and argv are the command line parameters which were passed to
 *  the ADD_TEST command in the CMakeLists.txt file. For the automatic
 *  tests, argv is either empty for the simple tests or contains the filename
 *  of a test image for the image tests (see CMakeLists.txt).
 */
class mitkDataNodeTestClass { public:

static void TestDataSetting(mitk::DataNode::Pointer dataNode)
{

  mitk::BaseData::Pointer baseData;

  //NULL pointer Test
  dataNode->SetData(baseData);
  MITK_TEST_CONDITION( baseData == dataNode->GetData(), "Testing if a NULL pointer was set correctly" )

  baseData = mitk::GeometryData::New();
  dataNode->SetData(baseData);
  MITK_TEST_CONDITION( baseData == dataNode->GetData(), "Testing if a GeometryData object was set correctly" )

  baseData = mitk::PlaneGeometryData::New();
  dataNode->SetData(baseData);
  MITK_TEST_CONDITION( baseData == dataNode->GetData(), "Testing if a PlaneGeometryData object was set correctly" )

  baseData = mitk::ManufacturerLogo::New();
  dataNode->SetData(baseData);
  MITK_TEST_CONDITION( baseData == dataNode->GetData(), "Testing if a ManufacturerLogo object was set correctly" )

  baseData = mitk::PointSet::New();
  dataNode->SetData(baseData);
  MITK_TEST_CONDITION( baseData == dataNode->GetData(), "Testing if a PointSet object was set correctly" )

  baseData = mitk::Image::New();
  dataNode->SetData(baseData);
  MITK_TEST_CONDITION( baseData == dataNode->GetData(), "Testing if a Image object was set correctly" )

  baseData = mitk::Surface::New();
  dataNode->SetData(baseData);
  MITK_TEST_CONDITION( baseData == dataNode->GetData(), "Testing if a Surface object was set correctly" )

  dataNode->SetData(nullptr);
  MITK_TEST_CONDITION( nullptr == dataNode->GetData(), "Testing if base data (already set) was replaced by a NULL pointer" )
}
static void TestMapperSetting(mitk::DataNode::Pointer dataNode)
{
  //tests the SetMapper() method
  //in dataNode is a mapper vector which can be accessed by index
  //in this test method we use only slot 0 (filled with null) and slot 1
  //so we also test the destructor of the mapper classes
  mitk::Mapper::Pointer mapper;

  dataNode->SetMapper(0,mapper);
  MITK_TEST_CONDITION( mapper == dataNode->GetMapper(0), "Testing if a NULL pointer was set correctly" )

  mapper = mitk::PlaneGeometryDataMapper2D::New();
  dataNode->SetMapper(1,mapper);
  MITK_TEST_CONDITION( mapper == dataNode->GetMapper(1), "Testing if a PlaneGeometryDataMapper2D was set correctly" )
  MITK_TEST_CONDITION( dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode" )

  mapper = mitk::ImageVtkMapper2D::New();
  dataNode->SetMapper(1,mapper);
  MITK_TEST_CONDITION( mapper == dataNode->GetMapper(1), "Testing if a ImageVtkMapper2D was set correctly" )
  MITK_TEST_CONDITION( dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode" )

  mapper = mitk::PointSetVtkMapper2D::New();
  dataNode->SetMapper(1,mapper);
  MITK_TEST_CONDITION( mapper == dataNode->GetMapper(1), "Testing if a PointSetVtkMapper2D was set correctly" )
  MITK_TEST_CONDITION( dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode" )

  mapper = mitk::SurfaceVtkMapper2D::New();
  dataNode->SetMapper(1,mapper);
  MITK_TEST_CONDITION( mapper == dataNode->GetMapper(1), "Testing if a SurfaceGLMapper2D was set correctly" )
  MITK_TEST_CONDITION( dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode" )

  mapper = mitk::PlaneGeometryDataVtkMapper3D::New();
  dataNode->SetMapper(1,mapper);
  MITK_TEST_CONDITION( mapper == dataNode->GetMapper(1), "Testing if a PlaneGeometryDataVtkMapper3D was set correctly" )
  MITK_TEST_CONDITION( dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode" )

  mapper = mitk::PointSetVtkMapper3D::New();
  dataNode->SetMapper(1,mapper);
  MITK_TEST_CONDITION( mapper == dataNode->GetMapper(1), "Testing if a PointSetVtkMapper3D was set correctly" )
  MITK_TEST_CONDITION( dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode" )

  mapper = mitk::SurfaceVtkMapper3D::New();
  dataNode->SetMapper(1,mapper);
  MITK_TEST_CONDITION( mapper == dataNode->GetMapper(1), "Testing if a SurfaceVtkMapper3D was set correctly" )
  MITK_TEST_CONDITION( dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode" )
}

static void TestInteractorSetting(mitk::DataNode::Pointer dataNode)
{

  //this method tests the SetInteractor() and GetInteractor methods
  //the DataInteractor base class calls the DataNode->SetInteractor method

  mitk::DataInteractor::Pointer interactor;

  MITK_TEST_CONDITION( interactor == dataNode->GetDataInteractor(), "Testing if a NULL pointer was set correctly (DataInteractor)" )

  interactor = mitk::PointSetDataInteractor::New();
  interactor->SetEventConfig("PointSetConfig.xml");
  interactor->SetDataNode(dataNode);
  MITK_TEST_CONDITION( interactor == dataNode->GetDataInteractor(), "Testing if a PointSetDataInteractor was set correctly" )

  interactor = mitk::PointSetDataInteractor::New();
  dataNode->SetDataInteractor(interactor);
  MITK_TEST_CONDITION( interactor == dataNode->GetDataInteractor(), "Testing if a PointSetDataInteractor was set correctly" )
}
static void TestPropertyList(mitk::DataNode::Pointer dataNode)
{

  mitk::PropertyList::Pointer propertyList =  dataNode->GetPropertyList();

  MITK_TEST_CONDITION(dataNode->GetPropertyList() != NULL, "Testing if the constructor set the propertylist" )

  dataNode->SetIntProperty("int", -31337);
  int x;
  dataNode->GetIntProperty("int", x);
  MITK_TEST_CONDITION(x == -31337, "Testing Set/GetIntProperty");

  dataNode->SetBoolProperty("bool", true);
  bool b;
  dataNode->GetBoolProperty("bool", b);
  MITK_TEST_CONDITION(b == true, "Testing Set/GetBoolProperty");
  dataNode->SetFloatProperty("float", -31.337);
  float y;
  dataNode->GetFloatProperty("float", y);
  MITK_TEST_CONDITION(y - -31.337 < 0.01, "Testing Set/GetFloatProperty");
  double yd = 0;
  dataNode->GetDoubleProperty("float", yd);
  MITK_TEST_CONDITION(mitk::Equal(yd, static_cast<double>(y)), "Testing GetDoubleProperty");
  dataNode->SetStringProperty("string", "MITK");
  std::string s = "GANZVIELPLATZ";
  dataNode->GetStringProperty("string", s);
  MITK_TEST_CONDITION(s == "MITK", "Testing Set/GetStringProperty");

  std::string name = "MyTestName";
  dataNode->SetName(name.c_str());
  MITK_TEST_CONDITION(dataNode->GetName() == name, "Testing Set/GetName");
  name = "MySecondTestName";
  dataNode->SetName(name);
  MITK_TEST_CONDITION(dataNode->GetName() == name, "Testing Set/GetName(std::string)");

  MITK_TEST_CONDITION(propertyList == dataNode->GetPropertyList(), "Testing if the propertylist has changed during the last tests" )
}

static void TestSelected(mitk::DataNode::Pointer dataNode)
{
  vtkRenderWindow *renderWindow = vtkRenderWindow::New();

  mitk::VtkPropRenderer::Pointer base = mitk::VtkPropRenderer::New( "the first renderer", renderWindow, mitk::RenderingManager::GetInstance() );

  //with BaseRenderer==Null
  MITK_TEST_CONDITION(!dataNode->IsSelected(), "Testing if this node is not set as selected" )

  dataNode->SetSelected(true);
  MITK_TEST_CONDITION(dataNode->IsSelected(), "Testing if this node is set as selected" )
  dataNode->SetSelected(false);

  dataNode->SetSelected(true,base);

  MITK_TEST_CONDITION(dataNode->IsSelected(base), "Testing if this node with right base renderer is set as selected" )

  //Delete RenderWindow correctly
  renderWindow->Delete();

}
static void TestGetMTime(mitk::DataNode::Pointer dataNode)
{
  unsigned long time;
  time = dataNode->GetMTime();
  mitk::PointSet::Pointer pointSet = mitk::PointSet::New();

  dataNode->SetData(pointSet);
  MITK_TEST_CONDITION( time != dataNode->GetMTime(), "Testing if the node timestamp is updated after adding data to the node" )

  mitk::Point3D point;
  point.Fill(3.0);
  pointSet->SetPoint(0,point);

  //less or equal because dataNode timestamp is little later then the basedata timestamp
  MITK_TEST_CONDITION( pointSet->GetMTime() <= dataNode->GetMTime(), "Testing if the node timestamp is updated after base data was modified" )

  // testing if changing anything in the property list also sets the node in a modified state
  unsigned long lastModified = dataNode->GetMTime();
  dataNode->SetIntProperty("testIntProp", 2344);
  MITK_TEST_CONDITION( lastModified <= dataNode->GetMTime(), "Testing if the node timestamp is updated after property list was modified" )

}
static void TestSetDataUnderPropertyChange()
{
  mitk::Image::Pointer image = mitk::Image::New();
  mitk::Image::Pointer additionalImage = mitk::Image::New();

  mitk::DataNode::Pointer dataNode = mitk::DataNode::New();

  image = mitk::ImageGenerator::GenerateRandomImage<unsigned char>(3u, 3u);

  dataNode->SetData(image);

  float outlineWidth = 0;
  dataNode->GetPropertyValue("outline width", outlineWidth);

  MITK_TEST_CONDITION(mitk::Equal(outlineWidth,1.0), "Testing if the SetData set the default propertylist" )

  dataNode->SetProperty("outline width", mitk::FloatProperty::New( 42.0 ));
  dataNode->SetData(image);
  dataNode->GetPropertyValue("outline width", outlineWidth);

  MITK_TEST_CONDITION(mitk::Equal(outlineWidth,42.0), "Testing if the SetData does not set anything if imagedata is identical" )

  dataNode->SetData(additionalImage);
  dataNode->GetPropertyValue("outline width", outlineWidth);

  MITK_TEST_CONDITION(mitk::Equal(outlineWidth,42.0), "Testing if the SetData does not set the default propertylist if imagedata is already set" )

  mitk::Surface::Pointer surface = mitk::Surface::New();
  dataNode->SetData(surface);

  MITK_TEST_CONDITION(dataNode->GetPropertyValue("outline width", outlineWidth) == false, "Testing if the SetData sets the default propertylist if some new datatype is loaded" )
}
}; //mitkDataNodeTestClass

int mitkDataNodeTest(int /* argc */, char* /*argv*/[])
{
  // always start with this!
  MITK_TEST_BEGIN("DataNode")

  // Global interaction must(!) be initialized
  mitk::GlobalInteraction::GetInstance()->Initialize("global");

  // let's create an object of our class
  mitk::DataNode::Pointer myDataNode = mitk::DataNode::New();

  // first test: did this work?
  // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since
  // it makes no sense to continue without an object.
  MITK_TEST_CONDITION_REQUIRED(myDataNode.IsNotNull(),"Testing instantiation")

  //test setData() Method
  mitkDataNodeTestClass::TestDataSetting(myDataNode);
  mitkDataNodeTestClass::TestMapperSetting(myDataNode);
  mitkDataNodeTestClass::TestSetDataUnderPropertyChange();
  //
  //note, that no data is set to the dataNode
  mitkDataNodeTestClass::TestInteractorSetting(myDataNode);
  mitkDataNodeTestClass::TestPropertyList(myDataNode);
  mitkDataNodeTestClass::TestSelected(myDataNode);
  mitkDataNodeTestClass::TestGetMTime(myDataNode);

  // write your own tests here and use the macros from mitkTestingMacros.h !!!
  // do not write to std::cout and do not return from this function yourself!

  // always end with this!
  MITK_TEST_END()
}

<|endoftext|>


<commit_before>/* validator.C
 *
 * Copyright (C) 2009 Marcel Schumann
 *
 * This file is part of QuEasy -- A Toolbox for Automated QSAR Model
 * Construction and Validation.
 * QuEasy is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or (at
 * your option) any later version.
 *
 * QuEasy is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

#include <BALL/FORMAT/commandlineParser.h>
#include <BALL/QSAR/registry.h>
#include <BALL/QSAR/featureSelection.h>
#include <BALL/QSAR/configIO.h>
#include <fstream>
#include "version.h"

using namespace BALL::QSAR;
using namespace BALL;
using namespace std;

void startValidation(ValidationConfiguration& conf, QSARData* q, String* data_filename);

void startValidation(ifstream& in, QSARData* q, String* data_filename)
{
	ValidationConfiguration conf = ConfigIO::readValidationConfiguration(&in);

	if(conf.done || conf.for_visualization_only==1) return ; // stop processing this section and continue with next section

	startValidation(conf,q,data_filename);
}

void startValidation(ValidationConfiguration& conf, QSARData* q, String* data_filename)
{
	bool created_data_object=0;
	if(q==NULL || data_filename==NULL)
	{
		q = new QSARData;
		created_data_object=1;
	}

	Registry reg;
	Model* m;
	String model_type;

	ifstream model_input(conf.model.c_str()); // read model-abbreviation
	if(!model_input)
	{
		Log.error()<<"Error: Model-file '"<<conf.model<<"' does not exist!!"<<endl;
		return;
	}
	getline(model_input,model_type);
	getline(model_input,model_type);
	model_type = model_type.getField(0,"\t");
	model_input.close();

	RegistryEntry* entry = reg.getEntry(model_type);

	if(!entry->kernel)
	{
		m = (*entry->create)(*q);
	}
	else
	{
		// parameters irrelevant; will be overwritten by those read from file
		m = (*entry->createKernel1)(*q,1,1, -1);
	}

	m->readFromFile(conf.model.c_str());
	m->model_val->selectStat(conf.statistic);

	if(conf.data!="")
	{
		if(!data_filename || conf.data!=*data_filename)
		{
			q->readFromFile(conf.data);
			if(data_filename) *data_filename = conf.data;
		}

		if(conf.val_type==1) m->model_val->testInputData(1);

		else if(conf.val_type==2) m->model_val->crossValidation(conf.k_folds,1);

		else if(conf.val_type==3) m->model_val->bootstrap(conf.bootstrap_samples);

		else if(conf.val_type==4) m->model_val->yRandomizationTest(conf.no_of_permutation_tests,conf.k_folds);

		else if(conf.val_type==6)
		{
			if(entry->regression)
			{
				((RegressionModel*)m)->validation->calculateCoefficientStdErrors(conf.bootstrap_samples);
			}
		}

		else if(conf.val_type==7)
		{
			if(!data_filename || conf.validation_data!=*data_filename)
			{
				q->readFromFile(conf.validation_data.c_str());
				*data_filename = conf.validation_data;
			}
			m->model_val->testInputData(1);
		}
	}

	// save the result of the validation to the specified file
	m->model_val->saveToFile(conf.output);

	if(created_data_object) delete q;
	delete m;
}

#ifndef EXT_MAIN
int main(int argc, char* argv[])
{
	CommandlineParser par("Validator","evaluate quality of a QSAR model ", VERSION, String(__DATE__), "QuEasy (QSAR)");
	par.registerParameter("i","input mod-file",INFILE,true);
	par.registerParameter("dat","data-file",INFILE,true);
	par.registerParameter("o","output text file",OUTFILE,true);
	par.registerParameter("type","feature-selection type",STRING,true);

	String man = "Validator evaluates the quality of a QSAR model.\n\nThe validation technique to be used for this can selected by '-type'. As input this tools need a model-file as generate by InputReader or FeatureSelector and a data-file generated by InputReader containing the prediction data set. Note that the latter must contain response values so that predictions done by the supplied model can be compared to those values by the validation method.";
	par.setToolManual(man);
	list<String> slist;
	slist.push_back("cross validation");
	slist.push_back("bootstrapping");
	slist.push_back("response permutation");
	slist.push_back("evaluate fit to test data");
	par.setParameterRestrictions("type",slist);
	par.setSupportedFormats("i","mod");
	par.setSupportedFormats("dat","dat");
	par.setSupportedFormats("o","txt");
	par.parse(argc,argv);

	Registry reg;
	ValidationConfiguration conf;
	conf.model = par.get("i");
	conf.data = par.get("dat");
	conf.output = par.get("o");
	conf.k_folds = reg.default_k;
	conf.bootstrap_samples = reg.default_no_boostrap_samples;
	conf.no_of_permutation_tests = reg.default_no_permutations;

	String type = par.get("type");
	if (type=="cross_validation" || type=="cross validation")
	{
		conf.val_type = 2;
	}
	else if (type=="bootstrapping")
	{
		conf.val_type = 3;
	}
	else if (type=="response_permutation" || type=="response permutation")
	{
		conf.val_type = 4;
	}
	else if (type=="simple_prediction" || type=="evaluate fit to test data")
	{
		conf.val_type = 1;
	}
	else
	{
		cerr << "Validation-type '"<<type<<"' unknown, possible choices are:"<<endl;
		cerr<<"   "<<"cross_validation"<<endl;
		cerr<<"   "<<"bootstrapping"<<endl;
		cerr<<"   "<<"response_permutation"<<endl;
		cerr<<"   "<<"simple_prediction   = quality of predictions done for given predictions data set only (no sampling)"<<endl;
		exit(1);
	}

	startValidation(conf,0,0);
}
#endif
<commit_msg>deleted invalid licensing<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//

#include <BALL/FORMAT/commandlineParser.h>
#include <BALL/QSAR/registry.h>
#include <BALL/QSAR/featureSelection.h>
#include <BALL/QSAR/configIO.h>
#include <fstream>
#include "version.h"

using namespace BALL::QSAR;
using namespace BALL;
using namespace std;

void startValidation(ValidationConfiguration& conf, QSARData* q, String* data_filename);

void startValidation(ifstream& in, QSARData* q, String* data_filename)
{
	ValidationConfiguration conf = ConfigIO::readValidationConfiguration(&in);

	if(conf.done || conf.for_visualization_only==1) return ; // stop processing this section and continue with next section

	startValidation(conf,q,data_filename);
}

void startValidation(ValidationConfiguration& conf, QSARData* q, String* data_filename)
{
	bool created_data_object=0;
	if(q==NULL || data_filename==NULL)
	{
		q = new QSARData;
		created_data_object=1;
	}

	Registry reg;
	Model* m;
	String model_type;

	ifstream model_input(conf.model.c_str()); // read model-abbreviation
	if(!model_input)
	{
		Log.error()<<"Error: Model-file '"<<conf.model<<"' does not exist!!"<<endl;
		return;
	}
	getline(model_input,model_type);
	getline(model_input,model_type);
	model_type = model_type.getField(0,"\t");
	model_input.close();

	RegistryEntry* entry = reg.getEntry(model_type);

	if(!entry->kernel)
	{
		m = (*entry->create)(*q);
	}
	else
	{
		// parameters irrelevant; will be overwritten by those read from file
		m = (*entry->createKernel1)(*q,1,1, -1);
	}

	m->readFromFile(conf.model.c_str());
	m->model_val->selectStat(conf.statistic);

	if(conf.data!="")
	{
		if(!data_filename || conf.data!=*data_filename)
		{
			q->readFromFile(conf.data);
			if(data_filename) *data_filename = conf.data;
		}

		if(conf.val_type==1) m->model_val->testInputData(1);

		else if(conf.val_type==2) m->model_val->crossValidation(conf.k_folds,1);

		else if(conf.val_type==3) m->model_val->bootstrap(conf.bootstrap_samples);

		else if(conf.val_type==4) m->model_val->yRandomizationTest(conf.no_of_permutation_tests,conf.k_folds);

		else if(conf.val_type==6)
		{
			if(entry->regression)
			{
				((RegressionModel*)m)->validation->calculateCoefficientStdErrors(conf.bootstrap_samples);
			}
		}

		else if(conf.val_type==7)
		{
			if(!data_filename || conf.validation_data!=*data_filename)
			{
				q->readFromFile(conf.validation_data.c_str());
				*data_filename = conf.validation_data;
			}
			m->model_val->testInputData(1);
		}
	}

	// save the result of the validation to the specified file
	m->model_val->saveToFile(conf.output);

	if(created_data_object) delete q;
	delete m;
}

#ifndef EXT_MAIN
int main(int argc, char* argv[])
{
	CommandlineParser par("Validator","evaluate quality of a QSAR model ", VERSION, String(__DATE__), "QuEasy (QSAR)");
	par.registerParameter("i","input mod-file",INFILE,true);
	par.registerParameter("dat","data-file",INFILE,true);
	par.registerParameter("o","output text file",OUTFILE,true);
	par.registerParameter("type","feature-selection type",STRING,true);

	String man = "Validator evaluates the quality of a QSAR model.\n\nThe validation technique to be used for this can selected by '-type'. As input this tools need a model-file as generate by InputReader or FeatureSelector and a data-file generated by InputReader containing the prediction data set. Note that the latter must contain response values so that predictions done by the supplied model can be compared to those values by the validation method.";
	par.setToolManual(man);
	list<String> slist;
	slist.push_back("cross validation");
	slist.push_back("bootstrapping");
	slist.push_back("response permutation");
	slist.push_back("evaluate fit to test data");
	par.setParameterRestrictions("type",slist);
	par.setSupportedFormats("i","mod");
	par.setSupportedFormats("dat","dat");
	par.setSupportedFormats("o","txt");
	par.parse(argc,argv);

	Registry reg;
	ValidationConfiguration conf;
	conf.model = par.get("i");
	conf.data = par.get("dat");
	conf.output = par.get("o");
	conf.k_folds = reg.default_k;
	conf.bootstrap_samples = reg.default_no_boostrap_samples;
	conf.no_of_permutation_tests = reg.default_no_permutations;

	String type = par.get("type");
	if (type=="cross_validation" || type=="cross validation")
	{
		conf.val_type = 2;
	}
	else if (type=="bootstrapping")
	{
		conf.val_type = 3;
	}
	else if (type=="response_permutation" || type=="response permutation")
	{
		conf.val_type = 4;
	}
	else if (type=="simple_prediction" || type=="evaluate fit to test data")
	{
		conf.val_type = 1;
	}
	else
	{
		cerr << "Validation-type '"<<type<<"' unknown, possible choices are:"<<endl;
		cerr<<"   "<<"cross_validation"<<endl;
		cerr<<"   "<<"bootstrapping"<<endl;
		cerr<<"   "<<"response_permutation"<<endl;
		cerr<<"   "<<"simple_prediction   = quality of predictions done for given predictions data set only (no sampling)"<<endl;
		exit(1);
	}

	startValidation(conf,0,0);
}
#endif
<|endoftext|>


<commit_before>/* The MIT License

   Copyright (c) 2014 Adrian Tan <atks@umich.edu>

   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 "cat.h"

namespace
{

class Igor : Program
{
    public:

    std::string version;

    ///////////
    //options//
    ///////////
    std::vector<std::string> input_vcf_files;
    std::string input_vcf_file_list;
    std::string output_vcf_file;
    std::vector<GenomeInterval> intervals;
    std::string interval_list;
    uint32_t sort_window_size;
    bool print;
    bool print_sites_only;
    int32_t no_subset_samples;

    ///////
    //i/o//
    ///////
    BCFOrderedReader *odr;
    BCFOrderedWriter *odw;

    //////////
    //filter//
    //////////
    std::string fexp;
    Filter filter;
    bool filter_exists;

    /////////
    //stats//
    /////////
    uint32_t no_variants;

    /////////
    //tools//
    /////////
    VariantManip *vm;

    Igor(int argc, char ** argv)
    {
        //////////////////////////
        //options initialization//
        //////////////////////////
        try
        {
            std::string desc = "Concatenate VCF files.  Assumes individuals are in the same order and files share the same header.";

            version = "0.5";
            TCLAP::CmdLine cmd(desc, ' ', version);
            VTOutput my; cmd.setOutput(&my);
            TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals", false, "", "str", cmd);
            TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "str", cmd);
            TCLAP::ValueArg<std::string> arg_output_vcf_file("o", "o", "output VCF file [-]", false, "-", "", cmd);
            TCLAP::ValueArg<std::string> arg_input_vcf_file_list("L", "L", "file containing list of input VCF files", false, "", "str", cmd);
            TCLAP::ValueArg<std::string> arg_fexp("f", "f", "filter expression []", false, "", "str", cmd);
            TCLAP::ValueArg<uint32_t> arg_sort_window_size("w", "w", "local sorting window size [0]", false, 0, "int", cmd);
            TCLAP::SwitchArg arg_print("p", "p", "print options and summary []", cmd, false);
            TCLAP::SwitchArg arg_print_sites_only("s", "s", "print site information only without genotypes [false]", cmd, false);
            TCLAP::UnlabeledMultiArg<std::string> arg_input_vcf_files("<in1.vcf>...", "Multiple VCF files",false, "files", cmd);

            cmd.parse(argc, argv);

            parse_files(input_vcf_files, arg_input_vcf_files.getValue(), arg_input_vcf_file_list.getValue());
            output_vcf_file = arg_output_vcf_file.getValue();
            fexp = arg_fexp.getValue();
            sort_window_size = arg_sort_window_size.getValue();
            parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue());
            no_subset_samples = arg_print_sites_only.getValue() ? 0 : -1;
            print = arg_print.getValue();

            if (input_vcf_files.size()==0)
            {
                fprintf(stderr, "[E:%s:%d %s] no input vcf files.\n", __FILE__, __LINE__, __FUNCTION__);
                exit(1);
            }
        }
        catch (TCLAP::ArgException &e)
        {
            std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n";
            abort();
        }
    };

    void initialize()
    {
        //////////////////////
        //i/o initialization//
        //////////////////////
        odr = new BCFOrderedReader(input_vcf_files[0], intervals);

        std::cerr << "sorting window size: " << sort_window_size << "\n";

        odw = new BCFOrderedWriter(output_vcf_file, sort_window_size);
        if (no_subset_samples==-1)
        {
            odw->set_hdr(odr->hdr);
        }
        else if (no_subset_samples==0)
        {
            odw->set_hdr(bcf_hdr_subset(odr->hdr, 0, 0, 0));
        }

        /////////////////////////
        //filter initialization//
        /////////////////////////
        filter.parse(fexp.c_str());
        filter_exists = fexp=="" ? false : true;

        ////////////////////////
        //stats initialization//
        ////////////////////////
        no_variants = 0;

        ///////////////////////
        //tool initialization//
        ///////////////////////
        vm = new VariantManip("");
    }

    void cat()
    {
        odw->write_hdr();
        bcf1_t *v = bcf_init();
        Variant variant;

        for (size_t i=0; i<input_vcf_files.size(); ++i)
        {
            if (i)
            {
                delete odr;
                odr = new BCFOrderedReader(input_vcf_files[i], intervals);
            }

            while(odr->read(v))
            {
                if (filter_exists)
                {
                    vm->classify_variant(odr->hdr, v, variant);
                    if (!filter.apply(odr->hdr, v, &variant))
                    {
                        continue;
                    }
                }

                if (no_subset_samples==0)
                {
                    bcf_subset(odw->hdr, v, 0, 0);
                    //maybe add some additional adhoc fixing for BCF files that do not have a complete header.
                }

                //assume the contigs list is the same for all?  Do we have checking for this?
                //bcf_set_chrom(odw->hdr, v, bcf_get_chrom(odr->hdr, v));
                odw->write(v);
                if (sort_window_size)
                {
                    v = odw->get_bcf1_from_pool();
                }
                ++no_variants;
            }

            odr->close();
        }

        odw->close();
    };

    void print_options()
    {
        if (!print) return;

        std::clog << "cat v" << version << "\n\n";
        print_ifiles("options:     input VCF file        ", input_vcf_files);
        std::clog << "         [o] output VCF file       " << output_vcf_file << "\n";
        print_num_op("         [w] sortin window size    ", sort_window_size);
        print_str_op("         [f] filter                ", fexp);
        print_int_op("         [i] intervals             ", intervals);
        std::clog << "\n";
    }

    void print_stats()
    {
        if (!print) return;

        std::clog << "\n";
        std::cerr << "stats: no. of variants   " << no_variants << "\n";
        std::clog << "\n";
    };

    ~Igor()
    {
    };

    private:
};

}

bool cat(int argc, char ** argv)
{
    Igor igor(argc, argv);
    igor.print_options();
    igor.initialize();
    igor.cat();
    igor.print_stats();
    return igor.print;
}<commit_msg>removed debug statements for cat.<commit_after>/* The MIT License

   Copyright (c) 2014 Adrian Tan <atks@umich.edu>

   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 "cat.h"

namespace
{

class Igor : Program
{
    public:

    std::string version;

    ///////////
    //options//
    ///////////
    std::vector<std::string> input_vcf_files;
    std::string input_vcf_file_list;
    std::string output_vcf_file;
    std::vector<GenomeInterval> intervals;
    std::string interval_list;
    uint32_t sort_window_size;
    bool print;
    bool print_sites_only;
    int32_t no_subset_samples;

    ///////
    //i/o//
    ///////
    BCFOrderedReader *odr;
    BCFOrderedWriter *odw;

    //////////
    //filter//
    //////////
    std::string fexp;
    Filter filter;
    bool filter_exists;

    /////////
    //stats//
    /////////
    uint32_t no_variants;

    /////////
    //tools//
    /////////
    VariantManip *vm;

    Igor(int argc, char ** argv)
    {
        //////////////////////////
        //options initialization//
        //////////////////////////
        try
        {
            std::string desc = "Concatenate VCF files.  Assumes individuals are in the same order and files share the same header.";

            version = "0.5";
            TCLAP::CmdLine cmd(desc, ' ', version);
            VTOutput my; cmd.setOutput(&my);
            TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals", false, "", "str", cmd);
            TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "str", cmd);
            TCLAP::ValueArg<std::string> arg_output_vcf_file("o", "o", "output VCF file [-]", false, "-", "", cmd);
            TCLAP::ValueArg<std::string> arg_input_vcf_file_list("L", "L", "file containing list of input VCF files", false, "", "str", cmd);
            TCLAP::ValueArg<std::string> arg_fexp("f", "f", "filter expression []", false, "", "str", cmd);
            TCLAP::ValueArg<uint32_t> arg_sort_window_size("w", "w", "local sorting window size [0]", false, 0, "int", cmd);
            TCLAP::SwitchArg arg_print("p", "p", "print options and summary []", cmd, false);
            TCLAP::SwitchArg arg_print_sites_only("s", "s", "print site information only without genotypes [false]", cmd, false);
            TCLAP::UnlabeledMultiArg<std::string> arg_input_vcf_files("<in1.vcf>...", "Multiple VCF files",false, "files", cmd);

            cmd.parse(argc, argv);

            parse_files(input_vcf_files, arg_input_vcf_files.getValue(), arg_input_vcf_file_list.getValue());
            output_vcf_file = arg_output_vcf_file.getValue();
            fexp = arg_fexp.getValue();
            sort_window_size = arg_sort_window_size.getValue();
            parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue());
            no_subset_samples = arg_print_sites_only.getValue() ? 0 : -1;
            print = arg_print.getValue();

            if (input_vcf_files.size()==0)
            {
                fprintf(stderr, "[E:%s:%d %s] no input vcf files.\n", __FILE__, __LINE__, __FUNCTION__);
                exit(1);
            }
        }
        catch (TCLAP::ArgException &e)
        {
            std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n";
            abort();
        }
    };

    void initialize()
    {
        //////////////////////
        //i/o initialization//
        //////////////////////
        odr = new BCFOrderedReader(input_vcf_files[0], intervals);
        odw = new BCFOrderedWriter(output_vcf_file, sort_window_size);
        if (no_subset_samples==-1)
        {
            odw->set_hdr(odr->hdr);
        }
        else if (no_subset_samples==0)
        {
            odw->set_hdr(bcf_hdr_subset(odr->hdr, 0, 0, 0));
        }

        /////////////////////////
        //filter initialization//
        /////////////////////////
        filter.parse(fexp.c_str());
        filter_exists = fexp=="" ? false : true;

        ////////////////////////
        //stats initialization//
        ////////////////////////
        no_variants = 0;

        ///////////////////////
        //tool initialization//
        ///////////////////////
        vm = new VariantManip("");
    }

    void cat()
    {
        odw->write_hdr();
        bcf1_t *v = bcf_init();
        Variant variant;

        for (size_t i=0; i<input_vcf_files.size(); ++i)
        {
            if (i)
            {
                delete odr;
                odr = new BCFOrderedReader(input_vcf_files[i], intervals);
            }

            while(odr->read(v))
            {
                if (filter_exists)
                {
                    vm->classify_variant(odr->hdr, v, variant);
                    if (!filter.apply(odr->hdr, v, &variant))
                    {
                        continue;
                    }
                }

                if (no_subset_samples==0)
                {
                    bcf_subset(odw->hdr, v, 0, 0);
                    //maybe add some additional adhoc fixing for BCF files that do not have a complete header.
                }

                //assume the contigs list is the same for all?  Do we have checking for this?
                //bcf_set_chrom(odw->hdr, v, bcf_get_chrom(odr->hdr, v));
                odw->write(v);
                if (sort_window_size)
                {
                    v = odw->get_bcf1_from_pool();
                }
                ++no_variants;
            }

            odr->close();
        }

        odw->close();
    };

    void print_options()
    {
        if (!print) return;

        std::clog << "cat v" << version << "\n\n";
        print_ifiles("options:     input VCF file        ", input_vcf_files);
        std::clog << "         [o] output VCF file       " << output_vcf_file << "\n";
        print_num_op("         [w] sortin window size    ", sort_window_size);
        print_str_op("         [f] filter                ", fexp);
        print_int_op("         [i] intervals             ", intervals);
        std::clog << "\n";
    }

    void print_stats()
    {
        if (!print) return;

        std::clog << "\n";
        std::cerr << "stats: no. of variants   " << no_variants << "\n";
        std::clog << "\n";
    };

    ~Igor()
    {
    };

    private:
};

}

bool cat(int argc, char ** argv)
{
    Igor igor(argc, argv);
    igor.print_options();
    igor.initialize();
    igor.cat();
    igor.print_stats();
    return igor.print;
}<|endoftext|>


<commit_before>//
// Copyright 2013 Jeff Bush
//
// 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 "output.h"

void sort(char *array, int length)
{
	for (int i = 0; i < length - 1; i++)
	{
		for (int j = i + 1; j < length; j++)
		{
			if (array[i] > array[j])
			{
				char tmp = array[i];
				array[i] = array[j];
				array[j] = tmp;
			}
		}
	}
}

Output output;

int main()
{
	char tmp[11] = "atjlnpqdgs";
	sort(tmp, 10);

	for (int i = 0; i < 10; i++)
		output << tmp[i];

	output << "\n";

	// CHECK: adgjlnpqst

	return 0;
}
<commit_msg>Add quicksort test<commit_after>/*-
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  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.
 * 3. Neither the name of the University 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 REGENTS 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 REGENTS 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 "output.h"
#include "cxx_runtime.h"

#define NULL 0

typedef unsigned int size_t;
typedef int		 cmp_t(const void *, const void *);
static inline char	*med3(char *, char *, char *, cmp_t *, void *);
static inline void	 swapfunc(void *, void *, int, int);

#define min(a, b)	(a) < (b) ? a : b

/*
 * Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
 */
#define swapcode(TYPE, parmi, parmj, n) { 		\
	long i = (n) / sizeof (TYPE); 			\
	TYPE *pi = (TYPE *) (parmi); 		\
	TYPE *pj = (TYPE *) (parmj); 		\
	do { 						\
		TYPE	t = *pi;		\
		*pi++ = *pj;				\
		*pj++ = t;				\
        } while (--i > 0);				\
}

#define SWAPINIT(a, es) swaptype = ((char *)a - (char *)0) % sizeof(long) || \
	es % sizeof(long) ? 2 : es == sizeof(long)? 0 : 1;

static inline void
swapfunc(void *a, void *b, int n, int swaptype)
{
	if(swaptype <= 1)
		swapcode(long, a, b, n)
	else
		swapcode(char, a, b, n)
}

#define swap(a, b)					\
	if (swaptype == 0) {				\
		long t = *(long *)(a);			\
		*(long *)(a) = *(long *)(b);		\
		*(long *)(b) = t;			\
	} else						\
		swapfunc(a, b, es, swaptype)

#define vecswap(a, b, n) 	if ((n) > 0) swapfunc(a, b, n, swaptype)

#define	CMP(t, x, y) (cmp((x), (y)))

static inline char *
med3(char *a, char *b, char *c, cmp_t *cmp, void *thunk)
{
	return CMP(thunk, a, b) < 0 ?
	       (CMP(thunk, b, c) < 0 ? b : (CMP(thunk, a, c) < 0 ? c : a ))
              :(CMP(thunk, b, c) > 0 ? b : (CMP(thunk, a, c) < 0 ? a : c ));
}

#define thunk NULL
void
qsort(void *a, size_t n, size_t es, cmp_t *cmp)
{
	char *pa, *pb, *pc, *pd, *pl, *pm, *pn;
	size_t d, r;
	int cmp_result;
	int swaptype, swap_cnt;

loop:	SWAPINIT(a, es);
	swap_cnt = 0;
	if (n < 7) {
		for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
			for (pl = pm;
			     pl > (char *)a && CMP(thunk, pl - es, pl) > 0;
			     pl -= es)
				swap(pl, pl - es);
		return;
	}
	pm = (char *)a + (n / 2) * es;
	if (n > 7) {
		pl = (char*) a;
		pn = (char *)a + (n - 1) * es;
		if (n > 40) {
			d = (n / 8) * es;
			pl = med3(pl, pl + d, pl + 2 * d, cmp, thunk);
			pm = med3(pm - d, pm, pm + d, cmp, thunk);
			pn = med3(pn - 2 * d, pn - d, pn, cmp, thunk);
		}
		pm = med3(pl, pm, pn, cmp, thunk);
	}
	swap(a, pm);
	pa = pb = (char *)a + es;

	pc = pd = (char *)a + (n - 1) * es;
	for (;;) {
		while (pb <= pc && (cmp_result = CMP(thunk, pb, a)) <= 0) {
			if (cmp_result == 0) {
				swap_cnt = 1;
				swap(pa, pb);
				pa += es;
			}
			pb += es;
		}
		while (pb <= pc && (cmp_result = CMP(thunk, pc, a)) >= 0) {
			if (cmp_result == 0) {
				swap_cnt = 1;
				swap(pc, pd);
				pd -= es;
			}
			pc -= es;
		}
		if (pb > pc)
			break;
		swap(pb, pc);
		swap_cnt = 1;
		pb += es;
		pc -= es;
	}
	if (swap_cnt == 0) {  /* Switch to insertion sort */
		for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
			for (pl = pm;
			     pl > (char *)a && CMP(thunk, pl - es, pl) > 0;
			     pl -= es)
				swap(pl, pl - es);
		return;
	}

	pn = (char *)a + n * es;
	r = min(pa - (char *)a, pb - pa);
	vecswap(a, pb - r, r);
	r = min(pd - pc, pn - pd - es);
	vecswap(pb, pn - r, r);
	if ((r = pb - pa) > es)
		qsort(a, r / es, es, cmp);
	if ((r = pd - pc) > es) {
		/* Iterate rather than recurse to save stack space */
		a = pn - r;
		n = r / es;
		goto loop;
	}
/*		qsort(pn - r, r / es, es, cmp);*/
}

Output output;

int cmpchar(const void *a, const void *b)
{
	char _a = *((const char *)a);
	char _b = *((const char *)b);
	return _a - _b;
}

int main()
{
	char tmp[14] = "aztjlnvpwqdgs";
	qsort(tmp, 13, 1, cmpchar);

	for (int i = 0; i < 13; i++)
		output << tmp[i];

	output << "\n";

	// CHECK: adgjlnpqstvwz

	return 0;
}
<|endoftext|>


<commit_before>/*  This file is part of the KDE project.

    Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).

    This library is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 2.1 or 3 of the License.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this library.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "gsthelper.h"

#include <gst/interfaces/propertyprobe.h>
#include <gst/gst.h>
#include "mediaobject.h"
#include "backend.h"

#include <QtCore/QList>

namespace Phonon
{
namespace Gstreamer
{

/**
 * Probes a gstElement for a list of settable string-property values
 *
 * @return a QStringList containing a list of allwed string values for the given
 *           element
 */
QList<QByteArray> GstHelper::extractProperties(GstElement *elem, const QByteArray &value)
{
    Q_ASSERT(elem);
    QList<QByteArray> list;

    if (GST_IS_PROPERTY_PROBE(elem)) {
        GstPropertyProbe *probe = GST_PROPERTY_PROBE(elem);
        const GParamSpec *devspec = 0;
        GValueArray *array = NULL;

        if ((devspec = gst_property_probe_get_property (probe, value))) {
            if ((array = gst_property_probe_probe_and_get_values (probe, devspec))) {
                for (unsigned int device = 0; device < array->n_values; device++) {
                    GValue *deviceId = g_value_array_get_nth (array, device);
                    list.append(g_value_get_string(deviceId));
                }
            }
            if (array)
                g_value_array_free (array);
        }
    }
    return list;
}

/**
 * Sets the string value of a GstElement's property
 *
 * @return false if the value could not be set.
 */
bool GstHelper::setProperty(GstElement *elem, const char *propertyName, const QByteArray &propertyValue)
{
    Q_ASSERT(elem);
    Q_ASSERT(propertyName && strlen(propertyName));

    if (GST_IS_PROPERTY_PROBE(elem) && gst_property_probe_get_property( GST_PROPERTY_PROBE( elem), propertyName ) ) {
        g_object_set(G_OBJECT(elem), propertyName, propertyValue.constData(), NULL);
        return true;
    }
    return false;
}

/**
 * Queries an element for the value of an object property
 */
QByteArray GstHelper::property(GstElement *elem, const char *propertyName)
{
    Q_ASSERT(elem);
    Q_ASSERT(propertyName && strlen(propertyName));
    QByteArray retVal;

    if (GST_IS_PROPERTY_PROBE(elem) && gst_property_probe_get_property( GST_PROPERTY_PROBE(elem), propertyName)) {
        gchar *value = NULL;
        g_object_get (G_OBJECT(elem), propertyName, &value, NULL);
        retVal = QByteArray(value);
        g_free (value);
    }
    return retVal;
}

/**
 * Queries a GstObject for it's name
 */
QByteArray GstHelper::name(GstObject *obj)
{
    Q_ASSERT(obj);
    QByteArray retVal;
    gchar *value = NULL;
    if ((value = gst_object_get_name (obj))) {
        retVal = QByteArray(value);
        g_free (value);
    }
    return retVal;
}

QString GstHelper::stateName(GstState state)
{
    switch(state) {
    case GST_STATE_VOID_PENDING:
        return "void pending";
    case GST_STATE_NULL:
        return "null";
    case GST_STATE_READY:
        return "ready";
    case GST_STATE_PAUSED:
        return "paused";
    case GST_STATE_PLAYING:
        return "playing";
    }
    return "";
}

} //namespace Gstreamer
} //namespace Phonon
<commit_msg>Partially port gsthelper.cpp<commit_after>/*  This file is part of the KDE project.

    Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).

    This library is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 2.1 or 3 of the License.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this library.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "gsthelper.h"

#include "phonon-config-gstreamer.h"

#include <gst/gst.h>

#if GST_VERSION < GST_VERSION_CHECK (1,0,0,0)
#include <gst/interfaces/propertyprobe.h>
#endif
#include "mediaobject.h"
#include "backend.h"

#include <QtCore/QList>

namespace Phonon
{
namespace Gstreamer
{

/**
 * Probes a gstElement for a list of settable string-property values
 *
 * @return a QStringList containing a list of allwed string values for the given
 *           element
 */
QList<QByteArray> GstHelper::extractProperties(GstElement *elem, const QByteArray &value)
{
    Q_ASSERT(elem);
    QList<QByteArray> list;

#if GST_VERSION < GST_VERSION_CHECK (1,0,0,0)
    if (GST_IS_PROPERTY_PROBE(elem)) {
        GstPropertyProbe *probe = GST_PROPERTY_PROBE(elem);
        const GParamSpec *devspec = 0;
        GValueArray *array = NULL;

        if ((devspec = gst_property_probe_get_property (probe, value))) {
            if ((array = gst_property_probe_probe_and_get_values (probe, devspec))) {
                for (unsigned int device = 0; device < array->n_values; device++) {
                    GValue *deviceId = g_value_array_get_nth (array, device);
                    list.append(g_value_get_string(deviceId));
                }
            }
            if (array)
                g_value_array_free (array);
        }
    }
#endif
    return list;
}

/**
 * Sets the string value of a GstElement's property
 *
 * @return false if the value could not be set.
 */
bool GstHelper::setProperty(GstElement *elem, const char *propertyName, const QByteArray &propertyValue)
{
    Q_ASSERT(elem);
    Q_ASSERT(propertyName && strlen(propertyName));

    if (g_object_class_find_property (G_OBJECT_GET_CLASS(elem), propertyName)) {
        g_object_set(G_OBJECT(elem), propertyName, propertyValue.constData(), NULL);
        return true;
    }
    return false;
}

/**
 * Queries an element for the value of an object property
 */
QByteArray GstHelper::property(GstElement *elem, const char *propertyName)
{
    Q_ASSERT(elem);
    Q_ASSERT(propertyName && strlen(propertyName));
    QByteArray retVal;

    if (g_object_class_find_property (G_OBJECT_GET_CLASS(elem), propertyName)) {
        gchar *value = NULL;
        g_object_get (G_OBJECT(elem), propertyName, &value, NULL);
        retVal = QByteArray(value);
        g_free (value);
    }
    return retVal;
}

/**
 * Queries a GstObject for it's name
 */
QByteArray GstHelper::name(GstObject *obj)
{
    Q_ASSERT(obj);
    QByteArray retVal;
    gchar *value = NULL;
    if ((value = gst_object_get_name (obj))) {
        retVal = QByteArray(value);
        g_free (value);
    }
    return retVal;
}

QString GstHelper::stateName(GstState state)
{
    switch(state) {
    case GST_STATE_VOID_PENDING:
        return "void pending";
    case GST_STATE_NULL:
        return "null";
    case GST_STATE_READY:
        return "ready";
    case GST_STATE_PAUSED:
        return "paused";
    case GST_STATE_PLAYING:
        return "playing";
    }
    return "";
}

} //namespace Gstreamer
} //namespace Phonon
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "jsextensions_p.h"

#include <language/scriptengine.h>
#include <logging/translator.h>
#include <tools/fileinfo.h>
#include <tools/stringconstants.h>

#include <QtCore/qdir.h>
#include <QtCore/qfileinfo.h>

#include <QtScript/qscriptable.h>
#include <QtScript/qscriptengine.h>

#include <regex>

namespace qbs {
namespace Internal {

class FileInfoExtension : public QObject, QScriptable
{
    Q_OBJECT
public:
    static QScriptValue js_ctor(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_path(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_fileName(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_baseName(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_cleanPath(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_completeBaseName(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_relativePath(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_resolvePath(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_isAbsolutePath(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_toWindowsSeparators(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_fromWindowsSeparators(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_toNativeSeparators(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_fromNativeSeparators(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_joinPaths(QScriptContext *context, QScriptEngine *engine);
};

static void initializeJsExtensionFileInfo(QScriptValue extensionObject)
{
    QScriptEngine *engine = extensionObject.engine();
    QScriptValue fileInfoObj = engine->newQMetaObject(&FileInfoExtension::staticMetaObject,
                                                  engine->newFunction(&FileInfoExtension::js_ctor));
    fileInfoObj.setProperty(StringConstants::fileInfoPath(),
                            engine->newFunction(FileInfoExtension::js_path));
    fileInfoObj.setProperty(StringConstants::fileInfoFileName(),
                            engine->newFunction(FileInfoExtension::js_fileName));
    fileInfoObj.setProperty(StringConstants::baseNameProperty(),
                            engine->newFunction(FileInfoExtension::js_baseName));
    fileInfoObj.setProperty(QLatin1String("cleanPath"),
                            engine->newFunction(FileInfoExtension::js_cleanPath));
    fileInfoObj.setProperty(StringConstants::completeBaseNameProperty(),
                            engine->newFunction(FileInfoExtension::js_completeBaseName));
    fileInfoObj.setProperty(QLatin1String("relativePath"),
                            engine->newFunction(FileInfoExtension::js_relativePath));
    fileInfoObj.setProperty(QLatin1String("resolvePath"),
                            engine->newFunction(FileInfoExtension::js_resolvePath));
    fileInfoObj.setProperty(QLatin1String("isAbsolutePath"),
                            engine->newFunction(FileInfoExtension::js_isAbsolutePath));
    fileInfoObj.setProperty(QLatin1String("toWindowsSeparators"),
                            engine->newFunction(FileInfoExtension::js_toWindowsSeparators));
    fileInfoObj.setProperty(QLatin1String("fromWindowsSeparators"),
                            engine->newFunction(FileInfoExtension::js_fromWindowsSeparators));
    fileInfoObj.setProperty(QLatin1String("toNativeSeparators"),
                            engine->newFunction(FileInfoExtension::js_toWindowsSeparators));
    fileInfoObj.setProperty(QLatin1String("fromNativeSeparators"),
                            engine->newFunction(FileInfoExtension::js_fromWindowsSeparators));
    fileInfoObj.setProperty(QLatin1String("joinPaths"),
                            engine->newFunction(FileInfoExtension::js_joinPaths));
    extensionObject.setProperty(QLatin1String("FileInfo"), fileInfoObj);
}

QBS_JSEXTENSION_REGISTER(FileInfo, &initializeJsExtensionFileInfo)

QScriptValue FileInfoExtension::js_ctor(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    return context->throwError(Tr::tr("'FileInfo' cannot be instantiated."));
}

QScriptValue FileInfoExtension::js_path(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("path expects 1 argument"));
    }
    HostOsInfo::HostOs hostOs = HostOsInfo::hostOs();
    if (context->argumentCount() > 1) {
        hostOs = context->argument(1).toVariant().toStringList().contains(QLatin1String("windows"))
                ? HostOsInfo::HostOsWindows : HostOsInfo::HostOsOtherUnix;
    }
    return FileInfo::path(context->argument(0).toString(), hostOs);
}

QScriptValue FileInfoExtension::js_fileName(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("fileName expects 1 argument"));
    }
    return FileInfo::fileName(context->argument(0).toString());
}

QScriptValue FileInfoExtension::js_baseName(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("baseName expects 1 argument"));
    }
    return FileInfo::baseName(context->argument(0).toString());
}

QScriptValue FileInfoExtension::js_cleanPath(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("cleanPath expects 1 argument"));
    }
    return QDir::cleanPath(context->argument(0).toString());
}

QScriptValue FileInfoExtension::js_completeBaseName(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("completeBaseName expects 1 argument"));
    }
    return FileInfo::completeBaseName(context->argument(0).toString());
}

QScriptValue FileInfoExtension::js_relativePath(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("relativePath expects 2 arguments"));
    }
    const QString baseDir = context->argument(0).toString();
    const QString filePath = context->argument(1).toString();
    if (!FileInfo::isAbsolute(baseDir)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("FileInfo.relativePath() expects an absolute path as "
                                          "its first argument, but it is '%1'.").arg(baseDir));
    }
    if (!FileInfo::isAbsolute(filePath)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("FileInfo.relativePath() expects an absolute path as "
                                          "its second argument, but it is '%1'.").arg(filePath));
    }
    return QDir(baseDir).relativeFilePath(filePath);
}

QScriptValue FileInfoExtension::js_resolvePath(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("resolvePath expects 2 arguments"));
    }
    const QString base = context->argument(0).toString();
    const QString rel = context->argument(1).toString();
    return FileInfo::resolvePath(base, rel);
}

QScriptValue FileInfoExtension::js_isAbsolutePath(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("isAbsolutePath expects 1 argument"));
    }
    HostOsInfo::HostOs hostOs = HostOsInfo::hostOs();
    if (context->argumentCount() > 1) {
        hostOs = context->argument(1).toVariant().toStringList().contains(QLatin1String("windows"))
                ? HostOsInfo::HostOsWindows : HostOsInfo::HostOsOtherUnix;
    }
    return FileInfo::isAbsolute(context->argument(0).toString(), hostOs);
}

QScriptValue FileInfoExtension::js_toWindowsSeparators(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("toWindowsSeparators expects 1 argument"));
    }
    return context->argument(0).toString().replace(QLatin1Char('/'), QLatin1Char('\\'));
}

QScriptValue FileInfoExtension::js_fromWindowsSeparators(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("fromWindowsSeparators expects 1 argument"));
    }
    return context->argument(0).toString().replace(QLatin1Char('\\'), QLatin1Char('/'));
}

QScriptValue FileInfoExtension::js_toNativeSeparators(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("toNativeSeparators expects 1 argument"));
    }
    return QDir::toNativeSeparators(context->argument(0).toString());
}

QScriptValue FileInfoExtension::js_fromNativeSeparators(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("fromNativeSeparators expects 1 argument"));
    }
    return QDir::fromNativeSeparators(context->argument(0).toString());
}

QScriptValue FileInfoExtension::js_joinPaths(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    QStringList paths;
    for (int i = 0; i < context->argumentCount(); ++i) {
        const QScriptValue value = context->argument(i);
        if (!value.isUndefined() && !value.isNull()) {
            const QString arg = value.toString();
            if (!arg.isEmpty())
                paths.push_back(arg);
        }
    }
    return engine->toScriptValue(QString::fromStdString(
                                     std::regex_replace(paths.join(QLatin1Char('/')).toStdString(),
                                                        std::regex("/{2,}"), "/")));
}

} // namespace Internal
} // namespace qbs

Q_DECLARE_METATYPE(qbs::Internal::FileInfoExtension *)

#include "fileinfoextension.moc"
<commit_msg>Fix FileInfo.{to,from}NativeSeparators()<commit_after>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "jsextensions_p.h"

#include <language/scriptengine.h>
#include <logging/translator.h>
#include <tools/fileinfo.h>
#include <tools/stringconstants.h>

#include <QtCore/qdir.h>
#include <QtCore/qfileinfo.h>

#include <QtScript/qscriptable.h>
#include <QtScript/qscriptengine.h>

#include <regex>

namespace qbs {
namespace Internal {

class FileInfoExtension : public QObject, QScriptable
{
    Q_OBJECT
public:
    static QScriptValue js_ctor(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_path(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_fileName(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_baseName(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_cleanPath(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_completeBaseName(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_relativePath(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_resolvePath(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_isAbsolutePath(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_toWindowsSeparators(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_fromWindowsSeparators(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_toNativeSeparators(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_fromNativeSeparators(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_joinPaths(QScriptContext *context, QScriptEngine *engine);
};

static void initializeJsExtensionFileInfo(QScriptValue extensionObject)
{
    QScriptEngine *engine = extensionObject.engine();
    QScriptValue fileInfoObj = engine->newQMetaObject(&FileInfoExtension::staticMetaObject,
                                                  engine->newFunction(&FileInfoExtension::js_ctor));
    fileInfoObj.setProperty(StringConstants::fileInfoPath(),
                            engine->newFunction(FileInfoExtension::js_path));
    fileInfoObj.setProperty(StringConstants::fileInfoFileName(),
                            engine->newFunction(FileInfoExtension::js_fileName));
    fileInfoObj.setProperty(StringConstants::baseNameProperty(),
                            engine->newFunction(FileInfoExtension::js_baseName));
    fileInfoObj.setProperty(QLatin1String("cleanPath"),
                            engine->newFunction(FileInfoExtension::js_cleanPath));
    fileInfoObj.setProperty(StringConstants::completeBaseNameProperty(),
                            engine->newFunction(FileInfoExtension::js_completeBaseName));
    fileInfoObj.setProperty(QLatin1String("relativePath"),
                            engine->newFunction(FileInfoExtension::js_relativePath));
    fileInfoObj.setProperty(QLatin1String("resolvePath"),
                            engine->newFunction(FileInfoExtension::js_resolvePath));
    fileInfoObj.setProperty(QLatin1String("isAbsolutePath"),
                            engine->newFunction(FileInfoExtension::js_isAbsolutePath));
    fileInfoObj.setProperty(QLatin1String("toWindowsSeparators"),
                            engine->newFunction(FileInfoExtension::js_toWindowsSeparators));
    fileInfoObj.setProperty(QLatin1String("fromWindowsSeparators"),
                            engine->newFunction(FileInfoExtension::js_fromWindowsSeparators));
    fileInfoObj.setProperty(QLatin1String("toNativeSeparators"),
                            engine->newFunction(FileInfoExtension::js_toNativeSeparators));
    fileInfoObj.setProperty(QLatin1String("fromNativeSeparators"),
                            engine->newFunction(FileInfoExtension::js_fromNativeSeparators));
    fileInfoObj.setProperty(QLatin1String("joinPaths"),
                            engine->newFunction(FileInfoExtension::js_joinPaths));
    extensionObject.setProperty(QLatin1String("FileInfo"), fileInfoObj);
}

QBS_JSEXTENSION_REGISTER(FileInfo, &initializeJsExtensionFileInfo)

QScriptValue FileInfoExtension::js_ctor(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    return context->throwError(Tr::tr("'FileInfo' cannot be instantiated."));
}

QScriptValue FileInfoExtension::js_path(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("path expects 1 argument"));
    }
    HostOsInfo::HostOs hostOs = HostOsInfo::hostOs();
    if (context->argumentCount() > 1) {
        hostOs = context->argument(1).toVariant().toStringList().contains(QLatin1String("windows"))
                ? HostOsInfo::HostOsWindows : HostOsInfo::HostOsOtherUnix;
    }
    return FileInfo::path(context->argument(0).toString(), hostOs);
}

QScriptValue FileInfoExtension::js_fileName(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("fileName expects 1 argument"));
    }
    return FileInfo::fileName(context->argument(0).toString());
}

QScriptValue FileInfoExtension::js_baseName(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("baseName expects 1 argument"));
    }
    return FileInfo::baseName(context->argument(0).toString());
}

QScriptValue FileInfoExtension::js_cleanPath(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("cleanPath expects 1 argument"));
    }
    return QDir::cleanPath(context->argument(0).toString());
}

QScriptValue FileInfoExtension::js_completeBaseName(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("completeBaseName expects 1 argument"));
    }
    return FileInfo::completeBaseName(context->argument(0).toString());
}

QScriptValue FileInfoExtension::js_relativePath(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("relativePath expects 2 arguments"));
    }
    const QString baseDir = context->argument(0).toString();
    const QString filePath = context->argument(1).toString();
    if (!FileInfo::isAbsolute(baseDir)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("FileInfo.relativePath() expects an absolute path as "
                                          "its first argument, but it is '%1'.").arg(baseDir));
    }
    if (!FileInfo::isAbsolute(filePath)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("FileInfo.relativePath() expects an absolute path as "
                                          "its second argument, but it is '%1'.").arg(filePath));
    }
    return QDir(baseDir).relativeFilePath(filePath);
}

QScriptValue FileInfoExtension::js_resolvePath(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("resolvePath expects 2 arguments"));
    }
    const QString base = context->argument(0).toString();
    const QString rel = context->argument(1).toString();
    return FileInfo::resolvePath(base, rel);
}

QScriptValue FileInfoExtension::js_isAbsolutePath(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("isAbsolutePath expects 1 argument"));
    }
    HostOsInfo::HostOs hostOs = HostOsInfo::hostOs();
    if (context->argumentCount() > 1) {
        hostOs = context->argument(1).toVariant().toStringList().contains(QLatin1String("windows"))
                ? HostOsInfo::HostOsWindows : HostOsInfo::HostOsOtherUnix;
    }
    return FileInfo::isAbsolute(context->argument(0).toString(), hostOs);
}

QScriptValue FileInfoExtension::js_toWindowsSeparators(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("toWindowsSeparators expects 1 argument"));
    }
    return context->argument(0).toString().replace(QLatin1Char('/'), QLatin1Char('\\'));
}

QScriptValue FileInfoExtension::js_fromWindowsSeparators(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("fromWindowsSeparators expects 1 argument"));
    }
    return context->argument(0).toString().replace(QLatin1Char('\\'), QLatin1Char('/'));
}

QScriptValue FileInfoExtension::js_toNativeSeparators(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("toNativeSeparators expects 1 argument"));
    }
    return QDir::toNativeSeparators(context->argument(0).toString());
}

QScriptValue FileInfoExtension::js_fromNativeSeparators(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    if (Q_UNLIKELY(context->argumentCount() < 1)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("fromNativeSeparators expects 1 argument"));
    }
    return QDir::fromNativeSeparators(context->argument(0).toString());
}

QScriptValue FileInfoExtension::js_joinPaths(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(engine);
    QStringList paths;
    for (int i = 0; i < context->argumentCount(); ++i) {
        const QScriptValue value = context->argument(i);
        if (!value.isUndefined() && !value.isNull()) {
            const QString arg = value.toString();
            if (!arg.isEmpty())
                paths.push_back(arg);
        }
    }
    return engine->toScriptValue(QString::fromStdString(
                                     std::regex_replace(paths.join(QLatin1Char('/')).toStdString(),
                                                        std::regex("/{2,}"), "/")));
}

} // namespace Internal
} // namespace qbs

Q_DECLARE_METATYPE(qbs::Internal::FileInfoExtension *)

#include "fileinfoextension.moc"
<|endoftext|>


<commit_before>#include <am/vsynonym/QueryNormalize.h>
QueryNormalize::QueryNormalize()
{
    count_ = 0;
    filePath_ = "./QUERYNORMALIZE";
    keyStr_ = new string[MAX_NORMALIZE_SIZE];
    valueStr_ = new string[MAX_NORMALIZE_SIZE];
    keyString_ = "";
}

QueryNormalize::~QueryNormalize()
{
    delete [] keyStr_;
    delete [] valueStr_;
}

bool QueryNormalize::query_Normalize(string &str)
{
    stanrd_raw(str);
    if(str.length() < 3)
        return false;
    string firstthree = str.substr(0, 3);
    if(keyString_.find(firstthree) == string::npos)
    {
        return true;
    }
    else
    {
        string tmp = "";
        uint32_t i, pos;//uint32_t
        for(i = 0; i < count_; i++)
        {
            if(str.find(keyStr_[i]) == 0)
            {
                tmp.append(keyStr_[i]);
                if(tmp.length() == str.length())
                    return true;
                tmp.append(" ");
                break;
            }
        }
        pos = keyStr_[i].length();
        while(str[pos] == ' ')
            pos++;
        string nextpart = str.substr(pos);
        uint32_t len = nextpart.length();
        uint32_t size;
        if( len < MAX_TYPE_LENGTH)
            size = len;
        else
            size = MAX_TYPE_LENGTH;
        uint32_t j;
        for(j = size; j > 0; j--)
        {
            string tmpstr = nextpart.substr(0, j);
            if(isTypeString(valueStr_[i], tmpstr))
            {
                tmp.append(tmpstr);
                if(tmp.length() != str.length() + 1)
                    tmp.append(" ");
                break;
            }
        }
        while(nextpart[j] == ' ')
            j++;
        tmp.append(nextpart.substr(j));
        str = tmp;
    }
    return true;
}

bool QueryNormalize::load(string nameFile)
{
    filePath_ = nameFile;
    fstream in,out;
    const char* path = filePath_.c_str();
    in.open(path, ios::in);
    string strline;
    while(!in.eof())
    {
        getline(in, strline);
        if(strline[0] != '#')
        {
            if(!build(strline));
               // cout<<"wrong at:"<<strline<<endl;
        }
    }
    in.close();
    buildkeystring();
    return true;
}

bool QueryNormalize::build(string& str)
{
    uint32_t len;
    if((len = str.find_first_of('#')) == string::npos)
        return false;
    keyStr_[count_] = str.substr(0, len);
    valueStr_[count_] = str.substr(len + 1);
    count_++;
    return true;
}

void QueryNormalize::buildkeystring()
{
    for(uint32_t i = 0; i < count_; i++)
    {
        string str = keyStr_[i].substr(0, 3);
        keyString_.append(str);
        keyString_.append("#");
    }
}

bool QueryNormalize::isTypeString(const string& valuestring, const string& type)
{
    uint32_t pos = 0;
    uint32_t valuelen = valuestring.length();
    uint32_t i = 0;
    while(i < valuelen)
    {
        if(valuestring[i] != '#')
            i++;
        else
        {
            string subtype = valuestring.substr(pos, i - pos);
            if(subtype == type)
                return true;
            pos = i + 1;
            i++;
        }
    }
    return false;
}

void QueryNormalize::stanrd_raw(string& str)
{
    transform(str.begin(), str.end(), str.begin(), ::tolower);
    uint32_t len = str.length();
    char * c = new char[len];
    uint32_t k = 0;
    uint32_t i = 0;
    while(str[i] == ' ')
        i++;
    while(str[len - 1] == ' ')
        len--;
    for(; i < len; i++)
    {
        if(str[i] == ' ')
        {
            if(str[i - 1] != ' ')
            {
                c[k] = str[i];
                k++;
            }
        }
        else
        {
            c[k] = str[i];
            k++;
        }
    }
    string s(c,k);
    str = s;
}

<commit_msg>fixed<commit_after>#include <am/vsynonym/QueryNormalize.h>
QueryNormalize::QueryNormalize()
{
    count_ = 0;
    filePath_ = "./QUERYNORMALIZE";
    keyStr_ = new string[MAX_NORMALIZE_SIZE];
    valueStr_ = new string[MAX_NORMALIZE_SIZE];
    keyString_ = "";
}

QueryNormalize::~QueryNormalize()
{
    delete [] keyStr_;
    delete [] valueStr_;
}

bool QueryNormalize::query_Normalize(string &str)
{
    if(count_ == 0)
	return false;
    stanrd_raw(str);
    if(str.length() < 3)
        return false;
    string firstthree = str.substr(0, 3);
    if(keyString_.find(firstthree) == string::npos)
    {
        return true;
    }
    else
    {
        string tmp = "";
        uint32_t i, pos;//uint32_t
        for(i = 0; i < count_; i++)
        {
            if(str.find(keyStr_[i]) == 0)
            {
                tmp.append(keyStr_[i]);
                if(tmp.length() == str.length())
                    return true;
                tmp.append(" ");
                break;
            }
        }
        pos = keyStr_[i].length();
        while(str[pos] == ' ')
            pos++;
        string nextpart = str.substr(pos);
        uint32_t len = nextpart.length();
        uint32_t size;
        if( len < MAX_TYPE_LENGTH)
            size = len;
        else
            size = MAX_TYPE_LENGTH;
        uint32_t j;
        for(j = size; j > 0; j--)
        {
            string tmpstr = nextpart.substr(0, j);
            if(isTypeString(valueStr_[i], tmpstr))
            {
                tmp.append(tmpstr);
                if(tmp.length() != str.length() + 1)
                    tmp.append(" ");
                break;
            }
        }
        while(nextpart[j] == ' ')
            j++;
        tmp.append(nextpart.substr(j));
        str = tmp;
    }
    return true;
}

bool QueryNormalize::load(string nameFile)
{
    filePath_ = nameFile;
    fstream in,out;
    const char* path = filePath_.c_str();
    in.open(path, ios::in);
    string strline;
    if(in.good())
    {
	while(!in.eof())
        {
            getline(in, strline);
            if(strline[0] != '#')
            {
                 if(!build(strline));
            }
        }
    }
    else
    {
        return false;
    }
    in.close();
    buildkeystring();
    return true;
}

bool QueryNormalize::build(string& str)
{
    uint32_t len;
    if((len = str.find_first_of('#')) == string::npos)
        return false;
    keyStr_[count_] = str.substr(0, len);
    valueStr_[count_] = str.substr(len + 1);
    count_++;
    return true;
}

void QueryNormalize::buildkeystring()
{
    for(uint32_t i = 0; i < count_; i++)
    {
        string str = keyStr_[i].substr(0, 3);
        keyString_.append(str);
        keyString_.append("#");
    }
}

bool QueryNormalize::isTypeString(const string& valuestring, const string& type)
{
    uint32_t pos = 0;
    uint32_t valuelen = valuestring.length();
    uint32_t i = 0;
    while(i < valuelen)
    {
        if(valuestring[i] != '#')
            i++;
        else
        {
            string subtype = valuestring.substr(pos, i - pos);
            if(subtype == type)
                return true;
            pos = i + 1;
            i++;
        }
    }
    return false;
}

void QueryNormalize::stanrd_raw(string& str)
{
    transform(str.begin(), str.end(), str.begin(), ::tolower);
    uint32_t len = str.length();
    char * c = new char[len];
    uint32_t k = 0;
    uint32_t i = 0;
    while(str[i] == ' ')
        i++;
    while(str[len - 1] == ' ')
        len--;
    for(; i < len; i++)
    {
        if(str[i] == ' ')
        {
            if(str[i - 1] != ' ')
            {
                c[k] = str[i];
                k++;
            }
        }
        else
        {
            c[k] = str[i];
            k++;
        }
    }
    string s(c,k);
    str = s;
}

<|endoftext|>