<commit_before>/*************************************************************************
 *
 *  $RCSfile: serviceinfohelper.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: jb $ $Date: 2002-12-06 13:07:48 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "serviceinfohelper.hxx"

namespace configmgr
{
// ---------------------------------------------------------------------------

    sal_Int32 ServiceInfoHelper::countServices( ) const
    {
        if (m_info == 0)
            return 0;

        sal_Int32 nCount = 0;
        if (AsciiServiceName const* p= m_info->registeredServiceNames)
        {
            while (*p != 0)
            {
                ++nCount;
                ++p;
            }
        }
        if (AsciiServiceName const* p= m_info->additionalServiceNames)
        {
            while (*p != 0)
            {
                ++nCount;
                ++p;
            }
        }

        return nCount;
    }
// ---------------------------------------------------------------------------

    OUString ServiceInfoHelper::getImplementationName( ) const
        throw(uno::RuntimeException)
    {
        AsciiServiceName p= m_info ? m_info->implementationName : 0;

        return p ? OUString::createFromAscii(p) : OUString();
    }
// ---------------------------------------------------------------------------

    sal_Bool ServiceInfoHelper::supportsService( OUString const & ServiceName ) const
        throw(uno::RuntimeException)
    {
        if (m_info == 0)
            return false;

        if (AsciiServiceName const* p= m_info->registeredServiceNames)
        {
            while (*p != 0)
            {
                if (ServiceName.equalsAscii(*p))
                    return true;
                ++p;
            }
        }
        if (AsciiServiceName const* p= m_info->additionalServiceNames)
        {
            while (*p != 0)
            {
                if (ServiceName.equalsAscii(*p))
                    return true;
                ++p;
            }
        }

        return false;
    }
// ---------------------------------------------------------------------------

    uno::Sequence< OUString > ServiceInfoHelper::getSupportedServiceNames( ) const
        throw(uno::RuntimeException)
    {
        sal_Int32 const nCount = countServices();

        uno::Sequence< OUString > aServices( nCount );

        if (nCount)
        {
            OSL_ASSERT(m_info);
            sal_Int32 i = 0;
            if (AsciiServiceName const* p= m_info->registeredServiceNames)
            {
                while (*p != 0)
                {
                    aServices[i++] = OUString::createFromAscii(*p++);
                }
            }
            if (AsciiServiceName const* p= m_info->additionalServiceNames)
            {
                while (*p != 0)
                {
                    aServices[i++] = OUString::createFromAscii(*p++);
                }
            }
            OSL_ASSERT( i == nCount );
        }

        return aServices;
    }
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------

    sal_Int32 ServiceRegistrationHelper::countServices( ) const
    {
        if (m_info == 0)
            return 0;

        sal_Int32 nCount = 0;
        if (AsciiServiceName const* p= m_info->registeredServiceNames)
        {
            while (*p != 0)
            {
                ++nCount;
                ++p;
            }
        }

        return nCount;
    }
// ---------------------------------------------------------------------------

    OUString ServiceRegistrationHelper::getImplementationName( ) const
        throw(uno::RuntimeException)
    {
        AsciiServiceName p= m_info ? m_info->implementationName : 0;

        return p ? OUString::createFromAscii(p) : OUString();
    }
// ---------------------------------------------------------------------------

    uno::Sequence< OUString > ServiceRegistrationHelper::getRegisteredServiceNames( ) const
        throw(uno::RuntimeException)
    {
        sal_Int32 const nCount = countServices();

        uno::Sequence< OUString > aServices( nCount );

        if (nCount)
        {
            OSL_ASSERT(m_info);
            sal_Int32 i = 0;
            if (AsciiServiceName const* p= m_info->registeredServiceNames)
            {
                while (*p != 0)
                {
                    aServices[i++] = OUString::createFromAscii(*p++);
                }
            }
            OSL_ASSERT( i == nCount );
        }

        return aServices;
    }
// ---------------------------------------------------------------------------
} // namespace config

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.216); FILE MERGED 2005/09/05 17:04:59 rt 1.2.216.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: serviceinfohelper.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 04:12:42 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "serviceinfohelper.hxx"

namespace configmgr
{
// ---------------------------------------------------------------------------

    sal_Int32 ServiceInfoHelper::countServices( ) const
    {
        if (m_info == 0)
            return 0;

        sal_Int32 nCount = 0;
        if (AsciiServiceName const* p= m_info->registeredServiceNames)
        {
            while (*p != 0)
            {
                ++nCount;
                ++p;
            }
        }
        if (AsciiServiceName const* p= m_info->additionalServiceNames)
        {
            while (*p != 0)
            {
                ++nCount;
                ++p;
            }
        }

        return nCount;
    }
// ---------------------------------------------------------------------------

    OUString ServiceInfoHelper::getImplementationName( ) const
        throw(uno::RuntimeException)
    {
        AsciiServiceName p= m_info ? m_info->implementationName : 0;

        return p ? OUString::createFromAscii(p) : OUString();
    }
// ---------------------------------------------------------------------------

    sal_Bool ServiceInfoHelper::supportsService( OUString const & ServiceName ) const
        throw(uno::RuntimeException)
    {
        if (m_info == 0)
            return false;

        if (AsciiServiceName const* p= m_info->registeredServiceNames)
        {
            while (*p != 0)
            {
                if (ServiceName.equalsAscii(*p))
                    return true;
                ++p;
            }
        }
        if (AsciiServiceName const* p= m_info->additionalServiceNames)
        {
            while (*p != 0)
            {
                if (ServiceName.equalsAscii(*p))
                    return true;
                ++p;
            }
        }

        return false;
    }
// ---------------------------------------------------------------------------

    uno::Sequence< OUString > ServiceInfoHelper::getSupportedServiceNames( ) const
        throw(uno::RuntimeException)
    {
        sal_Int32 const nCount = countServices();

        uno::Sequence< OUString > aServices( nCount );

        if (nCount)
        {
            OSL_ASSERT(m_info);
            sal_Int32 i = 0;
            if (AsciiServiceName const* p= m_info->registeredServiceNames)
            {
                while (*p != 0)
                {
                    aServices[i++] = OUString::createFromAscii(*p++);
                }
            }
            if (AsciiServiceName const* p= m_info->additionalServiceNames)
            {
                while (*p != 0)
                {
                    aServices[i++] = OUString::createFromAscii(*p++);
                }
            }
            OSL_ASSERT( i == nCount );
        }

        return aServices;
    }
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------

    sal_Int32 ServiceRegistrationHelper::countServices( ) const
    {
        if (m_info == 0)
            return 0;

        sal_Int32 nCount = 0;
        if (AsciiServiceName const* p= m_info->registeredServiceNames)
        {
            while (*p != 0)
            {
                ++nCount;
                ++p;
            }
        }

        return nCount;
    }
// ---------------------------------------------------------------------------

    OUString ServiceRegistrationHelper::getImplementationName( ) const
        throw(uno::RuntimeException)
    {
        AsciiServiceName p= m_info ? m_info->implementationName : 0;

        return p ? OUString::createFromAscii(p) : OUString();
    }
// ---------------------------------------------------------------------------

    uno::Sequence< OUString > ServiceRegistrationHelper::getRegisteredServiceNames( ) const
        throw(uno::RuntimeException)
    {
        sal_Int32 const nCount = countServices();

        uno::Sequence< OUString > aServices( nCount );

        if (nCount)
        {
            OSL_ASSERT(m_info);
            sal_Int32 i = 0;
            if (AsciiServiceName const* p= m_info->registeredServiceNames)
            {
                while (*p != 0)
                {
                    aServices[i++] = OUString::createFromAscii(*p++);
                }
            }
            OSL_ASSERT( i == nCount );
        }

        return aServices;
    }
// ---------------------------------------------------------------------------
} // namespace config

<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/utf_string_conversions.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test_utils.h"
#include "content/shell/shell.h"
#include "content/test/content_browser_test.h"
#include "content/test/content_browser_test_utils.h"
#include "net/test/test_server.h"

#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif

namespace content {

class WebrtcBrowserTest: public ContentBrowserTest {
 public:
  WebrtcBrowserTest() {}
  virtual ~WebrtcBrowserTest() {}

  virtual void SetUpOnMainThread() OVERRIDE {
    // We need fake devices in this test since we want to run on naked VMs. We
    // assume this switch is set by default in content_browsertests.
    ASSERT_TRUE(CommandLine::ForCurrentProcess()->HasSwitch(
        switches::kUseFakeDeviceForMediaStream));

    ASSERT_TRUE(test_server()->Start());
  }
 protected:
  bool ExecuteJavascript(const std::string& javascript) {
    return ExecuteScript(shell()->web_contents(), javascript);
  }

  void ExpectTitle(const std::string& expected_title) const {
    string16 expected_title16(ASCIIToUTF16(expected_title));
    TitleWatcher title_watcher(shell()->web_contents(), expected_title16);
    EXPECT_EQ(expected_title16, title_watcher.WaitAndGetTitle());
  }
};

// These tests will all make a getUserMedia call with different constraints and
// see that the success callback is called. If the error callback is called or
// none of the callbacks are called the tests will simply time out and fail.
IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, GetVideoStreamAndStop) {
  GURL url(test_server()->GetURL("files/media/getusermedia_and_stop.html"));
  NavigateToURL(shell(), url);

  EXPECT_TRUE(ExecuteJavascript("getUserMedia({video: true});"));

  ExpectTitle("OK");
}

IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, GetAudioAndVideoStreamAndStop) {
  GURL url(test_server()->GetURL("files/media/getusermedia_and_stop.html"));
  NavigateToURL(shell(), url);

  EXPECT_TRUE(ExecuteJavascript("getUserMedia({video: true, audio: true});"));

  ExpectTitle("OK");
}

// These tests will make a complete PeerConnection-based call and verify that
// video is playing for the call.
IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanSetupVideoCall) {
  GURL url(test_server()->GetURL("files/media/peerconnection-call.html"));
  NavigateToURL(shell(), url);

  EXPECT_TRUE(ExecuteJavascript("call({video: true});"));
  ExpectTitle("OK");
}

IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanSetupAudioAndVideoCall) {
  GURL url(test_server()->GetURL("files/media/peerconnection-call.html"));
  NavigateToURL(shell(), url);

  EXPECT_TRUE(ExecuteJavascript("call({video: true, audio: true});"));
  ExpectTitle("OK");
}

IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, MANUAL_CanSetupCallAndSendDtmf) {
  GURL url(test_server()->GetURL("files/media/peerconnection-call.html"));
  NavigateToURL(shell(), url);

  EXPECT_TRUE(
      ExecuteJavascript("callAndSendDtmf('123,abc');"));
}

IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest,
                       CanMakeEmptyCallThenAddStreamsAndRenegotiate) {
  GURL url(test_server()->GetURL("files/media/peerconnection-call.html"));
  NavigateToURL(shell(), url);

  const char* kJavascript =
      "makeEmptyCallThenAddOneStreamAndRenegotiate("
      "{video: true, audio: true});";
  EXPECT_TRUE(ExecuteJavascript(kJavascript));
  ExpectTitle("OK");
}

// This test will make a complete PeerConnection-based call but remove the
// MSID and bundle attribute from the initial offer to verify that
// video is playing for the call even if the initiating client don't support
// MSID. http://tools.ietf.org/html/draft-alvestrand-rtcweb-msid-02
IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest,
                       CanSetupAudioAndVideoCallWithoutMsidAndBundle) {
  GURL url(test_server()->GetURL("files/media/peerconnection-call.html"));
  NavigateToURL(shell(), url);

  EXPECT_TRUE(ExecuteJavascript("callWithoutMsidAndBundle();"));
  ExpectTitle("OK");
}

// This test will make a PeerConnection-based call and test an unreliable text
// dataChannel.
IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataOnly) {
  GURL url(test_server()->GetURL("files/media/peerconnection-call.html"));
  NavigateToURL(shell(), url);

  EXPECT_TRUE(ExecuteJavascript("callWithDataOnly();"));
  ExpectTitle("OK");
}

// This test will make a PeerConnection-based call and test an unreliable text
// dataChannel and audio and video tracks.
IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataAndMedia) {
  GURL url(test_server()->GetURL("files/media/peerconnection-call.html"));
  NavigateToURL(shell(), url);

  EXPECT_TRUE(ExecuteJavascript("callWithDataAndMedia();"));
  ExpectTitle("OK");
}

// This test will make a PeerConnection-based call and test an unreliable text
// dataChannel and later add an audio and video track.
IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataAndLaterAddMedia) {
  GURL url(test_server()->GetURL("files/media/peerconnection-call.html"));
  NavigateToURL(shell(), url);

  EXPECT_TRUE(ExecuteJavascript("callWithDataAndLaterAddMedia();"));
  ExpectTitle("OK");
}

}  // namespace content

<commit_msg>Disable WebrtcBrowserTest.CallWithDataAndLaterAddMedia test.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/utf_string_conversions.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test_utils.h"
#include "content/shell/shell.h"
#include "content/test/content_browser_test.h"
#include "content/test/content_browser_test_utils.h"
#include "net/test/test_server.h"

#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif

namespace content {

class WebrtcBrowserTest: public ContentBrowserTest {
 public:
  WebrtcBrowserTest() {}
  virtual ~WebrtcBrowserTest() {}

  virtual void SetUpOnMainThread() OVERRIDE {
    // We need fake devices in this test since we want to run on naked VMs. We
    // assume this switch is set by default in content_browsertests.
    ASSERT_TRUE(CommandLine::ForCurrentProcess()->HasSwitch(
        switches::kUseFakeDeviceForMediaStream));

    ASSERT_TRUE(test_server()->Start());
  }
 protected:
  bool ExecuteJavascript(const std::string& javascript) {
    return ExecuteScript(shell()->web_contents(), javascript);
  }

  void ExpectTitle(const std::string& expected_title) const {
    string16 expected_title16(ASCIIToUTF16(expected_title));
    TitleWatcher title_watcher(shell()->web_contents(), expected_title16);
    EXPECT_EQ(expected_title16, title_watcher.WaitAndGetTitle());
  }
};

// These tests will all make a getUserMedia call with different constraints and
// see that the success callback is called. If the error callback is called or
// none of the callbacks are called the tests will simply time out and fail.
IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, GetVideoStreamAndStop) {
  GURL url(test_server()->GetURL("files/media/getusermedia_and_stop.html"));
  NavigateToURL(shell(), url);

  EXPECT_TRUE(ExecuteJavascript("getUserMedia({video: true});"));

  ExpectTitle("OK");
}

IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, GetAudioAndVideoStreamAndStop) {
  GURL url(test_server()->GetURL("files/media/getusermedia_and_stop.html"));
  NavigateToURL(shell(), url);

  EXPECT_TRUE(ExecuteJavascript("getUserMedia({video: true, audio: true});"));

  ExpectTitle("OK");
}

// These tests will make a complete PeerConnection-based call and verify that
// video is playing for the call.
IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanSetupVideoCall) {
  GURL url(test_server()->GetURL("files/media/peerconnection-call.html"));
  NavigateToURL(shell(), url);

  EXPECT_TRUE(ExecuteJavascript("call({video: true});"));
  ExpectTitle("OK");
}

IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanSetupAudioAndVideoCall) {
  GURL url(test_server()->GetURL("files/media/peerconnection-call.html"));
  NavigateToURL(shell(), url);

  EXPECT_TRUE(ExecuteJavascript("call({video: true, audio: true});"));
  ExpectTitle("OK");
}

IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, MANUAL_CanSetupCallAndSendDtmf) {
  GURL url(test_server()->GetURL("files/media/peerconnection-call.html"));
  NavigateToURL(shell(), url);

  EXPECT_TRUE(
      ExecuteJavascript("callAndSendDtmf('123,abc');"));
}

IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest,
                       CanMakeEmptyCallThenAddStreamsAndRenegotiate) {
  GURL url(test_server()->GetURL("files/media/peerconnection-call.html"));
  NavigateToURL(shell(), url);

  const char* kJavascript =
      "makeEmptyCallThenAddOneStreamAndRenegotiate("
      "{video: true, audio: true});";
  EXPECT_TRUE(ExecuteJavascript(kJavascript));
  ExpectTitle("OK");
}

// This test will make a complete PeerConnection-based call but remove the
// MSID and bundle attribute from the initial offer to verify that
// video is playing for the call even if the initiating client don't support
// MSID. http://tools.ietf.org/html/draft-alvestrand-rtcweb-msid-02
IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest,
                       CanSetupAudioAndVideoCallWithoutMsidAndBundle) {
  GURL url(test_server()->GetURL("files/media/peerconnection-call.html"));
  NavigateToURL(shell(), url);

  EXPECT_TRUE(ExecuteJavascript("callWithoutMsidAndBundle();"));
  ExpectTitle("OK");
}

// This test will make a PeerConnection-based call and test an unreliable text
// dataChannel.
IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataOnly) {
  GURL url(test_server()->GetURL("files/media/peerconnection-call.html"));
  NavigateToURL(shell(), url);

  EXPECT_TRUE(ExecuteJavascript("callWithDataOnly();"));
  ExpectTitle("OK");
}

// This test will make a PeerConnection-based call and test an unreliable text
// dataChannel and audio and video tracks.
IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataAndMedia) {
  GURL url(test_server()->GetURL("files/media/peerconnection-call.html"));
  NavigateToURL(shell(), url);

  EXPECT_TRUE(ExecuteJavascript("callWithDataAndMedia();"));
  ExpectTitle("OK");
}

// This test will make a PeerConnection-based call and test an unreliable text
// dataChannel and later add an audio and video track.
// TODO(perkj): Fix flakiness. See: http://crbug.com/227409
IN_PROC_BROWSER_TEST_F(WebrtcBrowserTest,
                       DISABLED_CallWithDataAndLaterAddMedia) {
  GURL url(test_server()->GetURL("files/media/peerconnection-call.html"));
  NavigateToURL(shell(), url);

  EXPECT_TRUE(ExecuteJavascript("callWithDataAndLaterAddMedia();"));
  ExpectTitle("OK");
}

}  // namespace content

<|endoftext|>


<commit_before>
// DCMQI includes
#include "dcmqi/Helper.h"

// DCMTK includes
#include <dcmtk/ofstd/oflist.h>

namespace dcmqi {

  bool Helper::isUndefinedOrPathDoesNotExist(const string &var, const string &humanReadableName) {
    return Helper::isUndefined(var, humanReadableName) || !Helper::pathExists(var);
  }

  bool Helper::isUndefinedOrPathsDoNotExist(vector<string> &var, const string &humanReadableName) {
    return Helper::isUndefined(var, humanReadableName) || !Helper::pathsExist(var);
  }

  bool Helper::pathsExist(const vector<string> &paths) {
    bool allExist = true;
    for(vector<string>::const_iterator iter = paths.begin(); iter != paths.end(); ++iter) {
      if (!Helper::pathExists(*iter)){
        allExist = false;
      }
    }
    return allExist;
  }

  bool Helper::pathExists(const string &path) {
    struct stat buffer;
    if (stat (path.c_str(), &buffer) != 0) {
      cerr << "Error: " << path << " not found!" << endl;
      return false;
    } else {
      return true;
    }
  }

  string Helper::getFileExtensionFromType(const string& type) {
    string extension = ".nrrd";
    if (type == "nii" || type == "nifti")
      extension = ".nii.gz";
    else if (type == "mhd")
      extension = ".mhd";
    else if (type == "mha")
      extension = ".mha";
    else if (type == "img")
      extension = ".img";
    else if (type == "hdr")
      extension = ".hdr";
    else if (type == "nrrd")
      extension = ".nrrd";
    return extension;
  }

  vector<string> Helper::getFileListRecursively(string directory) {
    OFList<OFString> fileList;
    vector<string> dicomImageFiles;
#if _WIN32
    replace(directory.begin(), directory.end(), '/', PATH_SEPARATOR);
#endif
    cout << "Searching recursively " << directory << " for DICOM files" << endl;
    if(OFStandard::searchDirectoryRecursively(directory.c_str(), fileList)) {
      for(OFListIterator(OFString) fileListIterator=fileList.begin(); fileListIterator!=fileList.end(); fileListIterator++) {
        dicomImageFiles.push_back((*fileListIterator).c_str());
      }
    }
    return dicomImageFiles;
  }

  vector<DcmDataset*> Helper::loadDatasets(const vector<string>& dicomImageFiles) {
    vector<DcmDataset*> dcmDatasets;
    OFString tmp, sopInstanceUID;
    DcmFileFormat* sliceFF = new DcmFileFormat();
    for(size_t dcmFileNumber=0; dcmFileNumber<dicomImageFiles.size(); dcmFileNumber++){
      if(sliceFF->loadFile(dicomImageFiles[dcmFileNumber].c_str()).good()){
        DcmDataset* currentDataset = sliceFF->getAndRemoveDataset();
        if(!currentDataset->tagExistsWithValue(DCM_PixelData)){
          std::cerr << "Source DICOM file does not contain PixelData, skipping: " << std::endl
             << "  >>>   " << dicomImageFiles[dcmFileNumber] << std::endl;
          continue;
        };
        currentDataset->findAndGetOFString(DCM_SOPInstanceUID, sopInstanceUID);
        bool exists = false;
        for(size_t i=0;i<dcmDatasets.size();i++) {
          dcmDatasets[i]->findAndGetOFString(DCM_SOPInstanceUID, tmp);
          if (tmp == sopInstanceUID) {
            cout << dicomImageFiles[dcmFileNumber].c_str() << " with SOPInstanceUID: " << sopInstanceUID
                 << " already exists" << endl;
            exists = true;
            break;
          }
        }
        if (!exists) {
          dcmDatasets.push_back(currentDataset);
        }
      } else {
        cerr << "Failed to read " << dicomImageFiles[dcmFileNumber] << ". Skipping it." << endl;
      }
    }
    delete sliceFF;
    return dcmDatasets;
  }

  string Helper::floatToStr(float f) {
    ostringstream sstream;
    sstream.imbue(std::locale::classic());
    sstream.precision(9);
    sstream << f;
    string f_str = sstream.str();
    cout << "Formatted float (length): " << f_str << "(" << f_str.size() << ")" << endl;
    return sstream.str();
  }

  void Helper::checkValidityOfFirstSrcImage(DcmSegmentation *segdoc) {
    FGInterface &fgInterface = segdoc->getFunctionalGroups();
    bool isPerFrame = false;
    FGDerivationImage *derimgfg = OFstatic_cast(FGDerivationImage*, fgInterface.get(0, DcmFGTypes::EFG_DERIVATIONIMAGE,
                                                                                isPerFrame));
    if(!derimgfg){
      cout << "Debug: No derivation items present in the segmentation dataset" << endl;
    }
    assert(isPerFrame);

    OFVector<DerivationImageItem *> &deritems = derimgfg->getDerivationImageItems();

    OFVector<SourceImageItem *> &srcitems = deritems[0]->getSourceImageItems();
    OFString codeValue;
    if(srcitems.size()>0){
      CodeSequenceMacro &code = srcitems[0]->getPurposeOfReferenceCode();
      if (!code.getCodeValue(codeValue).good()) {
        cout << "Failed to look up purpose of reference code" << endl;
        abort();
      }
    } else {
      cout << "Warning: Source images are not initialized!" << endl;
    }
  }

  void Helper::tokenizeString(string str, vector<string> &tokens, string delimiter) {
    // http://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c
    size_t pos = 0;
    while ((pos = str.find(delimiter)) != string::npos) {
      string token = str.substr(0, pos);
      tokens.push_back(token);
      str.erase(0, pos + delimiter.length());
    }
    tokens.push_back(str);
  };

  void Helper::splitString(string str, string &head, string &tail, string delimiter) {
    // http://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c
    size_t pos = str.find(delimiter);
    if (pos != string::npos) {
      head = str.substr(0, pos);
      tail = str.substr(pos + delimiter.length(), str.length() - 1);
    }
  };

  string Helper::toString(const unsigned int& value) {
    ostringstream oss;
    oss << value;
    return oss.str();
  }

  CodeSequenceMacro Helper::stringToCodeSequenceMacro(string str) {
    string tail, code, designator, meaning;
    splitString(str, code, tail, ",");
    splitString(tail, designator, meaning, ",");
    return CodeSequenceMacro(code.c_str(), designator.c_str(), meaning.c_str());
  }

  DSRCodedEntryValue Helper::stringToDSRCodedEntryValue(string str) {
    string tail, code, designator, meaning;
    splitString(str, code, tail, ",");
    splitString(tail, designator, meaning, ",");
    return DSRCodedEntryValue(code.c_str(), designator.c_str(), meaning.c_str());
  }

  CodeSequenceMacro* Helper::createNewCodeSequence(const string& code, const string& designator, const string& meaning) {
    if (code.empty() || designator.empty() || meaning.empty())
      throw CodeSequenceValueException();
    return new CodeSequenceMacro(code.c_str(), designator.c_str(), meaning.c_str());
  }

}
<commit_msg>CI: remove print<commit_after>
// DCMQI includes
#include "dcmqi/Helper.h"

// DCMTK includes
#include <dcmtk/ofstd/oflist.h>

namespace dcmqi {

  bool Helper::isUndefinedOrPathDoesNotExist(const string &var, const string &humanReadableName) {
    return Helper::isUndefined(var, humanReadableName) || !Helper::pathExists(var);
  }

  bool Helper::isUndefinedOrPathsDoNotExist(vector<string> &var, const string &humanReadableName) {
    return Helper::isUndefined(var, humanReadableName) || !Helper::pathsExist(var);
  }

  bool Helper::pathsExist(const vector<string> &paths) {
    bool allExist = true;
    for(vector<string>::const_iterator iter = paths.begin(); iter != paths.end(); ++iter) {
      if (!Helper::pathExists(*iter)){
        allExist = false;
      }
    }
    return allExist;
  }

  bool Helper::pathExists(const string &path) {
    struct stat buffer;
    if (stat (path.c_str(), &buffer) != 0) {
      cerr << "Error: " << path << " not found!" << endl;
      return false;
    } else {
      return true;
    }
  }

  string Helper::getFileExtensionFromType(const string& type) {
    string extension = ".nrrd";
    if (type == "nii" || type == "nifti")
      extension = ".nii.gz";
    else if (type == "mhd")
      extension = ".mhd";
    else if (type == "mha")
      extension = ".mha";
    else if (type == "img")
      extension = ".img";
    else if (type == "hdr")
      extension = ".hdr";
    else if (type == "nrrd")
      extension = ".nrrd";
    return extension;
  }

  vector<string> Helper::getFileListRecursively(string directory) {
    OFList<OFString> fileList;
    vector<string> dicomImageFiles;
#if _WIN32
    replace(directory.begin(), directory.end(), '/', PATH_SEPARATOR);
#endif
    cout << "Searching recursively " << directory << " for DICOM files" << endl;
    if(OFStandard::searchDirectoryRecursively(directory.c_str(), fileList)) {
      for(OFListIterator(OFString) fileListIterator=fileList.begin(); fileListIterator!=fileList.end(); fileListIterator++) {
        dicomImageFiles.push_back((*fileListIterator).c_str());
      }
    }
    return dicomImageFiles;
  }

  vector<DcmDataset*> Helper::loadDatasets(const vector<string>& dicomImageFiles) {
    vector<DcmDataset*> dcmDatasets;
    OFString tmp, sopInstanceUID;
    DcmFileFormat* sliceFF = new DcmFileFormat();
    for(size_t dcmFileNumber=0; dcmFileNumber<dicomImageFiles.size(); dcmFileNumber++){
      if(sliceFF->loadFile(dicomImageFiles[dcmFileNumber].c_str()).good()){
        DcmDataset* currentDataset = sliceFF->getAndRemoveDataset();
        if(!currentDataset->tagExistsWithValue(DCM_PixelData)){
          std::cerr << "Source DICOM file does not contain PixelData, skipping: " << std::endl
             << "  >>>   " << dicomImageFiles[dcmFileNumber] << std::endl;
          continue;
        };
        currentDataset->findAndGetOFString(DCM_SOPInstanceUID, sopInstanceUID);
        bool exists = false;
        for(size_t i=0;i<dcmDatasets.size();i++) {
          dcmDatasets[i]->findAndGetOFString(DCM_SOPInstanceUID, tmp);
          if (tmp == sopInstanceUID) {
            cout << dicomImageFiles[dcmFileNumber].c_str() << " with SOPInstanceUID: " << sopInstanceUID
                 << " already exists" << endl;
            exists = true;
            break;
          }
        }
        if (!exists) {
          dcmDatasets.push_back(currentDataset);
        }
      } else {
        cerr << "Failed to read " << dicomImageFiles[dcmFileNumber] << ". Skipping it." << endl;
      }
    }
    delete sliceFF;
    return dcmDatasets;
  }

  string Helper::floatToStr(float f) {
    ostringstream sstream;
    sstream.imbue(std::locale::classic());
    sstream.precision(9);
    sstream << f;
    //string f_str = sstream.str();
    //cout << "Formatted float (length): " << f_str << "(" << f_str.size() << ")" << endl;
    return sstream.str();
  }

  void Helper::checkValidityOfFirstSrcImage(DcmSegmentation *segdoc) {
    FGInterface &fgInterface = segdoc->getFunctionalGroups();
    bool isPerFrame = false;
    FGDerivationImage *derimgfg = OFstatic_cast(FGDerivationImage*, fgInterface.get(0, DcmFGTypes::EFG_DERIVATIONIMAGE,
                                                                                isPerFrame));
    if(!derimgfg){
      cout << "Debug: No derivation items present in the segmentation dataset" << endl;
    }
    assert(isPerFrame);

    OFVector<DerivationImageItem *> &deritems = derimgfg->getDerivationImageItems();

    OFVector<SourceImageItem *> &srcitems = deritems[0]->getSourceImageItems();
    OFString codeValue;
    if(srcitems.size()>0){
      CodeSequenceMacro &code = srcitems[0]->getPurposeOfReferenceCode();
      if (!code.getCodeValue(codeValue).good()) {
        cout << "Failed to look up purpose of reference code" << endl;
        abort();
      }
    } else {
      cout << "Warning: Source images are not initialized!" << endl;
    }
  }

  void Helper::tokenizeString(string str, vector<string> &tokens, string delimiter) {
    // http://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c
    size_t pos = 0;
    while ((pos = str.find(delimiter)) != string::npos) {
      string token = str.substr(0, pos);
      tokens.push_back(token);
      str.erase(0, pos + delimiter.length());
    }
    tokens.push_back(str);
  };

  void Helper::splitString(string str, string &head, string &tail, string delimiter) {
    // http://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c
    size_t pos = str.find(delimiter);
    if (pos != string::npos) {
      head = str.substr(0, pos);
      tail = str.substr(pos + delimiter.length(), str.length() - 1);
    }
  };

  string Helper::toString(const unsigned int& value) {
    ostringstream oss;
    oss << value;
    return oss.str();
  }

  CodeSequenceMacro Helper::stringToCodeSequenceMacro(string str) {
    string tail, code, designator, meaning;
    splitString(str, code, tail, ",");
    splitString(tail, designator, meaning, ",");
    return CodeSequenceMacro(code.c_str(), designator.c_str(), meaning.c_str());
  }

  DSRCodedEntryValue Helper::stringToDSRCodedEntryValue(string str) {
    string tail, code, designator, meaning;
    splitString(str, code, tail, ",");
    splitString(tail, designator, meaning, ",");
    return DSRCodedEntryValue(code.c_str(), designator.c_str(), meaning.c_str());
  }

  CodeSequenceMacro* Helper::createNewCodeSequence(const string& code, const string& designator, const string& meaning) {
    if (code.empty() || designator.empty() || meaning.empty())
      throw CodeSequenceValueException();
    return new CodeSequenceMacro(code.c_str(), designator.c_str(), meaning.c_str());
  }

}
<|endoftext|>


<commit_before>/*
 *MIT License
 *
 *  Copyright (c) 2017 Banuprathap Anandan
 *
 *  AUTHOR : BANUPRATHAP ANANDAN
 *  AFFILIATION : UNIVERSITY OF MARYLAND, MARYLAND ROBOTICS CENTER
 *  EMAIL : BPRATHAP@UMD.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.
 *
 *
 *
 *  Project: Frontier Explorer for Turtlebot
 *
 *
 */

/**
 * @file main.cpp
 * @brief
 * @author Banuprathap Anandan
 * @date   04/26/2017
 */
#include "ros/ros.h"
#include "ros/console.h"
#include "geometry_msgs/Twist.h"
#include "sensor_msgs/LaserScan.h"
#include "nav_msgs/OccupancyGrid.h"

/**
 * @brief      Execution starts here
 *
 * @param[in]  argc  The argc
 * @param      argv  The argv
 *
 * @return     Returns 0 upon successful execution
 */
int main(int argc, char **argv) {
  // Implement me
  return 0;
}
<commit_msg>Class declaration - explorer<commit_after>/*
 *MIT License
 *
 *  Copyright (c) 2017 Banuprathap Anandan
 *
 *  AUTHOR : BANUPRATHAP ANANDAN
 *  AFFILIATION : UNIVERSITY OF MARYLAND, MARYLAND ROBOTICS CENTER
 *  EMAIL : BPRATHAP@UMD.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.
 *
 *
 *
 *  Project: Frontier Explorer for Turtlebot
 *
 *
 */

/**
 * @file main.cpp
 * @brief
 * @author Banuprathap Anandan
 * @date   04/26/2017
 */
#include "ros/ros.h"
#include "ros/console.h"
#include "geometry_msgs/Twist.h"
#include "sensor_msgs/LaserScan.h"
#include "nav_msgs/OccupancyGrid.h"
#include "wavefront_detection.hpp"
/**
 * @brief      Class for exploration task.
 */
class Explorer {
 public:
    /**
     * @brief      Default constructor to initiate publisher and subscriber
     *
     *
     * @param      nh    ROS NodeHandle
     */
    Explorer(ros::NodeHandle& nh);
    /**
     * @brief      Callback function from the map subscriber
     *
     * @param[in]  map   The map
     */
    void mapCallback(const nav_msgs::OccupancyGrid& map);
 protected:
    sensor_msgs::PointCloud frontier_cloud;
    ros::Publisher frontier_pub;
    ros::Subscriber mapSub;
};

/**
 * @brief      Execution starts here
 *
 * @param[in]  argc  The argc
 * @param      argv  The argv
 *
 * @return     Returns 0 upon successful execution
 */
int main(int argc, char **argv) {
  // Implement me
  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <string>

#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>

#include "waveforms/SquareWave.h"

static const std::string VERSION = "1.0";
static const std::string USAGE = ""
"Usage: wfg [-hv]\n"
"       wfg [-0 <duration>] [-1 <duration>] square\n"
"\n"
"Options:\n"
"  -h, --help              Print this menu and exit.\n"
"  -v, --version           Print the program version and exit.\n"
"  -0                      The milliseconds for active low.\n"
"  -1                      The milliseconds for active high.\n"
"\n";

int main(int argc, char **argv)
{
    int opt;
    int optionIndex;
    int lowDuration = 1000000;
    int highDuration = 1000000;
    struct option options[] = {
        { "help", no_argument, NULL, 'h' },
        { "version", no_argument, NULL, 'v' },
        { 0, 0, 0, 0 },
    };

    while (1) {
        opt = getopt_long(argc, argv, "hv0:1:", options, &optionIndex);

        if (opt == -1) {
            break;
        }

        switch (opt) {
        case 'h':
            std::cout << USAGE << std::endl;
            return 0;

        case 'v':
            std::cout << VERSION << std::endl;
            return 0;

        case '0': {
            std::stringstream str(optarg);
            str >> lowDuration;
            break;
        }

        case '1': {
            std::stringstream str(optarg);
            str >> highDuration;
            break;
        }

        case 0:
        case '?':
        default:
            return 1;
        }
    }

    if ((argc - optind) < 1) {
        std::cerr << "No waveform type specified. See -h for usage." << std::endl;
        exit(EXIT_FAILURE);
    }

    std::string waveStr(argv[optind]);

    if (waveStr == "square") {
        SquareWave wave(lowDuration, highDuration);
        wave.SetDuration(5000000);
        wave.Generate();
    }

    return 0;
}
<commit_msg>Added a -t, --timeout option to generate a wave for certain amount of time<commit_after>#include <iostream>
#include <sstream>
#include <string>

#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>

#include "waveforms/SquareWave.h"

static const std::string VERSION = "1.0";
static const std::string USAGE = ""
"Usage: wfg [-hv]\n"
"       wfg [-0 <duration>] [-1 <duration>] square\n"
"\n"
"Options:\n"
"  -h, --help              Print this menu and exit.\n"
"  -v, --version           Print the program version and exit.\n"
"  -t, --timeout           The milliseconds for how long to generate wave.\n"
"  -0                      The milliseconds for active low.\n"
"  -1                      The milliseconds for active high.\n"
"\n";

int main(int argc, char **argv)
{
    int opt;
    int optionIndex;
    int lowDuration = 1000000;
    int highDuration = 1000000;
    int timeout = 0;
    struct option options[] = {
        { "help", no_argument, NULL, 'h' },
        { "version", no_argument, NULL, 'v' },
        { "timeout", required_argument, NULL, 't' },
        { 0, 0, 0, 0 },
    };

    while (1) {
        opt = getopt_long(argc, argv, "hv0:1:t:", options, &optionIndex);

        if (opt == -1) {
            break;
        }

        switch (opt) {
        case 'h':
            std::cout << USAGE << std::endl;
            return 0;

        case 'v':
            std::cout << VERSION << std::endl;
            return 0;

        case 't': {
            std::stringstream str(optarg);
            str >> timeout;
            break;
        }

        case '0': {
            std::stringstream str(optarg);
            str >> lowDuration;
            break;
        }

        case '1': {
            std::stringstream str(optarg);
            str >> highDuration;
            break;
        }

        case 0:
        case '?':
        default:
            return 1;
        }
    }

    if ((argc - optind) < 1) {
        std::cerr << "No waveform type specified. See -h for usage." << std::endl;
        exit(EXIT_FAILURE);
    }

    std::string waveStr(argv[optind]);

    if (waveStr == "square") {
        SquareWave wave(lowDuration, highDuration);
        wave.SetDuration(timeout);
        wave.Generate();
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <Arduino.h>
#include "scheduler.h"

static Scheduler scheduler;
static const int UPDATE_PERIOD_MS = 50;

void setup()
{
	Serial.begin(115200);
	delay(1000);
	Serial.println("Hello world");
    //scheduler.ScheduleFunction(TASK, UPDATE_PERIOD_MS);
}

void loop()
{
    scheduler.Update();
}
<commit_msg>Main prepared for use of scanners<commit_after>#include <Arduino.h>
#include "scheduler.h"
#include "shape_mapping_scanner.h"
#include "defined_area_scanner.h"

static Scheduler scheduler;
static const int UPDATE_PERIOD_MS = 50;
static void AppUpdate(void);

// Scanner objects
// Switch the commented out portions for other type of scanning
static ShapeMappingScanner scanner;
//static DefinedAreaScanner scanner;

void setup()
{
	Serial.begin(115200);
    scheduler.ScheduleFunction(AppUpdate, UPDATE_PERIOD_MS);
    scanner.HardwareSetup();
    delay(1000);
    scanner.SetReferenceInductance();
    scanner.SetHomePosition();
    scanner.SetScanOrigin(0, 150, 40);

    // Uncomment these for use of the DefinedAreaScanner
    // and update parameters if necessary
    //scanner.SetDesiredHorizontalTravelMM(100);
    //scanner.SetDesiredDepthTravelMM(40);
    //scanner.SetDepthScanIncrementMM(5);

}

void loop()
{
    scheduler.Update();
}

static void AppUpdate(void)
{
    scanner.Update(UPDATE_PERIOD_MS);
    if (scanner.isScanComplete())
    {
        Serial.println("Scan complete!");
        while(1);
    }
}
<|endoftext|>


<commit_before>#include <string.h>
#include <fcntl.h>
#include <boost/algorithm/string.hpp>
#include <boost/tokenizer.hpp>
#include <stdlib.h>
#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <vector>

using namespace boost;
using namespace std;

int check_input(string usrString)
{
	if (usrString.find("&&") != string::npos ||
		usrString.find("||") != string::npos ||
		usrString.find(";") != string::npos ||
		usrString.find("#") != string::npos ||
		(usrString.find(">") == string::npos &&
		usrString.find("<") == string::npos &&
		usrString.find("|") == string::npos))
		{
			return 0;
		}
	else
	{
		return 1;
	}
	return -1;
}

bool popv(string usrString, vector<string> &iop, vector<vector<string> > &cmds)
{
	typedef tokenizer<char_separator<char> > tokenizer;
	char_separator<char> sep(" ", "<>|", drop_empty_tokens);
	tokenizer tokens(usrString, sep);
	int cnt = 0;
	bool first = true;
	for (auto it = tokens.begin(); it != tokens.end(); ++it)
	{
		if(*it == "|" || *it == "<")
		{
			first = true;
			iop.push_back(*it);
			++cnt;
			continue;
		}
		else if(*it == ">")
		{
			if(iop.empty())
            {
            	first = true;
            	iop.push_back(*it);
            	++cnt;
            	continue;
            }

			else if (iop.at(iop.size()-1) == ">")
			{
				first = true;
				iop.at(iop.size()-1).append(">");
				continue;
			}
			else
			{
				first = true;
				iop.push_back(*it);
				++cnt;
			}
		}
		else
		{
			if(first)
			{
				first = false;
				vector<string> temp;
				temp.push_back(*it);
				cmds.push_back(temp);
			}
			else
			{
				cmds.at(cnt).push_back(*it);
			}
		}

	}

	//Print check
	/*
	cout << "cmds: ";
	for (size_t i = 0; i < cmds.size(); ++i)
	{
		for(size_t j = 0; j < cmds.at(i).size(); ++j)
		{
			cout << cmds.at(i).at(j) << " ";
		}
	}
	cout << endl;

	cout << "iop: ";
	for (size_t n = 0; n < iop.size(); ++n)
	{
		cout << iop.at(n) << " ";
	}
	cout << endl;
	*/
	return true;
}

//Function that parses a passed in string and executes the command it yields
bool parse_exec(string usrString, int size)
{
	int status;
	char **args = new char*[size+1];
	char *cstr = new char[size+1];
	strcpy(cstr,usrString.c_str());
	char *temp = strtok(cstr, " &|;#");
	int cnt = 0;

	while (temp != 0){
		args[cnt] = temp;
		++cnt;
		temp = strtok(NULL, " &|");
	}
	if (cnt == 0){
		delete[] cstr;
		delete[] args;
		return false;
	}
	args[cnt] = NULL;

	if (!strcmp(args[0],"exit")){
		exit(0);
	}

	int pid = fork();
	if (pid == -1){
		perror("fork");
	}
	else if(pid == 0){
		if (execvp(args[0],args) == -1){
			perror("execvp");
			exit(1);
		}
	}
	else if(pid > 0){
		if(-1 == wait(&status)){
			perror("wait");
		}
	}

	delete[] cstr;
	delete[] args;

	if(WEXITSTATUS(status) == 0){
		return true;
	}
	else{
		return false;
	}
	return false;
}

//Function checks for connectors and returns a number based on which one is found
//Pass in a string, a position integer, and a starting point integer
int check_connect(const string& str, int& pos, int start){
	unsigned found = 0;
	found = str.find_first_of(";&|#",start);
	if (found >= str.size()){	//If not found...
		pos = -1;
		return -1;
	}
	else{
		if (str.at(found) == ';'){
			pos = found;
			return 1;
		}
		else if (str.at(found) == '&'){
			if (str.at(found+1) == '&'){
				pos = found;
				return 2;
			}
			else{
				return check_connect(str,pos,found+1);
			}
		}

		else if (str.at(found) == '|'){
			if (str.at(found+1) == '|'){
				pos = found;
				return 3;
			}
			else{
				return 5;
			}
		}
		else if (str.at(found) == '#'){
			pos = found;
			return 4;
		}
	}
	return -1;
}

void my_close(int fd)
{
	if (-1 == close(fd))
	{
		perror("close");
	}
}
void redirect(int oldf, int newf)
{
	if (oldf != newf)
	{
		if (-1 == dup2(oldf,newf))
		{
			perror("dup2");
		}
		else
		{
			my_close(oldf);
		}
	}
}

void execute(vector<string> cmd, int in, int out)
{
	redirect(in, STDIN_FILENO);
	redirect(out, STDOUT_FILENO);

	int n = cmd.size();
	int i;
	const char **args = new const char*[ n+1 ];
	for (i = 0; i < n; ++i)
	{
		args[i] = cmd.at(i).c_str();
	}
	args[i] = NULL;

	execvp(args[0], (char * const*)args);
	perror("execvp");
	exit(1);
}

void in_redir(vector<string> cmd, string file, int out, int cnt)
{
	my_close(0);
	open(file.c_str(), O_RDWR);
	size_t i;
	const char **args = new const char*[cmd.size()+1];
	for (i = 0; i < cmd.size(); ++i)
	{
		args[i] = cmd.at(i).c_str();
	}
	args[i] = NULL;
	if ( cnt > 0 )
	{
		redirect(out,STDOUT_FILENO);
	}
	if(-1 == execvp(args[0], (char * const*)args))
	{
		perror("execvp");
		exit(1);
	}
}

void out1_redir(vector<string> cmd, string file, int out, int save_out)
{
	int out2;
	if (-1 == (out2 = open(file.c_str(), O_WRONLY | O_CREAT | O_TRUNC)))
	{
		perror("open");
		exit(1);
	}
	size_t i;
	const char **args = new const char*[cmd.size()+1];
	for (i = 0; i < cmd.size(); ++i)
	{
		args[i] = cmd.at(i).c_str();
	}
	args[i] = NULL;

	redirect(out2,STDOUT_FILENO);
	my_close(out2);
	if (-1 == execvp(args[0], (char * const*)args))
	{
		perror("execvp");
		exit(1);
	}
}

int main()
{
	//Get User Info
	string hostname;
	string username = getlogin();
	if(getlogin() == NULL){
		perror("login");
		username = "UNKNOWN";
	}
	char host_temp[64];
	if(gethostname(host_temp,64) == -1){
		perror("hostname");
		hostname = "UNKNOWN";
	}
	else{
		hostname = host_temp;
	}

	while(1){
		//Get User Input
		bool exec_stat = true;		//Execution Status
		int con_stat = 0;			//Connector Status
		int pos = 0;				//Position of Connector
		int start = 0;				//Start position for parse function
		int size = 0;				//Size of user input
		string usrString;			//User Input String
		vector<string> iop;
		vector<vector<string> > cmds;
		cout << username << "@" << hostname << "$ ";
		cin.sync();
		getline(cin,usrString); size = usrString.size();
		if (size == 0){
			continue;
		}

		if (1 == check_input(usrString))
		{
			iop.clear(); cmds.clear();
			popv(usrString,iop,cmds);

			int pipe_cnt = 0;
			for (size_t a = 0; a < iop.size(); ++a)
			{
				if (iop.at(a) == "|")
				{
					++pipe_cnt;
				}
			}

			if(cmds.empty())
			{
				continue;
			}

		/*	int save_out;
			if (-1 == (save_out = dup(STDOUT_FILENO)))
			{
				perror("dup");
				exit(1);
			}  */

			int save_in;
			if ( -1 == (save_in = dup(STDIN_FILENO)))
			{
				perror("dup");
				exit(1);
			}

			pid_t pid;
			int in = STDIN_FILENO;
			size_t i = 0;
			int fd[2];

			if (iop.at(0) == "<")
			{
				if (-1 == pipe(fd))
				{
					perror("pipe");
				}
				if (-1 == (pid = fork()))
				{
					perror("fork");
					exit(1);
				}
				else if (pid == 0)
				{
					my_close(fd[0]);
					in_redir(cmds.at(0),cmds.at(1).at(0),fd[1],pipe_cnt);
				}
				else if (pid > 0)
				{
					wait(0);
					my_close(fd[1]);
					my_close(in);
					in = fd[0];
					i = 2;
				}
			}

			if ((cmds.size() >= 2) && (pipe_cnt > 0))
			{

				for (; i < cmds.size()-1; ++i)
				{

					if (-1 == pipe(fd))
					{
						perror("pipe");
						exit(1);
					}
					else if (-1 == (pid = fork()))
					{
						perror("fork");
						exit(1);
					}
					else if (pid == 0)
					{
						my_close(fd[0]);
						execute(cmds.at(i),in,fd[1]);
						exit(1);
					}
					else if (pid >0)
					{
						wait(0);
						my_close(fd[1]);
						my_close(in);
						in = fd[0];
					}
				}

				if (-1 == (pid = fork()))
				{
					perror("fork");
					exit(1);
				}
				if (pid == 0)
				{
					execute(cmds.at(i),in,STDOUT_FILENO);
					exit(1);
				}

				wait(0);
				my_close(in);
				in = fd[0];
				/*
				else if (iop.at(iop.size()-1) == ">")
				{
					if (-1 == (pid = fork()))
					{
						perror("fork");
						exit(1);
					}
					else if (pid == 0)
					{
						my_close(1);
						size_t sz = cmds.size();
						out1_redir(cmds.at(sz-2),cmds.at(sz-1).at(0),in,save_out);
					}
					else if (pid > 0)
					{
						wait(0);
						my_close(fd[1]);
						my_close(in);
						in = fd[0];
					}
				}
				*/
			}
			dup2(save_in,STDIN_FILENO);
		//	dup2(save_out,STDOUT_FILENO);
			continue;

		}

		else
		{
			//Check Connectors
			while(1){
				exec_stat = false;
				con_stat = check_connect(usrString,pos,start);
				if (con_stat == -1){
					exec_stat = parse_exec(usrString.substr(start),size);
					break;
					//If -1 there are no more connectors in the string so
					//execute and break for more input
				}
				else if (con_stat == 1){
					exec_stat = parse_exec(usrString.substr(start,pos-start), size);
					start = pos + 1;
					continue;
					//Semi-colon encountered so execute and continue with
					//the rest of command line
				}
				else if (con_stat == 2){
					exec_stat = parse_exec(usrString.substr(start,pos-start), size);
					start = pos + 2;
					if (exec_stat == true){
						continue;
					}
					else{
						break;
					}
					//AND connector encountered so execute and check it's exit status
					//If success then continue with command line
					//Else break for more input
				}
				else if (con_stat == 3){
					exec_stat = parse_exec(usrString.substr(start,pos-start), size);
					start = pos + 2;
					if (exec_stat == true){
						break;
					}
					else{
						continue;
					}
					//OR connector encountered so execute and check it's exit status
					//If success then break for more input
					//Else continue with command line
				}
				else if (con_stat == 4){
					exec_stat = parse_exec(usrString.substr(start,pos-start), size);
					break;
					//COMMENT encountered so execute everything before and break
					//for more input
				}
			}
		}
	}

	return 0;
}

<commit_msg>fix fd bug<commit_after>#include <string.h>
#include <fcntl.h>
#include <boost/algorithm/string.hpp>
#include <boost/tokenizer.hpp>
#include <stdlib.h>
#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <vector>

using namespace boost;
using namespace std;

int check_input(string usrString)
{
	if (usrString.find("&&") != string::npos ||
		usrString.find("||") != string::npos ||
		usrString.find(";") != string::npos ||
		usrString.find("#") != string::npos ||
		(usrString.find(">") == string::npos &&
		usrString.find("<") == string::npos &&
		usrString.find("|") == string::npos))
		{
			return 0;
		}
	else
	{
		return 1;
	}
	return -1;
}

bool popv(string usrString, vector<string> &iop, vector<vector<string> > &cmds)
{
	typedef tokenizer<char_separator<char> > tokenizer;
	char_separator<char> sep(" ", "<>|", drop_empty_tokens);
	tokenizer tokens(usrString, sep);
	int cnt = 0;
	bool first = true;
	for (auto it = tokens.begin(); it != tokens.end(); ++it)
	{
		if(*it == "|" || *it == "<")
		{
			first = true;
			iop.push_back(*it);
			++cnt;
			continue;
		}
		else if(*it == ">")
		{
			if(iop.empty())
            {
            	first = true;
            	iop.push_back(*it);
            	++cnt;
            	continue;
            }

			else if (iop.at(iop.size()-1) == ">")
			{
				first = true;
				iop.at(iop.size()-1).append(">");
				continue;
			}
			else
			{
				first = true;
				iop.push_back(*it);
				++cnt;
			}
		}
		else
		{
			if(first)
			{
				first = false;
				vector<string> temp;
				temp.push_back(*it);
				cmds.push_back(temp);
			}
			else
			{
				cmds.at(cnt).push_back(*it);
			}
		}

	}

	//Print check
	/*
	cout << "cmds: ";
	for (size_t i = 0; i < cmds.size(); ++i)
	{
		for(size_t j = 0; j < cmds.at(i).size(); ++j)
		{
			cout << cmds.at(i).at(j) << " ";
		}
	}
	cout << endl;

	cout << "iop: ";
	for (size_t n = 0; n < iop.size(); ++n)
	{
		cout << iop.at(n) << " ";
	}
	cout << endl;
	*/
	return true;
}

//Function that parses a passed in string and executes the command it yields
bool parse_exec(string usrString, int size)
{
	int status;
	char **args = new char*[size+1];
	char *cstr = new char[size+1];
	strcpy(cstr,usrString.c_str());
	char *temp = strtok(cstr, " &|;#");
	int cnt = 0;

	while (temp != 0){
		args[cnt] = temp;
		++cnt;
		temp = strtok(NULL, " &|");
	}
	if (cnt == 0){
		delete[] cstr;
		delete[] args;
		return false;
	}
	args[cnt] = NULL;

	if (!strcmp(args[0],"exit")){
		exit(0);
	}

	int pid = fork();
	if (pid == -1){
		perror("fork");
	}
	else if(pid == 0){
		if (execvp(args[0],args) == -1){
			perror("execvp");
			exit(1);
		}
	}
	else if(pid > 0){
		if(-1 == wait(&status)){
			perror("wait");
		}
	}

	delete[] cstr;
	delete[] args;

	if(WEXITSTATUS(status) == 0){
		return true;
	}
	else{
		return false;
	}
	return false;
}

//Function checks for connectors and returns a number based on which one is found
//Pass in a string, a position integer, and a starting point integer
int check_connect(const string& str, int& pos, int start){
	unsigned found = 0;
	found = str.find_first_of(";&|#",start);
	if (found >= str.size()){	//If not found...
		pos = -1;
		return -1;
	}
	else{
		if (str.at(found) == ';'){
			pos = found;
			return 1;
		}
		else if (str.at(found) == '&'){
			if (str.at(found+1) == '&'){
				pos = found;
				return 2;
			}
			else{
				return check_connect(str,pos,found+1);
			}
		}

		else if (str.at(found) == '|'){
			if (str.at(found+1) == '|'){
				pos = found;
				return 3;
			}
			else{
				return 5;
			}
		}
		else if (str.at(found) == '#'){
			pos = found;
			return 4;
		}
	}
	return -1;
}

void my_close(int fd)
{
	if (-1 == close(fd))
	{
		perror("close");
	}
}
void redirect(int oldf, int newf)
{
	if (oldf != newf)
	{
		if (-1 == dup2(oldf,newf))
		{
			perror("dup2");
		}
		else
		{
			my_close(oldf);
		}
	}
}

void execute(vector<string> cmd, int in, int out)
{
	redirect(in, STDIN_FILENO);
	redirect(out, STDOUT_FILENO);

	int n = cmd.size();
	int i;
	const char **args = new const char*[ n+1 ];
	for (i = 0; i < n; ++i)
	{
		args[i] = cmd.at(i).c_str();
	}
	args[i] = NULL;

	execvp(args[0], (char * const*)args);
	perror("execvp");
	exit(1);
}

void in_redir(vector<string> cmd, string file, int out, int cnt)
{
	my_close(0);
	open(file.c_str(), O_RDWR);
	size_t i;
	const char **args = new const char*[cmd.size()+1];
	for (i = 0; i < cmd.size(); ++i)
	{
		args[i] = cmd.at(i).c_str();
	}
	args[i] = NULL;
	if ( cnt > 0 )
	{
		redirect(out,STDOUT_FILENO);
	}
	if(-1 == execvp(args[0], (char * const*)args))
	{
		perror("execvp");
		exit(1);
	}
}

void out1_redir(vector<string> cmd, string file, int out, int save_out)
{
	int out2;
	if (-1 == (out2 = open(file.c_str(), O_WRONLY | O_CREAT | O_TRUNC)))
	{
		perror("open");
		exit(1);
	}
	size_t i;
	const char **args = new const char*[cmd.size()+1];
	for (i = 0; i < cmd.size(); ++i)
	{
		args[i] = cmd.at(i).c_str();
	}
	args[i] = NULL;

	redirect(out2,STDOUT_FILENO);
	my_close(out2);
	if (-1 == execvp(args[0], (char * const*)args))
	{
		perror("execvp");
		exit(1);
	}
}

int main()
{
	//Get User Info
	string hostname;
	string username = getlogin();
	if(getlogin() == NULL){
		perror("login");
		username = "UNKNOWN";
	}
	char host_temp[64];
	if(gethostname(host_temp,64) == -1){
		perror("hostname");
		hostname = "UNKNOWN";
	}
	else{
		hostname = host_temp;
	}

	while(1){
		//Get User Input
		bool exec_stat = true;		//Execution Status
		int con_stat = 0;			//Connector Status
		int pos = 0;				//Position of Connector
		int start = 0;				//Start position for parse function
		int size = 0;				//Size of user input
		string usrString;			//User Input String
		vector<string> iop;
		vector<vector<string> > cmds;
		cout << username << "@" << hostname << "$ ";
		cin.sync();
		getline(cin,usrString); size = usrString.size();
		if (size == 0){
			continue;
		}

		if (1 == check_input(usrString))
		{
			iop.clear(); cmds.clear();
			popv(usrString,iop,cmds);

			int pipe_cnt = 0;
			for (size_t a = 0; a < iop.size(); ++a)
			{
				if (iop.at(a) == "|")
				{
					++pipe_cnt;
				}
			}

			if(cmds.empty())
			{
				continue;
			}

			/*int save_out;
			if (-1 == (save_out = dup(STDOUT_FILENO)))
			{
				perror("dup");
				exit(1);
			} */

			int save_in;
			if ( -1 == (save_in = dup(STDIN_FILENO)))
			{
				perror("dup");
				exit(1);
			}

			pid_t pid;
			int in = STDIN_FILENO;
			size_t i = 0;
			int fd[2];

			if (iop.at(0) == "<")
			{
				if (-1 == pipe(fd))
				{
					perror("pipe");
				}
				cout << "fd[0] " << fd[0] << endl;
				cout << "fd[1] " << fd[1] << endl;
				if (-1 == (pid = fork()))
				{
					perror("fork");
					exit(1);
				}
				else if (pid == 0)
				{
					my_close(fd[0]);
					in_redir(cmds.at(0),cmds.at(1).at(0),fd[1],pipe_cnt);
				}
				else if (pid > 0)
				{
					wait(0);
					my_close(fd[1]);
					my_close(in);
					in = fd[0];
					i = 2;
				}
			}

			if ((cmds.size() >= 2) && (pipe_cnt > 0))
			{

				for (; i < cmds.size()-1; ++i)
				{

					if (-1 == pipe(fd))
					{
						perror("pipe");
						exit(1);
					}
					else if (-1 == (pid = fork()))
					{
						perror("fork");
						exit(1);
					}
					else if (pid == 0)
					{
						my_close(fd[0]);
						execute(cmds.at(i),in,fd[1]);
						exit(1);
					}
					else if (pid >0)
					{
						wait(0);
						my_close(fd[1]);
						my_close(in);
						in = fd[0];
					}
				}

				if (-1 == (pid = fork()))
				{
					perror("fork");
					exit(1);
				}
				if (pid == 0)
				{
					execute(cmds.at(i),in,STDOUT_FILENO);
					exit(1);
				}
				else if (pid > 0)
				{
					wait(0);
					my_close(in);
					in = fd[0];
					cout << "fd[0]: " << fd[0] << endl;
					cout << "fd[1]: " << fd[1] << endl;
				}
			}
			dup2(save_in,STDIN_FILENO);
			my_close(save_in);
			//dup2(save_out,fd[1]);
			continue;

		}

		else
		{
			//Check Connectors
			while(1){
				exec_stat = false;
				con_stat = check_connect(usrString,pos,start);
				if (con_stat == -1){
					exec_stat = parse_exec(usrString.substr(start),size);
					break;
					//If -1 there are no more connectors in the string so
					//execute and break for more input
				}
				else if (con_stat == 1){
					exec_stat = parse_exec(usrString.substr(start,pos-start), size);
					start = pos + 1;
					continue;
					//Semi-colon encountered so execute and continue with
					//the rest of command line
				}
				else if (con_stat == 2){
					exec_stat = parse_exec(usrString.substr(start,pos-start), size);
					start = pos + 2;
					if (exec_stat == true){
						continue;
					}
					else{
						break;
					}
					//AND connector encountered so execute and check it's exit status
					//If success then continue with command line
					//Else break for more input
				}
				else if (con_stat == 3){
					exec_stat = parse_exec(usrString.substr(start,pos-start), size);
					start = pos + 2;
					if (exec_stat == true){
						break;
					}
					else{
						continue;
					}
					//OR connector encountered so execute and check it's exit status
					//If success then break for more input
					//Else continue with command line
				}
				else if (con_stat == 4){
					exec_stat = parse_exec(usrString.substr(start,pos-start), size);
					break;
					//COMMENT encountered so execute everything before and break
					//for more input
				}
			}
		}
	}

	return 0;
}

<|endoftext|>


<commit_before>#include <fstream>
#include <vector>
#include "LogEntryFilter.h"
#include "LogEntryRootFilter.h"
#include "LogEntryMessageFilter.h"
#include "LogEntryTimeFilter.h"
#include "FileUtils.hpp"
#include "CommandLineUtils.hpp"
#include "LogEntryParser.h"
#include "Rearranger.h"
#include "LogEntryFilterFactory.h"
#include "alphanum.hpp"

using namespace std;

void sortFiles(vector<string> &files);

int main(int argc, char *argv[]) {
    int ret = 0;
    if (argc == 1 || cmdOptionExists(argv, argv + argc, "--help")) {
        cout << "LogUtil: A handy tool to merge/filter log files.\n";
        cout << "usage :\tlogutil";
        cout << "\t[-d] [-f] [-o] [-r] [-start] [-end]\n";
        cout << "\n";
        cout << "\t-d merge all files under the directory.\n";
        cout << "\t-f sort the log file.\n";
        cout << "\t-o output file. [<file_or_dirname>_ALL.log] will be used if not set.\n";
        cout << "\t-r filter rules.\n";
        cout << "\t-start/end show logs between [start , end), \"YYYY-mm-dd hh:MM:SS.SSS\" .\n\n";
        cout << "examples :\n";
        cout << "\tlogutil -d ~/LogDir\n";
        cout << "\tlogutil -d ~/LogDir -start 2016-06-18\n";
        cout << "\tlogutil -d ~/LogDir -start 2016-06-18 -end 2016-06-19\n";
        cout << "\tlogutil -d ~/LogDir -f ~/block_rules.json\n";
        cout << "\tlogutil -d ~/LogDir -o ~/Log_ALL.log\n";
        cout << "\tlogutil -f ~/LogDir/log.log -o ~/Log_ALL.log\n";
        return 0;
    }
    vector<string> files;
    char *dirname = nullptr, *filename = nullptr, *outputFilename = nullptr;

    if (argc == 2) {
        if (isFile(argv[1])) {
            filename = argv[1];
        } else {
            dirname = argv[1];
        }
    } else {
        dirname = getCmdOption(argv, argv + argc, "-d");
        filename = getCmdOption(argv, argv + argc, "-f");
    }

    if (filename) {
        files.push_back(filename);
    }

    if (dirname) {
        ret = listFiles(dirname, files);
        sortFiles(files);
    }

    if (ret != 0) {
        return ret;
    }

    char *filterRultFile = getCmdOption(argv, argv + argc, "-r");
    char *startTime = getCmdOption(argv, argv + argc, "-start");
    char *endTime = getCmdOption(argv, argv + argc, "-end");

    outputFilename = getCmdOption(argv, argv + argc, "-o");
    if (!outputFilename) {
        if (filename) {
            string folderName, filenameWoDir;
            splitFilename(string(filename), folderName, filenameWoDir);

            string newFilename(folderName + "/All_" + filenameWoDir);
            outputFilename = new char[newFilename.length() + 1];
            strcpy(outputFilename, newFilename.c_str());
        } else if (dirname) {
            string newFilename(string(dirname) + "/" + "All.log");
            outputFilename = new char[newFilename.length() + 1];
            strcpy(outputFilename, newFilename.c_str());
        }
    }

    LogEntryFilterFactory::registerCreator("root", LogEntryRootFilter::creator);
    LogEntryFilterFactory::registerCreator("log", LogEntryMessageFilter::creator);
    LogEntryFilterFactory::registerCreator("time", LogEntryTimeFilter::creator);

    LogEntryParser parser;

    if (filterRultFile) {
        auto fileRuleStream = fstream(filterRultFile);
        json fileRuleJson;
        fileRuleStream >> fileRuleJson;
        parser.addFilter(LogEntryFilterFactory::create(fileRuleJson));
    }

    if (startTime || endTime) {
        string start = startTime ? (string) startTime : "";
        string end = endTime ? (string) endTime : "";
        LogEntryTimeFilter *filter = new LogEntryTimeFilter(
                LogEntryTimeFilter::getDate(start),
                LogEntryTimeFilter::getTime(start),
                LogEntryTimeFilter::getDate(end),
                LogEntryTimeFilter::getTime(end),
                true);
        parser.addFilter(filter);
    }

    vector<LogEntry *> entries;

    for (string file : files) {
        try {
            parser.parseFile(file, entries);
        } catch (runtime_error &error) {
            cerr << "Failed to parse file : " << file << ". error: " << error.what() << endl;
        } catch (...) {
            cerr << "Failed to parse file : " << file << endl;
        }
    }

    Rearranger rearranger;
    rearranger.sort(entries);

    int index = 1;
    for (LogEntry *entry : entries) {
        entry->line.orderedIndex = index;
        index += entry->line.lines.size();
    }

    if (outputFilename) {
        ofstream os(outputFilename);
        for (LogEntry *entry : entries) {
            os << *entry;
        }
    } else {
        for (LogEntry *entry : entries) {
            cout << *entry;
        }
    }

    return 0;
}

void sortFiles(vector<string> &files) {
    /*
     * A little tricky here: files must be sorted in natural order on filename.
     * Or output result might be mis-ordered on log entries with same timestamp but stored in separate files.
     *
     * For example.
     *
     * We'ev two logs files:
     *
     * 9.log ([2000-1-1 00:00:00,000] A)
     * 10.log ([2000-1-1 00:00:00,000] B)
     *
     * log [A] is printed before log [B] but both in the same time [2000-1-1 00:00:00,000].
     *
     * After sorting by ascii comparing on filename:
     * 10.log
     * 9.log
     *
     * Then we first parse [B] from 10.log and then [A] from 9.log:
     *
     * [2000-1-1 00:00:00,000] B
     * [2000-1-1 00:00:00,000] A
     *
     * So the sorting order of files must be the same as generating.
     *
     */
    sort(files.begin(), files.end(), [](string &lhs, string &rhs) {
            return doj::alphanum_comp(lhs, rhs) < 0;
        });
}<commit_msg>- : bug<commit_after>#include <fstream>
#include <vector>
#include "LogEntryFilter.h"
#include "LogEntryRootFilter.h"
#include "LogEntryMessageFilter.h"
#include "LogEntryTimeFilter.h"
#include "FileUtils.hpp"
#include "CommandLineUtils.hpp"
#include "LogEntryParser.h"
#include "Rearranger.h"
#include "LogEntryFilterFactory.h"
#include "alphanum.hpp"

using namespace std;

void sortFiles(vector<string> &files);

int main(int argc, char *argv[]) {
    int ret = 0;
    if (argc == 1 || cmdOptionExists(argv, argv + argc, "--help")) {
        cout << "LogUtil: A handy tool to merge/filter log files.\n";
        cout << "usage :\tlogutil";
        cout << "\t[-d] [-f] [-o] [-r] [-start] [-end]\n";
        cout << "\n";
        cout << "\t-d merge all files under the directory.\n";
        cout << "\t-f sort the log file.\n";
        cout << "\t-o output file. [<file_or_dirname>_ALL.log] will be used if not set.\n";
        cout << "\t-r filter rules.\n";
        cout << "\t-start/end show logs between [start , end), \"YYYY-mm-dd hh:MM:SS.SSS\" .\n\n";
        cout << "examples :\n";
        cout << "\tlogutil -d ~/LogDir\n";
        cout << "\tlogutil -d ~/LogDir -start 2016-06-18\n";
        cout << "\tlogutil -d ~/LogDir -start 2016-06-18 -end 2016-06-19\n";
        cout << "\tlogutil -d ~/LogDir -r ~/block_rules.json\n";
        cout << "\tlogutil -d ~/LogDir -o ~/Log_ALL.log\n";
        cout << "\tlogutil -f ~/LogDir/log.log -o ~/Log_ALL.log\n";
        return 0;
    }
    vector<string> files;
    char *dirname = nullptr, *filename = nullptr, *outputFilename = nullptr;

    if (argc == 2) {
        if (isFile(argv[1])) {
            filename = argv[1];
        } else {
            dirname = argv[1];
        }
    } else {
        dirname = getCmdOption(argv, argv + argc, "-d");
        filename = getCmdOption(argv, argv + argc, "-f");
    }

    if (filename) {
        files.push_back(filename);
    }

    if (dirname) {
        ret = listFiles(dirname, files);
        sortFiles(files);
    }

    if (ret != 0) {
        return ret;
    }

    char *filterRultFile = getCmdOption(argv, argv + argc, "-r");
    char *startTime = getCmdOption(argv, argv + argc, "-start");
    char *endTime = getCmdOption(argv, argv + argc, "-end");

    outputFilename = getCmdOption(argv, argv + argc, "-o");
    if (!outputFilename) {
        if (filename) {
            string folderName, filenameWoDir;
            splitFilename(string(filename), folderName, filenameWoDir);

            string newFilename(folderName + "/All_" + filenameWoDir);
            outputFilename = new char[newFilename.length() + 1];
            strcpy(outputFilename, newFilename.c_str());
        } else if (dirname) {
            string newFilename(string(dirname) + "/" + "All.log");
            outputFilename = new char[newFilename.length() + 1];
            strcpy(outputFilename, newFilename.c_str());
        }
    }

    LogEntryFilterFactory::registerCreator("root", LogEntryRootFilter::creator);
    LogEntryFilterFactory::registerCreator("log", LogEntryMessageFilter::creator);
    LogEntryFilterFactory::registerCreator("time", LogEntryTimeFilter::creator);

    LogEntryParser parser;

    if (filterRultFile) {
        auto fileRuleStream = fstream(filterRultFile);
        json fileRuleJson;
        fileRuleStream >> fileRuleJson;
        parser.addFilter(LogEntryFilterFactory::create(fileRuleJson));
    }

    if (startTime || endTime) {
        string start = startTime ? (string) startTime : "";
        string end = endTime ? (string) endTime : "";
        LogEntryTimeFilter *filter = new LogEntryTimeFilter(
                LogEntryTimeFilter::getDate(start),
                LogEntryTimeFilter::getTime(start),
                LogEntryTimeFilter::getDate(end),
                LogEntryTimeFilter::getTime(end),
                true);
        parser.addFilter(filter);
    }

    vector<LogEntry *> entries;

    for (string file : files) {
        try {
            parser.parseFile(file, entries);
        } catch (runtime_error &error) {
            cerr << "Failed to parse file : " << file << ". error: " << error.what() << endl;
        } catch (...) {
            cerr << "Failed to parse file : " << file << endl;
        }
    }

    Rearranger rearranger;
    rearranger.sort(entries);

    int index = 1;
    for (LogEntry *entry : entries) {
        entry->line.orderedIndex = index;
        index += entry->line.lines.size();
    }

    if (outputFilename) {
        ofstream os(outputFilename);
        for (LogEntry *entry : entries) {
            os << *entry;
        }
    } else {
        for (LogEntry *entry : entries) {
            cout << *entry;
        }
    }

    return 0;
}

void sortFiles(vector<string> &files) {
    /*
     * A little tricky here: files must be sorted in natural order on filename.
     * Or output result might be mis-ordered on log entries with same timestamp but stored in separate files.
     *
     * For example.
     *
     * We'ev two logs files:
     *
     * 9.log ([2000-1-1 00:00:00,000] A)
     * 10.log ([2000-1-1 00:00:00,000] B)
     *
     * log [A] is printed before log [B] but both in the same time [2000-1-1 00:00:00,000].
     *
     * After sorting by ascii comparing on filename:
     * 10.log
     * 9.log
     *
     * Then we first parse [B] from 10.log and then [A] from 9.log:
     *
     * [2000-1-1 00:00:00,000] B
     * [2000-1-1 00:00:00,000] A
     *
     * So the sorting order of files must be the same as generating.
     *
     */
    sort(files.begin(), files.end(), [](string &lhs, string &rhs) {
            return doj::alphanum_comp(lhs, rhs) < 0;
        });
}<|endoftext|>


<commit_before>/*!
 * @file main.cpp
 *
 * @brief FGAP entry point
 *
 * @author Andrey Shelest
 * @author Oleksii Aliakin (alex@nls.la)
 * @date Created Jan 04, 2015
 * @date Modified Sep 05, 2015
 */

#include "log.h"
#include "FgAircraftsModel.h"
#include "utils/Filesystem.h"

#include <QtQml>
#include <QTextCodec>
#include <QApplication>

int main(int argc, char *argv[])
{
#ifdef FGAP_PLUGINS_PATH
    // Add path to search for Qt plugins
    QString pluginsPaths = fgap::path::join(
                QFileInfo(argv[0]).dir().path(),
                FGAP_PLUGINS_PATH);
    QCoreApplication::addLibraryPath(pluginsPaths);
#endif

    QApplication app(argc, argv);
    qInstallMessageHandler(logMessageHandler);

    // Set up settings
    app.setOrganizationName("FlightgearAutopilot");
    app.setApplicationName("Flightgear_autopilot");
    QSettings::setDefaultFormat(QSettings::IniFormat);

    { // Copy default setting if settings file does not exist
        QSettings settings;
        QDir settingsDir = QFileInfo(settings.fileName()).absoluteDir();
        if (!settingsDir.exists())
            if (!settingsDir.mkpath(settingsDir.absolutePath()))
                qDebug() << "Could not create settings directory " << settingsDir.absolutePath();
        if (!QFile::exists(settings.fileName()))
        {
            QString configFileName(fgap::path::join(QCoreApplication::applicationDirPath(),
                                                    CONFIG_PATH,
                                                    "example_multiplayWithoutServer.ini"));
            qDebug() << "Copying "<< configFileName << " settings to " << settings.fileName();
            if (!QFile::copy(configFileName, settings.fileName()))
                qWarning() << "Could not copy default settings to " << settings.fileName();
        }
    }

    // Setup QML
    qmlRegisterType<FgAircraftsModel>("fgap", 1, 0, "FgAircraftsModel");
    QQmlApplicationEngine engine;
    QString qmlFilesPath = fgap::path::join(
                QCoreApplication::applicationDirPath(),
                FGAP_QML_MODULES_PATH);
    qDebug() << "qmlFilesPath = " << qmlFilesPath;
    engine.addImportPath(qmlFilesPath);
    engine.load(QUrl(QStringLiteral("qrc:qml/MainView.qml")));

    return app.exec();
}
<commit_msg>Properly hanlde QML errors.<commit_after>/*!
 * @file main.cpp
 *
 * @brief FGAP entry point
 *
 * @author Andrey Shelest
 * @author Oleksii Aliakin (alex@nls.la)
 * @date Created Jan 04, 2015
 * @date Modified Oct 21, 2015
 */

#include "log.h"
#include "FgAircraftsModel.h"
#include "utils/Filesystem.h"

#include <QtQml>
#include <QTextCodec>
#include <QMessageBox>
#include <QApplication>

int main(int argc, char *argv[])
{
#ifdef FGAP_PLUGINS_PATH
    // Add path to search for Qt plugins
    QString pluginsPaths = fgap::path::join(
                QFileInfo(argv[0]).dir().path(),
                FGAP_PLUGINS_PATH);
    QCoreApplication::addLibraryPath(pluginsPaths);
#endif

    QApplication app(argc, argv);
    qInstallMessageHandler(logMessageHandler);

    // Set up settings
    app.setOrganizationName("FlightgearAutopilot");
    app.setApplicationName("Flightgear_autopilot");
    QSettings::setDefaultFormat(QSettings::IniFormat);

    { // Copy default setting if settings file does not exist
        QSettings settings;
        QDir settingsDir = QFileInfo(settings.fileName()).absoluteDir();
        if (!settingsDir.exists())
            if (!settingsDir.mkpath(settingsDir.absolutePath()))
                qDebug() << "Could not create settings directory " << settingsDir.absolutePath();
        if (!QFile::exists(settings.fileName()))
        {
            QString configFileName(fgap::path::join(QCoreApplication::applicationDirPath(),
                                                    CONFIG_PATH,
                                                    "example_multiplayWithoutServer.ini"));
            qDebug() << "Copying "<< configFileName << " settings to " << settings.fileName();
            if (!QFile::copy(configFileName, settings.fileName()))
                qWarning() << "Could not copy default settings to " << settings.fileName();
        }
    }

    // Setup QML
    bool success = true;
    qmlRegisterType<FgAircraftsModel>("fgap", 1, 0, "FgAircraftsModel");
    QQmlApplicationEngine engine;
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, [&app, &success](QObject *object, const QUrl &url){
        if (!object)
        {
            qWarning() << "Could not load QML";
            QMessageBox::critical(nullptr, "Flightgear autopilot",
                                  "Flightgear autopilot is failed to start due to errors in the main QML file.\n"
                                  "Please report the error following this link: "
                                  ""
                                  "https://github.com/approximator/FlightGear_Autopilot/issues/new");
            success = false;
        }
        else
            qDebug() << "QML object created successfully: " << url;
    });

    QString qmlFilesPath = fgap::path::join(
                QCoreApplication::applicationDirPath(),
                FGAP_QML_MODULES_PATH);
    qDebug() << "qmlFilesPath = " << qmlFilesPath;
    engine.addImportPath(qmlFilesPath);
    engine.load(QUrl(QStringLiteral("qrc:qml/MainView.qml")));

    return success ? app.exec() : 1;
}
<|endoftext|>


<commit_before>#include <signal.h>
#include <cv.h>
#include <highgui.h>
#include <iostream>
#include <cstdlib>
#include <list>

#include <gflags/gflags.h>

using namespace std;
using namespace cv;

DEFINE_bool(display, true, "Display video in window.");
DEFINE_bool(quiet, false, "Suppress terminal output.");
DEFINE_string(save, "", "Save output to file.");
DEFINE_string(axis, "y", "Axis of rotation.");
DEFINE_double(fps, 24, "Frame per second for output.");
DEFINE_bool(live, false, "Use live feed.");
DEFINE_int32(postrotate, 0, "Rotation of final frames to fix flipped source video.\n"
                            "\t0\tNo rotation\n"
                            "\t1\t90 degrees clockwise\n"
                            "\t2\t90 degrees counter-clockwise\n"
                            "\t3\t180 degrees\n"
                            );

enum postrotate_enum {
    ROT_NONE,
    ROT_90CW,
    ROT_90CCW,
    ROT_180
};

enum axis_enum {
    AXIS_X,
    AXIS_Y,
    AXIS_T
};

typedef struct options_struct {
    enum axis_enum axis;
    Size size;
    int frame_count;
    VideoCapture *video_src;
    VideoWriter *video_dst;
    bool live;
    enum postrotate_enum postrotate;
} options_type;

int video_file_filter(options_type *o, char *window_name);
int video_live_filter(options_type *o, char *window_name);

options_type * create_options(int *argc, char ***argv) {
    google::ParseCommandLineFlags(argc, argv, true);
    options_type *o = (options_type *) calloc(1, sizeof(options_type));

    if (FLAGS_live && *argc == 1) {
        o->live = true;
    } else if (*argc != 2) {
        o->live = false;
        cout << "usage: " << *argv[0] << " input-video" << endl;
        free(o);
        return NULL;
    }

    // Prerotation?
    o->postrotate = (enum postrotate_enum)FLAGS_postrotate;

    // open input video
    if (o->live) {
        o->video_src = new VideoCapture(0);
    } else {
        string input_file = (*argv)[(*argc) - 1];
        o->video_src = new VideoCapture(input_file);
    }
    if(!o->video_src->isOpened()) return NULL;

    // get axis
    if (FLAGS_axis == "x") {
        o->axis = AXIS_X;
    } else if (FLAGS_axis == "y") {
        o->axis = AXIS_Y;
    } else if (FLAGS_axis == "t") {
        o->axis = AXIS_T;
    } else {
        free(o);
        return NULL;
    }

    // get size of output video
    int width = o->video_src->get(CV_CAP_PROP_FRAME_WIDTH);
    int height = o->video_src->get(CV_CAP_PROP_FRAME_HEIGHT);
    int frame_count = o->video_src->get(CV_CAP_PROP_FRAME_COUNT);
    if (o->live) {
        o->size = Size(width, height);
        o->frame_count = FLAGS_axis == "x" ? height : width;
    } else if (FLAGS_axis == "x") {
        o->size = Size(width, frame_count);
        o->frame_count = height;
    } else if (FLAGS_axis == "y") {
        o->size = Size(frame_count, height);
        o->frame_count = width;
    } else {
        free(o);
        return NULL;
    }

    // get output video
    if (!FLAGS_save.empty()) {
        o->video_dst = new VideoWriter;
        int ex = CV_FOURCC('I', 'Y', 'U', 'V');
        if (o->postrotate == ROT_NONE || o->postrotate == ROT_180) {
            o->video_dst->open(FLAGS_save, ex, FLAGS_fps, o->size);
        } else {
            o->video_dst->open(FLAGS_save, ex, FLAGS_fps, Size(o->size.height, o->size.width));
        }
    }

    return o;

}

int main(int argc, char **argv) {
    signal(SIGINT, SIG_IGN);

    google::SetUsageMessage("Rotate video in time.");

    options_type *o = create_options(&argc, &argv);
    if (o == NULL)
        return -1;

    if (FLAGS_display) {
        namedWindow(argv[0],CV_WINDOW_NORMAL);
        setWindowProperty(argv[0], CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);
    }

    if (o->live)
        video_live_filter(o, argv[0]);
    else
        video_file_filter(o, argv[0]);

    delete o->video_src;
    delete o->video_dst;
    free(o);

    return 0;
}

int video_live_filter(options_type *o, char *window_name) {
    Mat frame_in;
    *(o->video_src) >> frame_in;
    Mat frame_out(o->size, frame_in.type());

    list<Mat> frame_list;
    for (int i = 0; i < o->frame_count; i++) {
        cout << "Frame " << i+1 << " of " << o->frame_count << endl;
        if (waitKey(1) == '')
            return 0;
        *(o->video_src) >> frame_in;
        frame_list.push_back(frame_in.clone());
    }

    int j = 0;
    int d = 1;
    for (;;) {
        int i = 0;
        for (list<Mat>::iterator it = frame_list.begin(); it != frame_list.end(); it++) {
            switch (o->axis) {
                case AXIS_X:
                    it->row(j).copyTo(frame_out.row(i));
                    break;
                case AXIS_Y:
                    it->col(j).copyTo(frame_out.col(i));
                    break;
                default:
                    cout << "UNIMPLEMENTED" << endl;
                    return -1;
            }
            i++;
        }
        if (j == o->frame_count - 1) {
            d = -1;
        } else if (j == 0) {
            d = 1;
        }
        j += d;

        imshow(window_name, frame_out);
        if (waitKey(1) == '')
            return 0;

        *(o->video_src) >> frame_in;
        frame_list.push_back(frame_in.clone());
        frame_list.pop_front();
    }

}

int video_file_filter(options_type *o, char *window_name) {
    Mat frame_in;
    *(o->video_src) >> frame_in;
    Mat frame_out(o->size, frame_in.type());

    int frame_count_src = o->video_src->get(CV_CAP_PROP_FRAME_COUNT);
    for (int j = 0; j < o->frame_count; j++) {

        // Output status to console
        if (!FLAGS_quiet)
            cout << "Frame " << j+1 << " of " << o->frame_count << "." << endl;

        // Create a new frame.
        o->video_src->set(CV_CAP_PROP_POS_FRAMES, 0);
        for (int i = 0; i < frame_count_src; i++) {
            *(o->video_src) >> frame_in;
            switch (o->axis) {
                case AXIS_X:
                    frame_in.row(j).copyTo(frame_out.row(i));
                    break;
                case AXIS_Y:
                    frame_in.col(j).copyTo(frame_out.col(i));
                    break;
                default:
                    cout << "UNIMPLEMENTED" << endl;
                    return -1;
            }
        }

        // Do any postrotation required before finishing frame.
        Mat f;
        if (o->postrotate == ROT_90CW) {
            transpose(frame_out, f);
            flip(f, f, 1);
        } else if (o->postrotate == ROT_90CCW) {
            transpose(frame_out, f);
            flip(f, f, 0);
        } else if (o->postrotate == ROT_180) {
            flip(frame_out, f, -1);
        } else {
            f = frame_out;
        }

        // Display window
        if (FLAGS_display) {
            imshow(window_name, f);
            if (waitKey(1) == '')
                return 0;
        }

        // Save frame to file
        if (!FLAGS_save.empty())
            o->video_dst->write(f);

    }
}
<commit_msg>Added more detailed output about progress<commit_after>#include <signal.h>
#include <cv.h>
#include <highgui.h>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <list>

#include <gflags/gflags.h>

using namespace std;
using namespace cv;

DEFINE_bool(display, true, "Display video in window.");
DEFINE_bool(quiet, false, "Suppress terminal output.");
DEFINE_string(save, "", "Save output to file.");
DEFINE_string(axis, "y", "Axis of rotation.");
DEFINE_double(fps, 24, "Frame per second for output.");
DEFINE_bool(live, false, "Use live feed.");
DEFINE_int32(postrotate, 0, "Rotation of final frames to fix flipped source video.\n"
                            "\t0\tNo rotation\n"
                            "\t1\t90 degrees clockwise\n"
                            "\t2\t90 degrees counter-clockwise\n"
                            "\t3\t180 degrees\n"
                            );

enum postrotate_enum {
    ROT_NONE,
    ROT_90CW,
    ROT_90CCW,
    ROT_180
};

enum axis_enum {
    AXIS_X,
    AXIS_Y,
    AXIS_T
};

typedef struct options_struct {
    enum axis_enum axis;
    Size size;
    int frame_count;
    VideoCapture *video_src;
    VideoWriter *video_dst;
    bool live;
    enum postrotate_enum postrotate;
} options_type;

int video_file_filter(options_type *o, char *window_name);
int video_live_filter(options_type *o, char *window_name);

options_type * create_options(int *argc, char ***argv) {
    google::ParseCommandLineFlags(argc, argv, true);
    options_type *o = (options_type *) calloc(1, sizeof(options_type));

    if (FLAGS_live && *argc == 1) {
        o->live = true;
    } else if (*argc != 2) {
        o->live = false;
        cout << "usage: " << *argv[0] << " input-video" << endl;
        free(o);
        return NULL;
    }

    // Prerotation?
    o->postrotate = (enum postrotate_enum)FLAGS_postrotate;

    // open input video
    if (o->live) {
        o->video_src = new VideoCapture(0);
    } else {
        string input_file = (*argv)[(*argc) - 1];
        o->video_src = new VideoCapture(input_file);
    }
    if(!o->video_src->isOpened()) return NULL;

    // get axis
    if (FLAGS_axis == "x") {
        o->axis = AXIS_X;
    } else if (FLAGS_axis == "y") {
        o->axis = AXIS_Y;
    } else if (FLAGS_axis == "t") {
        o->axis = AXIS_T;
    } else {
        free(o);
        return NULL;
    }

    // get size of output video
    int width = o->video_src->get(CV_CAP_PROP_FRAME_WIDTH);
    int height = o->video_src->get(CV_CAP_PROP_FRAME_HEIGHT);
    int frame_count = o->video_src->get(CV_CAP_PROP_FRAME_COUNT);
    if (o->live) {
        o->size = Size(width, height);
        o->frame_count = FLAGS_axis == "x" ? height : width;
    } else if (FLAGS_axis == "x") {
        o->size = Size(width, frame_count);
        o->frame_count = height;
    } else if (FLAGS_axis == "y") {
        o->size = Size(frame_count, height);
        o->frame_count = width;
    } else {
        free(o);
        return NULL;
    }

    // get output video
    if (!FLAGS_save.empty()) {
        o->video_dst = new VideoWriter;
        int ex = CV_FOURCC('I', 'Y', 'U', 'V');
        if (o->postrotate == ROT_NONE || o->postrotate == ROT_180) {
            o->video_dst->open(FLAGS_save, ex, FLAGS_fps, o->size);
        } else {
            o->video_dst->open(FLAGS_save, ex, FLAGS_fps, Size(o->size.height, o->size.width));
        }
    }

    return o;

}

int main(int argc, char **argv) {
    signal(SIGINT, SIG_IGN);
    setbuf(stdout, NULL);

    google::SetUsageMessage("Rotate video in time.");

    options_type *o = create_options(&argc, &argv);
    if (o == NULL)
        return -1;

    if (FLAGS_display) {
        namedWindow(argv[0],CV_WINDOW_NORMAL);
        setWindowProperty(argv[0], CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);
    }

    if (o->live)
        video_live_filter(o, argv[0]);
    else
        video_file_filter(o, argv[0]);

    delete o->video_src;
    delete o->video_dst;
    free(o);

    return 0;
}

int video_live_filter(options_type *o, char *window_name) {
    Mat frame_in;
    *(o->video_src) >> frame_in;
    Mat frame_out(o->size, frame_in.type());

    list<Mat> frame_list;
    for (int i = 0; i < o->frame_count; i++) {
        cout << "Frame " << i+1 << " of " << o->frame_count << endl;
        if (waitKey(1) == '')
            return 0;
        *(o->video_src) >> frame_in;
        frame_list.push_back(frame_in.clone());
    }

    int j = 0;
    int d = 1;
    for (;;) {
        int i = 0;
        for (list<Mat>::iterator it = frame_list.begin(); it != frame_list.end(); it++) {
            switch (o->axis) {
                case AXIS_X:
                    it->row(j).copyTo(frame_out.row(i));
                    break;
                case AXIS_Y:
                    it->col(j).copyTo(frame_out.col(i));
                    break;
                default:
                    cout << "UNIMPLEMENTED" << endl;
                    return -1;
            }
            i++;
        }
        if (j == o->frame_count - 1) {
            d = -1;
        } else if (j == 0) {
            d = 1;
        }
        j += d;

        imshow(window_name, frame_out);
        if (waitKey(1) == '')
            return 0;

        *(o->video_src) >> frame_in;
        frame_list.push_back(frame_in.clone());
        frame_list.pop_front();
    }

}

int video_file_filter(options_type *o, char *window_name) {
    Mat frame_in;
    *(o->video_src) >> frame_in;
    Mat frame_out(o->size, frame_in.type());

    int frame_count_src = o->video_src->get(CV_CAP_PROP_FRAME_COUNT);
    for (int j = 0; j < o->frame_count; j++) {

        // Output status to console
        if (!FLAGS_quiet)
            printf("Frame %d of %d...",j + 1, o->frame_count);

        // Create a new frame.
        o->video_src->set(CV_CAP_PROP_POS_FRAMES, 0);
        for (int i = 0; i < frame_count_src; i++) {
            *(o->video_src) >> frame_in;
            switch (o->axis) {
                case AXIS_X:
                    frame_in.row(j).copyTo(frame_out.row(i));
                    break;
                case AXIS_Y:
                    frame_in.col(j).copyTo(frame_out.col(i));
                    break;
                default:
                    cout << "UNIMPLEMENTED" << endl;
                    return -1;
            }
        }

        if (o->postrotate != ROT_NONE) {
            printf("postrotation...");
        }

        // Do any postrotation required before finishing frame.
        Mat f;
        if (o->postrotate == ROT_90CW) {
            transpose(frame_out, f);
            flip(f, f, 1);
        } else if (o->postrotate == ROT_90CCW) {
            transpose(frame_out, f);
            flip(f, f, 0);
        } else if (o->postrotate == ROT_180) {
            flip(frame_out, f, -1);
        } else {
            f = frame_out;
        }

        // Display window
        if (FLAGS_display) {
            imshow(window_name, f);
            if (waitKey(1) == '')
                return 0;
        }

        // Save frame to file
        if (!FLAGS_save.empty()) {
            printf("writing...");
            o->video_dst->write(f);
        }

        printf("done.\n");

    }
}
<|endoftext|>