<commit_before><commit_msg>cloneGeometry replica creation<commit_after><|endoftext|>


<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

#include <iostream>

#include "parquet/api/reader.h"
#include "parquet/api/schema.h"

int main(int argc, char** argv) {
  std::string filename = argv[1];

  try {
    std::unique_ptr<parquet::ParquetFileReader> reader =
        parquet::ParquetFileReader::OpenFile(filename);
    PrintSchema(reader->metadata()->schema()->schema_root().get(), std::cout);
  } catch (const std::exception& e) {
    std::cerr << "Parquet error: " << e.what() << std::endl;
    return -1;
  }

  return 0;
}
<commit_msg>PARQUET-1426: [C++] parquet-dump-schema has poor usability<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

#include <getopt.h>
#include <iostream>

#include "parquet/api/reader.h"
#include "parquet/api/schema.h"

int main(int argc, char** argv) {
  static struct option options[] = {
    {"help", no_argument, nullptr, 'h'}
  };
  bool help_flag = false;
  int opt_index;
  do {
    opt_index = getopt_long(argc, argv, "h", options, nullptr);
    switch (opt_index) {
    case '?':
    case 'h':
      help_flag = true;
      opt_index = -1;
      break;
    }
  } while (opt_index != -1);
  argc -= optind;
  argv += optind;

  if (argc != 1 || help_flag) {
    std::cerr << "Usage: parquet-dump-schema [-h] [--help]"
              << " <filename>" << std::endl;
    return -1;
  }

  std::string filename = argv[0];

  try {
    std::unique_ptr<parquet::ParquetFileReader> reader =
        parquet::ParquetFileReader::OpenFile(filename);
    PrintSchema(reader->metadata()->schema()->schema_root().get(), std::cout);
  } catch (const std::exception& e) {
    std::cerr << "Parquet error: " << e.what() << std::endl;
    return -1;
  }

  return 0;
}
<|endoftext|>


<commit_before>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */

#include <common/EFUArgs.h>
#include <test/TestBase.h>

class EFUArgsTest : public TestBase {};

TEST_F(EFUArgsTest, Constructor) {
  EFUArgs efu_args;
  auto settings = efu_args.GetBaseSettings();

  // ASSERT_EQ(12, settings.cpustart); /**< todo fixme */
  ASSERT_EQ("0.0.0.0", settings.DetectorAddress);
  ASSERT_EQ(9000, settings.DetectorPort);
  ASSERT_EQ("localhost", settings.KafkaBrokerAddress);
  ASSERT_EQ(9092, settings.KafkaBrokerPort);
  ASSERT_EQ("127.0.0.1", settings.GraphiteAddress);
  ASSERT_EQ(2003, settings.GraphitePort);
  ASSERT_EQ(0xffffffffU, settings.StopAfterSec);
}

TEST_F(EFUArgsTest, VerifyCommandLineOptions) {

  // clang-format off
  const char *myargv[] = {"progname",
                        "-b", "mybroker",
                        "-c" , "99",
                        "-d", "myinst",
                        "-i", "1.2.3.4",
                        "-p", "9876",
                        "-g", "4.3.2.1",
                        "-o", "2323",
                        "-s", "5",
                        "-a", "10.0.0.1",
                        "-m", "8989" };
  // clang-format on
  int myargc = 21;
  EFUArgs efu_args;
  auto ret = efu_args.parseAndProceed(myargc, (char **)myargv);
  ASSERT_EQ(ret, true); // has detector
  auto settings = efu_args.GetBaseSettings();
  auto glsettings = efu_args.getGraylogSettings();

  ASSERT_EQ("mybroker", settings.KafkaBrokerAddress);
  // ASSERT_EQ(99, opts.cpustart); /**< todo fixme */
  ASSERT_EQ("myinst", efu_args.det);
  ASSERT_EQ("1.2.3.4", settings.DetectorAddress);
  ASSERT_EQ(9876, settings.DetectorPort);
  ASSERT_EQ("4.3.2.1", settings.GraphiteAddress);
  ASSERT_EQ(2323, settings.GraphitePort);
  ASSERT_EQ(5, settings.StopAfterSec);
  ASSERT_EQ("10.0.0.1", glsettings.address);
  ASSERT_EQ(8989, settings.CommandServerPort);
}

TEST_F(EFUArgsTest, HelpText) {
  int myargc = 2;
  const char *myargv[] = {"progname", "-h"};

  EFUArgs efu_args;
  auto ret = efu_args.parseAndProceed(myargc, (char **)myargv);
  ASSERT_EQ(ret, false); // has detector

  ASSERT_EQ(myargc, 2);
  ASSERT_TRUE(myargv != NULL);
}

int main(int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>corrected efuargstest after kafka broker revert<commit_after>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */

#include <common/EFUArgs.h>
#include <test/TestBase.h>

class EFUArgsTest : public TestBase {};

TEST_F(EFUArgsTest, Constructor) {
  EFUArgs efu_args;
  auto settings = efu_args.GetBaseSettings();

  // ASSERT_EQ(12, settings.cpustart); /**< todo fixme */
  ASSERT_EQ("0.0.0.0", settings.DetectorAddress);
  ASSERT_EQ(9000, settings.DetectorPort);
  ASSERT_EQ("localhost:9092", settings.KafkaBroker);
  ASSERT_EQ("127.0.0.1", settings.GraphiteAddress);
  ASSERT_EQ(2003, settings.GraphitePort);
  ASSERT_EQ(0xffffffffU, settings.StopAfterSec);
}

TEST_F(EFUArgsTest, VerifyCommandLineOptions) {

  // clang-format off
  const char *myargv[] = {"progname",
                        "-b", "mybroker:9091",
                        "-c" , "99",
                        "-d", "myinst",
                        "-i", "1.2.3.4",
                        "-p", "9876",
                        "-g", "4.3.2.1",
                        "-o", "2323",
                        "-s", "5",
                        "-a", "10.0.0.1",
                        "-m", "8989" };
  // clang-format on
  int myargc = 21;
  EFUArgs efu_args;
  auto ret = efu_args.parseAndProceed(myargc, (char **)myargv);
  ASSERT_EQ(ret, true); // has detector
  auto settings = efu_args.GetBaseSettings();
  auto glsettings = efu_args.getGraylogSettings();

  ASSERT_EQ("mybroker:9091", settings.KafkaBroker);
  // ASSERT_EQ(99, opts.cpustart); /**< todo fixme */
  ASSERT_EQ("myinst", efu_args.det);
  ASSERT_EQ("1.2.3.4", settings.DetectorAddress);
  ASSERT_EQ(9876, settings.DetectorPort);
  ASSERT_EQ("4.3.2.1", settings.GraphiteAddress);
  ASSERT_EQ(2323, settings.GraphitePort);
  ASSERT_EQ(5, settings.StopAfterSec);
  ASSERT_EQ("10.0.0.1", glsettings.address);
  ASSERT_EQ(8989, settings.CommandServerPort);
}

TEST_F(EFUArgsTest, HelpText) {
  int myargc = 2;
  const char *myargv[] = {"progname", "-h"};

  EFUArgs efu_args;
  auto ret = efu_args.parseAndProceed(myargc, (char **)myargv);
  ASSERT_EQ(ret, false); // has detector

  ASSERT_EQ(myargc, 2);
  ASSERT_TRUE(myargv != NULL);
}

int main(int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#pragma once

#include <string>
#include <memory>
#include <random>
#include <type_traits>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <deque>
#include <cmath>

#include <boost/optional.hpp>

#include <glm/glm.hpp>

#include "traits.hxx"

namespace wonder_rabbit_project
{
  namespace wonderland
  {
    namespace maze
    {
      namespace solver
      {
        template
        < class T_size = std::int_fast32_t
        >
        class solver_2d_t
          : public std::enable_shared_from_this< solver_2d_t< T_size > >
        {
        public:
          using size_t = T_size;

          using shared_t = std::shared_ptr< solver_2d_t< T_size > >;

          using coordinate_t = to_glm_vec2_t< size_t >;

          using data_t = std::vector< std::vector< std::uint8_t > >;
          using shared_data_t = std::shared_ptr< data_t >;

          using answer_t = std::deque< coordinate_t >;
          using shared_answer_t = std::shared_ptr< answer_t >;

        private:

          shared_data_t _maze;
          shared_answer_t _answer;

          size_t _width;
          size_t _height;

          bool _full_gamut;

          const std::vector< coordinate_t > _directions;

          solver::algorithm _algorithm;

          auto solve_find_cell( coordinate_t* pstart = nullptr, coordinate_t* pgoal = nullptr ) const
            -> void
          {
            bool start_finded = false;
            bool goal_finded  = false;

            for ( size_t y = 0; y < _maze -> size(); ++y )
              for ( size_t x = 0; x < (*_maze)[y].size(); ++x )
              {
                if ( start( (*_maze)[y][x] ) and pstart )
                {
                  *pstart = { x, y };

                  if ( not pgoal )
                    return;

                  start_finded = true;
                }
                else if ( goal( (*_maze)[y][x] ) and pgoal )
                {
                  *pgoal = { x, y };

                  if ( not pstart )
                    return;

                  goal_finded = true;
                }
              }

            if ( pstart and not start_finded )
              throw std::runtime_error( "maze data has not start cell." );

            if ( pgoal and not goal_finded )
              throw std::runtime_error( "maze data has not goal cell." );
          }

        public:

          solver_2d_t()
            : _full_gamut( false )
            , _directions( generate_directions< coordinate_t >() )
            , _algorithm( solver::algorithm::dijkstra )
          { }

          auto algorithm( const solver::algorithm a )
            -> shared_t
          {
            _algorithm = a;
            return this ->shared_from_this();
          }

          auto full_gamut( bool enable = true )
            -> shared_t
          {
            _full_gamut = enable;

            return this -> shared_from_this();
          }

          auto load( std::istream& s )
            -> shared_t
          {
            throw std::logic_error( "not impl yet." );
            return this -> shared_from_this();
          }

          auto load( const std::string& t )
            -> shared_t
          {
            throw std::logic_error( "not impl yet." );
            return this -> shared_from_this();
          }

          auto load( const shared_data_t d )
            -> shared_t
          {
            if ( not d )
              throw std::runtime_error( "maze data is null." );

            if ( d -> empty() )
              throw std::runtime_error( "maze data rows is empty." );

            if ( d -> cbegin() -> empty() )
              throw std::runtime_error( "maze data cols is empty." );

            _maze   = d;

            _width  = d -> cbegin() -> size();
            _height = d -> size();

            for ( auto row = _maze -> cbegin() + 1; row != _maze -> cend(); ++row )
              if ( _width != row -> size() )
                throw std::runtime_error( "maze data cols is not constant size." );

            return this -> shared_from_this();
          }

          auto solve( )
            -> shared_t
          {
            struct vertex_data_t
            {
              size_t       distance;
              coordinate_t previous;
            };

            std::vector< std::vector< boost::optional< vertex_data_t > > > data
              ( _maze -> size()
              , std::vector< boost::optional< vertex_data_t > >
                ( (*_maze)[0].size()
                )
              );

            std::function< auto ( const coordinate_t& p ) -> void > search;

            coordinate_t start, goal;

            std::function< auto ( const coordinate_t& p, const coordinate_t& np ) -> size_t > distance;

            switch( _algorithm )
            { case solver::algorithm::dijkstra:
                solve_find_cell( &start, nullptr );
                distance = [&]( const coordinate_t& p, const coordinate_t&)
                  {
                    return data[ p.y ][ p.x ] -> distance + 1;
                    //const auto delta = np - start;
                    //return std::abs( delta.x ) + std::abs( delta.y );
                  };
                break;

              case solver::algorithm::a_star:
                solve_find_cell( &start, &goal );
                distance = [&]( const coordinate_t&, const coordinate_t& np )
                  {
                    const auto delta = np - goal;
                    return std::abs( delta.x ) + std::abs( delta.y );
                  };
                break;

              default:
                throw std::runtime_error("invalid algorithm");
            };

            std::priority_queue
              < coordinate_t
              , std::vector< coordinate_t >
              , std::function< auto ( const coordinate_t&, const coordinate_t& ) -> bool >
              >
              search_queue
                ( [&]( const coordinate_t& a, const coordinate_t& b )
                  { return distance( data[ a.y ][ a.x ] -> previous, a ) > distance( data[ b.y ][ b.x ] -> previous, b ); }
                )
              ;

            bool path_finded = false;

            search = [ & ]( const coordinate_t& p )
            {

              for ( const auto& direction : _directions )
              {
                const auto np = p + direction;

                if ( np.x < 0
                  or np.y < 0
                  or np.x >= _width
                  or np.y >= _height
                  or not road( (*_maze)[ np.y ][ np.x ] )
                )
                  continue;

                auto d = distance( p, np );

                auto next_cell = data[ np.y ][ np.x ];

                if ( next_cell && next_cell -> distance <= d )
                  continue;

                data[ np.y ][ np.x ] = { d, p };

                if ( maze::goal( (*_maze)[ np.y ][ np.x ] ) )
                {
                  goal = np;
                  path_finded = true;
                  if ( not _full_gamut )
                    return;
                }

                search_queue.push( np );
              }

              while( not search_queue.empty() )
              {
                const auto np = search_queue.top();
                search_queue.pop();
                search( np );

                if ( path_finded and not _full_gamut )
                  return;
              }

            };

            data[ start.y ][ start.x ] = { 0, start };
            search( start );

            _answer = std::make_shared< answer_t >();

            for ( auto cell = goal; cell != start; cell = data[ cell.y ][ cell.x ] -> previous )
              _answer -> emplace_front( std::move( cell ) );
            _answer -> emplace_front( std::move( start ) );

            // for debug
            //*
            {
              std::stringstream r;
              for ( const auto data_raw : data )
              {
                for ( const auto data_cell : data_raw )
                  if ( data_cell )
                    r << std::min<char>( '@' + data_cell -> distance, 'Z' );
                  else
                    r << " ";
                r << "\n";
              }
              std::cerr << r.str();
            }
            //*/

            return this -> shared_from_this();
          }

          auto answer()
            -> shared_answer_t
          { return _answer; }

          auto to_string()
            -> std::string
          {
            std::stringstream r;
            for ( size_t n = 0; n < _answer -> size(); ++n )
              r << n << " : ( " << (*_answer)[n].x << ", " << (*_answer)[n].y << " )\n";
            return r.str();
          }

        };
      }
    }
  }
}
<commit_msg>comment out debug code.<commit_after>#pragma once

#include <string>
#include <memory>
#include <random>
#include <type_traits>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <deque>
#include <cmath>

#include <boost/optional.hpp>

#include <glm/glm.hpp>

#include "traits.hxx"

namespace wonder_rabbit_project
{
  namespace wonderland
  {
    namespace maze
    {
      namespace solver
      {
        template
        < class T_size = std::int_fast32_t
        >
        class solver_2d_t
          : public std::enable_shared_from_this< solver_2d_t< T_size > >
        {
        public:
          using size_t = T_size;

          using shared_t = std::shared_ptr< solver_2d_t< T_size > >;

          using coordinate_t = to_glm_vec2_t< size_t >;

          using data_t = std::vector< std::vector< std::uint8_t > >;
          using shared_data_t = std::shared_ptr< data_t >;

          using answer_t = std::deque< coordinate_t >;
          using shared_answer_t = std::shared_ptr< answer_t >;

        private:

          shared_data_t _maze;
          shared_answer_t _answer;

          size_t _width;
          size_t _height;

          bool _full_gamut;

          const std::vector< coordinate_t > _directions;

          solver::algorithm _algorithm;

          auto solve_find_cell( coordinate_t* pstart = nullptr, coordinate_t* pgoal = nullptr ) const
            -> void
          {
            bool start_finded = false;
            bool goal_finded  = false;

            for ( size_t y = 0; y < _maze -> size(); ++y )
              for ( size_t x = 0; x < (*_maze)[y].size(); ++x )
              {
                if ( start( (*_maze)[y][x] ) and pstart )
                {
                  *pstart = { x, y };

                  if ( not pgoal )
                    return;

                  start_finded = true;
                }
                else if ( goal( (*_maze)[y][x] ) and pgoal )
                {
                  *pgoal = { x, y };

                  if ( not pstart )
                    return;

                  goal_finded = true;
                }
              }

            if ( pstart and not start_finded )
              throw std::runtime_error( "maze data has not start cell." );

            if ( pgoal and not goal_finded )
              throw std::runtime_error( "maze data has not goal cell." );
          }

        public:

          solver_2d_t()
            : _full_gamut( false )
            , _directions( generate_directions< coordinate_t >() )
            , _algorithm( solver::algorithm::dijkstra )
          { }

          auto algorithm( const solver::algorithm a )
            -> shared_t
          {
            _algorithm = a;
            return this ->shared_from_this();
          }

          auto full_gamut( bool enable = true )
            -> shared_t
          {
            _full_gamut = enable;

            return this -> shared_from_this();
          }

          auto load( std::istream& s )
            -> shared_t
          {
            throw std::logic_error( "not impl yet." );
            return this -> shared_from_this();
          }

          auto load( const std::string& t )
            -> shared_t
          {
            throw std::logic_error( "not impl yet." );
            return this -> shared_from_this();
          }

          auto load( const shared_data_t d )
            -> shared_t
          {
            if ( not d )
              throw std::runtime_error( "maze data is null." );

            if ( d -> empty() )
              throw std::runtime_error( "maze data rows is empty." );

            if ( d -> cbegin() -> empty() )
              throw std::runtime_error( "maze data cols is empty." );

            _maze   = d;

            _width  = d -> cbegin() -> size();
            _height = d -> size();

            for ( auto row = _maze -> cbegin() + 1; row != _maze -> cend(); ++row )
              if ( _width != row -> size() )
                throw std::runtime_error( "maze data cols is not constant size." );

            return this -> shared_from_this();
          }

          auto solve( )
            -> shared_t
          {
            struct vertex_data_t
            {
              size_t       distance;
              coordinate_t previous;
            };

            std::vector< std::vector< boost::optional< vertex_data_t > > > data
              ( _maze -> size()
              , std::vector< boost::optional< vertex_data_t > >
                ( (*_maze)[0].size()
                )
              );

            std::function< auto ( const coordinate_t& p ) -> void > search;

            coordinate_t start, goal;

            std::function< auto ( const coordinate_t& p, const coordinate_t& np ) -> size_t > distance;

            switch( _algorithm )
            { case solver::algorithm::dijkstra:
                solve_find_cell( &start, nullptr );
                distance = [&]( const coordinate_t& p, const coordinate_t&)
                  {
                    return data[ p.y ][ p.x ] -> distance + 1;
                    //const auto delta = np - start;
                    //return std::abs( delta.x ) + std::abs( delta.y );
                  };
                break;

              case solver::algorithm::a_star:
                solve_find_cell( &start, &goal );
                distance = [&]( const coordinate_t&, const coordinate_t& np )
                  {
                    const auto delta = np - goal;
                    return std::abs( delta.x ) + std::abs( delta.y );
                  };
                break;

              default:
                throw std::runtime_error("invalid algorithm");
            };

            std::priority_queue
              < coordinate_t
              , std::vector< coordinate_t >
              , std::function< auto ( const coordinate_t&, const coordinate_t& ) -> bool >
              >
              search_queue
                ( [&]( const coordinate_t& a, const coordinate_t& b )
                  { return distance( data[ a.y ][ a.x ] -> previous, a ) > distance( data[ b.y ][ b.x ] -> previous, b ); }
                )
              ;

            bool path_finded = false;

            search = [ & ]( const coordinate_t& p )
            {

              for ( const auto& direction : _directions )
              {
                const auto np = p + direction;

                if ( np.x < 0
                  or np.y < 0
                  or np.x >= _width
                  or np.y >= _height
                  or not road( (*_maze)[ np.y ][ np.x ] )
                )
                  continue;

                auto d = distance( p, np );

                auto next_cell = data[ np.y ][ np.x ];

                if ( next_cell && next_cell -> distance <= d )
                  continue;

                data[ np.y ][ np.x ] = { d, p };

                if ( maze::goal( (*_maze)[ np.y ][ np.x ] ) )
                {
                  goal = np;
                  path_finded = true;
                  if ( not _full_gamut )
                    return;
                }

                search_queue.push( np );
              }

              while( not search_queue.empty() )
              {
                const auto np = search_queue.top();
                search_queue.pop();
                search( np );

                if ( path_finded and not _full_gamut )
                  return;
              }

            };

            data[ start.y ][ start.x ] = { 0, start };
            search( start );

            _answer = std::make_shared< answer_t >();

            for ( auto cell = goal; cell != start; cell = data[ cell.y ][ cell.x ] -> previous )
              _answer -> emplace_front( std::move( cell ) );
            _answer -> emplace_front( std::move( start ) );

            // for debug
            /*
            {
              std::stringstream r;
              for ( const auto data_raw : data )
              {
                for ( const auto data_cell : data_raw )
                  if ( data_cell )
                    r << std::min<char>( '@' + data_cell -> distance, 'Z' );
                  else
                    r << " ";
                r << "\n";
              }
              std::cerr << r.str();
            }
            //*/

            return this -> shared_from_this();
          }

          auto answer()
            -> shared_answer_t
          { return _answer; }

          auto to_string()
            -> std::string
          {
            std::stringstream r;
            for ( size_t n = 0; n < _answer -> size(); ++n )
              r << n << " : ( " << (*_answer)[n].x << ", " << (*_answer)[n].y << " )\n";
            return r.str();
          }

        };
      }
    }
  }
}
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include "pch.h"
#include "lhc_mock.h"
#include "../HTTP/httpcall.h"

using namespace xbox::httpclient;

bool DoesMockCallMatch(_In_ const HC_CALL* mockCall, _In_ const HC_CALL* originalCall)
{
    if (mockCall->url.empty())
    {
        return true;
    }
    else
    {
        if (originalCall->url.substr(0, mockCall->url.size()) == mockCall->url)
        {
            if (mockCall->requestBodyBytes.empty())
            {
                return true;
            }
            else
            {
                if (originalCall->requestBodyBytes == mockCall->requestBodyBytes)
                {
                    return true;
                }
            }
        }
    }

    return false;
}

long GetIndexOfMock(const http_internal_vector<HC_MOCK_CALL*>& mocks, HC_MOCK_CALL* lastMatchingMock)
{
    if (lastMatchingMock == nullptr)
    {
        return -1;
    }

    for (long i = 0; i < static_cast<long>(mocks.size()); i++)
    {
        if (mocks[i] == lastMatchingMock)
        {
            return i;
        }
    }

    return -1;
}

HC_MOCK_CALL* GetMatchingMock(
    _In_ HC_CALL* originalCall
)
{
    auto httpSingleton = get_http_singleton(false);
    if (nullptr == httpSingleton)
    {
        return nullptr;
    }

    http_internal_vector<HC_MOCK_CALL*> mocks;
    HC_MOCK_CALL* lastMatchingMock = nullptr;
    HC_MOCK_CALL* matchingMock = nullptr;

    {
        std::lock_guard<std::recursive_mutex> guard(httpSingleton->m_mocksLock);
        mocks = httpSingleton->m_mocks;
        lastMatchingMock = httpSingleton->m_lastMatchingMock;
    }

    // ignore last matching call if it doesn't match the current call
    if (lastMatchingMock != nullptr && !DoesMockCallMatch(lastMatchingMock, originalCall))
    {
        lastMatchingMock = nullptr;
    }

    auto lastMockIndex = GetIndexOfMock(mocks, lastMatchingMock);
    if (lastMockIndex == -1)
    {
        // if there was no last matching call, then look through all mocks for first match
        for (auto& mockCall : mocks)
        {
            if (DoesMockCallMatch(mockCall, originalCall))
            {
                matchingMock = mockCall;
                break;
            }
        }
    }
    else
    {
        // if there was last matching call, looking through the rest of the mocks to see if there's more that match
        for (auto j = lastMockIndex + 1; j < static_cast<long>(mocks.size()); j++)
        {
            if (DoesMockCallMatch(mocks[j], originalCall))
            {
                matchingMock = mocks[j];
                break;
            }
        }

        // if last after matches, then just keep returning last match
        if (matchingMock == nullptr)
        {
            matchingMock = lastMatchingMock;
        }
    }

    {
        std::lock_guard<std::recursive_mutex> guard(httpSingleton->m_mocksLock);
        httpSingleton->m_lastMatchingMock = matchingMock;
    }

    return matchingMock;
}

bool Mock_Internal_HCHttpCallPerformAsync(
    _In_ HCCallHandle originalCallHandle
    )
{
    HC_CALL* originalCall = static_cast<HC_CALL*>(originalCallHandle);
    HC_MOCK_CALL* matchingMock = GetMatchingMock(originalCall);
    if (matchingMock == nullptr)
    {
        return false;
    }

    if (matchingMock->matchedCallback)
    {
        matchingMock->matchedCallback(
            matchingMock,
            originalCall->method.data(),
            originalCall->url.data(),
            originalCall->requestBodyBytes.data(),
            static_cast<uint32_t>(originalCall->requestBodyBytes.size()),
            matchingMock->matchCallbackContext
        );
    }

    size_t byteBuf;
    HCHttpCallResponseGetResponseBodyBytesSize(matchingMock, &byteBuf);
    http_memory_buffer buffer(byteBuf);
    HCHttpCallResponseGetResponseBodyBytes(matchingMock, byteBuf, static_cast<uint8_t*>(buffer.get()), nullptr);
    HCHttpCallResponseSetResponseBodyBytes(originalCall, static_cast<uint8_t*>(buffer.get()), byteBuf);

    uint32_t code;
    HCHttpCallResponseGetStatusCode(matchingMock, &code);
    HCHttpCallResponseSetStatusCode(originalCall, code);

    HRESULT genCode;
    HCHttpCallResponseGetNetworkErrorCode(matchingMock, &genCode, &code);
    HCHttpCallResponseSetNetworkErrorCode(originalCall, genCode, code);

    uint32_t numheaders;
    HCHttpCallResponseGetNumHeaders(matchingMock, &numheaders);

    const char* str1;
    const char* str2;
    for (uint32_t i = 0; i < numheaders; i++)
    {
        HCHttpCallResponseGetHeaderAtIndex(matchingMock, i, &str1, &str2);
        HCHttpCallResponseSetHeader(originalCall, str1, str2);
    }

    return true;
}
<commit_msg>Early exit if no mocks (#448)<commit_after>// Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include "pch.h"
#include "lhc_mock.h"
#include "../HTTP/httpcall.h"

using namespace xbox::httpclient;

bool DoesMockCallMatch(_In_ const HC_CALL* mockCall, _In_ const HC_CALL* originalCall)
{
    if (mockCall->url.empty())
    {
        return true;
    }
    else
    {
        if (originalCall->url.substr(0, mockCall->url.size()) == mockCall->url)
        {
            if (mockCall->requestBodyBytes.empty())
            {
                return true;
            }
            else
            {
                if (originalCall->requestBodyBytes == mockCall->requestBodyBytes)
                {
                    return true;
                }
            }
        }
    }

    return false;
}

long GetIndexOfMock(const http_internal_vector<HC_MOCK_CALL*>& mocks, HC_MOCK_CALL* lastMatchingMock)
{
    if (lastMatchingMock == nullptr)
    {
        return -1;
    }

    for (long i = 0; i < static_cast<long>(mocks.size()); i++)
    {
        if (mocks[i] == lastMatchingMock)
        {
            return i;
        }
    }

    return -1;
}

HC_MOCK_CALL* GetMatchingMock(
    _In_ HC_CALL* originalCall
)
{
    auto httpSingleton = get_http_singleton(false);
    if (nullptr == httpSingleton)
    {
        return nullptr;
    }

    if (httpSingleton->m_mocks.size() == 0)
    {
        return nullptr;
    }

    http_internal_vector<HC_MOCK_CALL*> mocks;
    HC_MOCK_CALL* lastMatchingMock = nullptr;
    HC_MOCK_CALL* matchingMock = nullptr;

    {
        std::lock_guard<std::recursive_mutex> guard(httpSingleton->m_mocksLock);
        mocks = httpSingleton->m_mocks;
        lastMatchingMock = httpSingleton->m_lastMatchingMock;
    }

    // ignore last matching call if it doesn't match the current call
    if (lastMatchingMock != nullptr && !DoesMockCallMatch(lastMatchingMock, originalCall))
    {
        lastMatchingMock = nullptr;
    }

    auto lastMockIndex = GetIndexOfMock(mocks, lastMatchingMock);
    if (lastMockIndex == -1)
    {
        // if there was no last matching call, then look through all mocks for first match
        for (auto& mockCall : mocks)
        {
            if (DoesMockCallMatch(mockCall, originalCall))
            {
                matchingMock = mockCall;
                break;
            }
        }
    }
    else
    {
        // if there was last matching call, looking through the rest of the mocks to see if there's more that match
        for (auto j = lastMockIndex + 1; j < static_cast<long>(mocks.size()); j++)
        {
            if (DoesMockCallMatch(mocks[j], originalCall))
            {
                matchingMock = mocks[j];
                break;
            }
        }

        // if last after matches, then just keep returning last match
        if (matchingMock == nullptr)
        {
            matchingMock = lastMatchingMock;
        }
    }

    {
        std::lock_guard<std::recursive_mutex> guard(httpSingleton->m_mocksLock);
        httpSingleton->m_lastMatchingMock = matchingMock;
    }

    return matchingMock;
}

bool Mock_Internal_HCHttpCallPerformAsync(
    _In_ HCCallHandle originalCallHandle
    )
{
    HC_CALL* originalCall = static_cast<HC_CALL*>(originalCallHandle);
    HC_MOCK_CALL* matchingMock = GetMatchingMock(originalCall);
    if (matchingMock == nullptr)
    {
        return false;
    }

    if (matchingMock->matchedCallback)
    {
        matchingMock->matchedCallback(
            matchingMock,
            originalCall->method.data(),
            originalCall->url.data(),
            originalCall->requestBodyBytes.data(),
            static_cast<uint32_t>(originalCall->requestBodyBytes.size()),
            matchingMock->matchCallbackContext
        );
    }

    size_t byteBuf;
    HCHttpCallResponseGetResponseBodyBytesSize(matchingMock, &byteBuf);
    http_memory_buffer buffer(byteBuf);
    HCHttpCallResponseGetResponseBodyBytes(matchingMock, byteBuf, static_cast<uint8_t*>(buffer.get()), nullptr);
    HCHttpCallResponseSetResponseBodyBytes(originalCall, static_cast<uint8_t*>(buffer.get()), byteBuf);

    uint32_t code;
    HCHttpCallResponseGetStatusCode(matchingMock, &code);
    HCHttpCallResponseSetStatusCode(originalCall, code);

    HRESULT genCode;
    HCHttpCallResponseGetNetworkErrorCode(matchingMock, &genCode, &code);
    HCHttpCallResponseSetNetworkErrorCode(originalCall, genCode, code);

    uint32_t numheaders;
    HCHttpCallResponseGetNumHeaders(matchingMock, &numheaders);

    const char* str1;
    const char* str2;
    for (uint32_t i = 0; i < numheaders; i++)
    {
        HCHttpCallResponseGetHeaderAtIndex(matchingMock, i, &str1, &str2);
        HCHttpCallResponseSetHeader(originalCall, str1, str2);
    }

    return true;
}
<|endoftext|>


<commit_before>/*
 * copyright: (c) RDO-Team, 2010
 * filename : rdo_event.cpp
 * author   :  ,
 * date     : 18.08.2010
 * bref     :
 * indent   : 4T
 */

// ====================================================================== INCLUDES
// ====================================================================== SYNOPSIS
#include "rdo_lib/rdo_runtime/pch.h"
#include "rdo_lib/rdo_runtime/rdo_event.h"
#include "rdo_lib/rdo_runtime/rdo_runtime.h"
// ===============================================================================

OPEN_RDO_RUNTIME_NAMESPACE

// ----------------------------------------------------------------------------
// ---------- RDOEvent
// ----------------------------------------------------------------------------
RDOEvent::RDOEvent( RDORuntime* runtime, RDOPatternEvent* pattern, bool trace, const std::string& name ):
	RDOActivityPattern<RDOPatternEvent>( runtime, pattern, trace, name )
{
	setTrace( trace );
	setTraceID( runtime->getFreeEventId() );
}

void RDOEvent::onStart( RDOSimulator* sim )
{
	onBeforeEvent( sim );
}

void RDOEvent::onStop( RDOSimulator* sim )
{
	sim->removeTimePoint( this );
}

bool RDOEvent::onCheckCondition(RDOSimulator *sim)
{
	return false;
}

IBaseOperation::BOResult RDOEvent::onDoOperation( RDOSimulator* sim )
{
	return IBaseOperation::BOR_cant_run;
}

void RDOEvent::onMakePlaned( RDOSimulator* sim, void* param )
{
	sim->inc_cnt_events();
	onBeforeEvent( sim );
	convertEvent( sim );
	onAfterEvent( sim );
}

void RDOEvent::convertEvent( RDOSimulator* sim )
{
	static_cast<RDORuntime*>(sim)->setCurrentActivity( this );
	m_pattern->convertEvent( static_cast<RDORuntime*>(sim) );
}

void RDOEvent::onBeforeEvent( RDOSimulator* sim )
{
	setPatternParameters( sim );
}

void RDOEvent::onAfterEvent( RDOSimulator* sim )
{
	updateConvertStatus( sim, m_pattern->m_convertorStatus );
	static_cast<RDOSimulatorTrace*>(sim)->getTracer()->writeEvent( this, static_cast<RDOSimulatorTrace*>(sim) );
	m_pattern->convertErase( static_cast<RDORuntime*>(sim) );
	updateRelRes( sim );
}

double RDOEvent::getNextTimeInterval( RDOSimulator* sim )
{
	static_cast<RDORuntime*>(sim)->setCurrentActivity( this );
	return m_pattern->getNextTimeInterval( static_cast<RDORuntime*>(sim) );
}

IBaseOperation::BOResult RDOEvent::onContinue(PTR(rdoRuntime::RDOSimulator) sim)
{
	return IBaseOperation::BOR_cant_run;
}

CLOSE_RDO_RUNTIME_NAMESPACE
<commit_msg> - для событий добавлено самопланирование, если для события проинициализирован атрибут m_timeCalc<commit_after>/*
 * copyright: (c) RDO-Team, 2010
 * filename : rdo_event.cpp
 * author   :  ,
 * date     : 18.08.2010
 * bref     :
 * indent   : 4T
 */

// ====================================================================== INCLUDES
// ====================================================================== SYNOPSIS
#include "rdo_lib/rdo_runtime/pch.h"
#include "rdo_lib/rdo_runtime/rdo_event.h"
#include "rdo_lib/rdo_runtime/rdo_runtime.h"
// ===============================================================================

OPEN_RDO_RUNTIME_NAMESPACE

// ----------------------------------------------------------------------------
// ---------- RDOEvent
// ----------------------------------------------------------------------------
RDOEvent::RDOEvent( RDORuntime* runtime, RDOPatternEvent* pattern, bool trace, const std::string& name ):
	RDOActivityPattern<RDOPatternEvent>( runtime, pattern, trace, name )
{
	setTrace( trace );
	setTraceID( runtime->getFreeEventId() );
}

void RDOEvent::onStart( RDOSimulator* sim )
{
	onBeforeEvent( sim );
}

void RDOEvent::onStop( RDOSimulator* sim )
{
	sim->removeTimePoint( this );
}

bool RDOEvent::onCheckCondition(RDOSimulator *sim)
{
	return false;
}

IBaseOperation::BOResult RDOEvent::onDoOperation( RDOSimulator* sim )
{
	return IBaseOperation::BOR_cant_run;
}

void RDOEvent::onMakePlaned( RDOSimulator* sim, void* param )
{
	sim->inc_cnt_events();
	onBeforeEvent( sim );
	if (m_pattern->m_timeCalc) sim->addTimePoint( getNextTimeInterval(sim) + sim->getCurrentTime(), this );
	convertEvent( sim );
	onAfterEvent( sim );
}

void RDOEvent::convertEvent( RDOSimulator* sim )
{
	static_cast<RDORuntime*>(sim)->setCurrentActivity( this );
	m_pattern->convertEvent( static_cast<RDORuntime*>(sim) );
}

void RDOEvent::onBeforeEvent( RDOSimulator* sim )
{
	setPatternParameters( sim );
}

void RDOEvent::onAfterEvent( RDOSimulator* sim )
{
	updateConvertStatus( sim, m_pattern->m_convertorStatus );
	static_cast<RDOSimulatorTrace*>(sim)->getTracer()->writeEvent( this, static_cast<RDOSimulatorTrace*>(sim) );
	m_pattern->convertErase( static_cast<RDORuntime*>(sim) );
	updateRelRes( sim );
}

double RDOEvent::getNextTimeInterval( RDOSimulator* sim )
{
	static_cast<RDORuntime*>(sim)->setCurrentActivity( this );
	return m_pattern->getNextTimeInterval( static_cast<RDORuntime*>(sim) );
}

IBaseOperation::BOResult RDOEvent::onContinue(PTR(rdoRuntime::RDOSimulator) sim)
{
	return IBaseOperation::BOR_cant_run;
}

CLOSE_RDO_RUNTIME_NAMESPACE
<|endoftext|>


<commit_before><commit_msg>Added type annotation postfix<commit_after><|endoftext|>


<commit_before>//=============================================================================================================
/**
* @file     natusproducer.cpp
* @author   Lorenz Esch <lorenz.esch@tu-ilmenau.de>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     June, 2018
*
* @section  LICENSE
*
* Copyright (C) 2018, Lorenz Esch and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
*       to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief    Contains the definition of the NatusProducer class.
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "natusproducer.h"

#include <iostream>

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QDebug>
#include <QDataStream>
#include <QScopedArrayPointer>

//*************************************************************************************************************
//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace NATUSPLUGIN;
using namespace Eigen;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

NatusProducer::NatusProducer(int iBlockSize, int iChannelSize, QObject *parent)
: QObject(parent)
, m_iMatDataSampleIterator(1)
{
    //qRegisterMetaType<Eigen::MatrixXd>();

    //Init socket
    m_pUdpSocket = QSharedPointer<QUdpSocket>(new QUdpSocket(this));
    m_pUdpSocket->bind(QHostAddress::AnyIPv4, 50000);
    connect(m_pUdpSocket.data(), &QUdpSocket::readyRead,
            this, &NatusProducer::readPendingDatagrams);

    m_matData.resize(iChannelSize, iBlockSize);
}

//*************************************************************************************************************

void NatusProducer::readPendingDatagrams()
{
    while (m_pUdpSocket->hasPendingDatagrams()) {
        QNetworkDatagram datagram = m_pUdpSocket->receiveDatagram();
        //qDebug() << "Datagram on port 50000 from IP "<<datagram.senderAddress();
        processDatagram(datagram);
    }
}

//*************************************************************************************************************

void NatusProducer::processDatagram(const QNetworkDatagram &datagram)
{
    QByteArray data = datagram.data();
    QDataStream stream(data);

    // Read info
    float fPackageNumber, fNumberSamples, fNumberChannels;

    char cInfo[3*sizeof(float)];
    stream.readRawData(cInfo, sizeof(cInfo));

    float* fInfo = reinterpret_cast<float*>(cInfo);

    fPackageNumber = fInfo[0];
    fNumberSamples = fInfo[1];
    fNumberChannels = fInfo[2];

//    // Print info about received data
//    qDebug()<<"fPackageNumber "<<fPackageNumber;
//    qDebug()<<"fNumberSamples "<<fNumberSamples;
//    qDebug()<<"fNumberChannels "<<fNumberChannels;
//    qDebug()<<"data.size() "<<data.size();
//    qDebug()<<"data.size() "<<data.size();
//    qDebug()<<"data.size() "<<data.size();

    // Read actual data
    int iDataSize = int(fNumberSamples * fNumberChannels);
    QScopedArrayPointer<char> cData(new char[iDataSize*sizeof(float)]);
    //char *cData = new char[iDataSize*sizeof(float)];
    stream.readRawData(cData.data(), iDataSize*sizeof(float));

    float* fData = reinterpret_cast<float*>(cData.data());

    //Get data
    Eigen::MatrixXf matData;
    matData.resize(fNumberChannels, fNumberSamples);
    int itr = 0;
    for(int j = 0; j < fNumberSamples; ++j) {
        for(int i = 0; i < fNumberChannels; ++i) {
            matData(i,j) = fData[itr++]/10e06;
        }
    }

    if(m_iMatDataSampleIterator+matData.cols() <= m_matData.cols()) {
        m_matData.block(0, m_iMatDataSampleIterator, matData.rows(), matData.cols()) = matData.cast<double>();

        m_iMatDataSampleIterator += matData.cols();
    } else {
        m_matData.block(0, m_iMatDataSampleIterator, matData.rows(), m_matData.cols()-m_iMatDataSampleIterator) = matData.block(0, 0, matData.rows(), m_matData.cols()-m_iMatDataSampleIterator).cast<double>();

        m_iMatDataSampleIterator = 0;
    }

    //qDebug() << "m_iMatDataSampleIterator" << m_iMatDataSampleIterator;

    if(m_iMatDataSampleIterator == m_matData.cols()) {
        m_iMatDataSampleIterator = 0;
        //qDebug()<<"Emit data";
        MatrixXd matEmit = m_matData.cast<double>();
        emit newDataAvailable(matEmit);
    }
}
<commit_msg>initialized unused member variables in constructor -- cov186880<commit_after>//=============================================================================================================
/**
* @file     natusproducer.cpp
* @author   Lorenz Esch <lorenz.esch@tu-ilmenau.de>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     June, 2018
*
* @section  LICENSE
*
* Copyright (C) 2018, Lorenz Esch and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
*       to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief    Contains the definition of the NatusProducer class.
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "natusproducer.h"

#include <iostream>

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QDebug>
#include <QDataStream>
#include <QScopedArrayPointer>

//*************************************************************************************************************
//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace NATUSPLUGIN;
using namespace Eigen;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

NatusProducer::NatusProducer(int iBlockSize, int iChannelSize, QObject *parent)
: QObject(parent)
, m_iMatDataSampleIterator(1)
{
    //qRegisterMetaType<Eigen::MatrixXd>();

    //Init socket
    m_pUdpSocket = QSharedPointer<QUdpSocket>(new QUdpSocket(this));
    m_pUdpSocket->bind(QHostAddress::AnyIPv4, 50000);
    connect(m_pUdpSocket.data(), &QUdpSocket::readyRead,
            this, &NatusProducer::readPendingDatagrams);

    m_matData.resize(iChannelSize, iBlockSize);
    m_fSampleFreq = 0;
    m_fChannelSize = 0;
}

//*************************************************************************************************************

void NatusProducer::readPendingDatagrams()
{
    while (m_pUdpSocket->hasPendingDatagrams()) {
        QNetworkDatagram datagram = m_pUdpSocket->receiveDatagram();
        //qDebug() << "Datagram on port 50000 from IP "<<datagram.senderAddress();
        processDatagram(datagram);
    }
}

//*************************************************************************************************************

void NatusProducer::processDatagram(const QNetworkDatagram &datagram)
{
    QByteArray data = datagram.data();
    QDataStream stream(data);

    // Read info
    float fPackageNumber, fNumberSamples, fNumberChannels;

    char cInfo[3*sizeof(float)];
    stream.readRawData(cInfo, sizeof(cInfo));

    float* fInfo = reinterpret_cast<float*>(cInfo);

    fPackageNumber = fInfo[0];
    fNumberSamples = fInfo[1];
    fNumberChannels = fInfo[2];

//    // Print info about received data
//    qDebug()<<"fPackageNumber "<<fPackageNumber;
//    qDebug()<<"fNumberSamples "<<fNumberSamples;
//    qDebug()<<"fNumberChannels "<<fNumberChannels;
//    qDebug()<<"data.size() "<<data.size();
//    qDebug()<<"data.size() "<<data.size();
//    qDebug()<<"data.size() "<<data.size();

    // Read actual data
    int iDataSize = int(fNumberSamples * fNumberChannels);
    QScopedArrayPointer<char> cData(new char[iDataSize*sizeof(float)]);
    //char *cData = new char[iDataSize*sizeof(float)];
    stream.readRawData(cData.data(), iDataSize*sizeof(float));

    float* fData = reinterpret_cast<float*>(cData.data());

    //Get data
    Eigen::MatrixXf matData;
    matData.resize(fNumberChannels, fNumberSamples);
    int itr = 0;
    for(int j = 0; j < fNumberSamples; ++j) {
        for(int i = 0; i < fNumberChannels; ++i) {
            matData(i,j) = fData[itr++]/10e06;
        }
    }

    if(m_iMatDataSampleIterator+matData.cols() <= m_matData.cols()) {
        m_matData.block(0, m_iMatDataSampleIterator, matData.rows(), matData.cols()) = matData.cast<double>();

        m_iMatDataSampleIterator += matData.cols();
    } else {
        m_matData.block(0, m_iMatDataSampleIterator, matData.rows(), m_matData.cols()-m_iMatDataSampleIterator) = matData.block(0, 0, matData.rows(), m_matData.cols()-m_iMatDataSampleIterator).cast<double>();

        m_iMatDataSampleIterator = 0;
    }

    //qDebug() << "m_iMatDataSampleIterator" << m_iMatDataSampleIterator;

    if(m_iMatDataSampleIterator == m_matData.cols()) {
        m_iMatDataSampleIterator = 0;
        //qDebug()<<"Emit data";
        MatrixXd matEmit = m_matData.cast<double>();
        emit newDataAvailable(matEmit);
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <time.h>
#include <vector>

#include "aggregate_bandwidth.cpp"
#include "aggregate_bandwidth.hpp"
#include "bytes_object.hpp"
#include "log_results.hpp"
#include <derecho/conf/conf.hpp>
#include <derecho/core/derecho.hpp>
#include <derecho/mutils-serialization/SerializationSupport.hpp>
#include <derecho/persistent/Persistent.hpp>

using std::endl;
using test::Bytes;

/**
 * RPC Object with a single function that accepts a string
 */
class TestObject {
public:
    void fun(const std::string& words) {
    }

    void bytes_fun(const Bytes& bytes) {
    }

    bool finishing_call(int x) {
        return true;
    }

    REGISTER_RPC_FUNCTIONS(TestObject, fun, bytes_fun, finishing_call);
};

struct exp_result {
    int num_nodes;
    long long unsigned int max_msg_size;
    unsigned int window_size;
    int count;
    double avg_msec;
    double avg_gbps;
    double avg_ops;

    void print(std::ofstream& fout) {
        fout << num_nodes << " "
             << max_msg_size << " " << window_size << " "
             << count << " "
             << avg_msec << " " << avg_gbps << " "
             << avg_ops << endl;
    }
};

#define DEFAULT_PROC_NAME "typed_bw_test"

int main(int argc, char* argv[]) {
    int dashdash_pos = argc - 1;
    while(dashdash_pos > 0) {
        if(strcmp(argv[dashdash_pos], "--") == 0) {
            break;
        }
        dashdash_pos--;
    }

    if((argc - dashdash_pos) < 3) {
        std::cout << "Invalid command line arguments." << std::endl;
        std::cout << "USAGE: " << argv[0] << " [ derecho-config-list -- ] <num_of_nodes> <count> [proc_name]" << std::endl;
        std::cout << "Note: proc_name sets the process's name as displayed in ps and pkill commands, default is " DEFAULT_PROC_NAME << std::endl;
        return -1;
    }

    derecho::Conf::initialize(argc, argv);

    int num_of_nodes = std::stoi(argv[dashdash_pos + 1]);
    uint64_t max_msg_size = derecho::getConfUInt64(CONF_SUBGROUP_DEFAULT_MAX_PAYLOAD_SIZE);
    int count = std::stoi(argv[dashdash_pos + 2]);
    if(dashdash_pos + 3 < argc) {
        pthread_setname_np(pthread_self(), argv[dashdash_pos + 3]);
    } else {
        pthread_setname_np(pthread_self(), DEFAULT_PROC_NAME);
    }

    derecho::SubgroupInfo subgroup_info{[num_of_nodes](
                                                const std::vector<std::type_index>& subgroup_type_order,
                                                const std::unique_ptr<derecho::View>& prev_view, derecho::View& curr_view) {
        if(curr_view.num_members < num_of_nodes) {
            std::cout << "not enough members yet:" << curr_view.num_members << " < " << num_of_nodes << std::endl;
            throw derecho::subgroup_provisioning_exception();
        }
        derecho::subgroup_shard_layout_t subgroup_layout(1);

        std::vector<uint32_t> members(num_of_nodes);
        for(int i = 0; i < num_of_nodes; i++) {
            members[i] = i;
        }

        subgroup_layout[0].emplace_back(curr_view.make_subview(members));
        curr_view.next_unassigned_rank = std::max(curr_view.next_unassigned_rank, num_of_nodes);
        derecho::subgroup_allocation_map_t subgroup_allocation;
        subgroup_allocation.emplace(std::type_index(typeid(TestObject)), std::move(subgroup_layout));
        return subgroup_allocation;
    }};

    auto ba_factory = [](persistent::PersistentRegistry*, derecho::subgroup_id_t) { return std::make_unique<TestObject>(); };

    derecho::Group<TestObject> group({}, subgroup_info, {}, std::vector<derecho::view_upcall_t>{}, ba_factory);
    std::cout << "Finished constructing/joining Group" << std::endl;

    derecho::Replicated<TestObject>& handle = group.get_subgroup<TestObject>();
    //std::string str_1k(max_msg_size, 'x');
    char* bbuf = (char*)malloc(max_msg_size);
    bzero(bbuf, max_msg_size);
    Bytes bytes(bbuf, max_msg_size);

    struct timespec t1, t2;
    clock_gettime(CLOCK_REALTIME, &t1);

    for(int i = 0; i < count; i++) {
        //handle.ordered_send<RPC_NAME(fun)>(str_1k);
        handle.ordered_send<RPC_NAME(bytes_fun)>(bytes);
    }

    auto members_order = group.get_members();
    uint32_t node_rank = group.get_my_rank();
    if(node_rank == 0) {
        derecho::rpc::QueryResults<bool> results = handle.ordered_send<RPC_NAME(finishing_call)>(0);
        std::cout << "waiting for response..." << std::endl;
#pragma GCC diagnostic ignored "-Wunused-variable"
        decltype(results)::ReplyMap& replies = results.get();
#pragma GCC diagnostic pop
    }

    clock_gettime(CLOCK_REALTIME, &t2);
    free(bbuf);

    int64_t nsec = ((int64_t)t2.tv_sec - t1.tv_sec) * 1000000000 + t2.tv_nsec - t1.tv_nsec;
    double msec = (double)nsec / 1000000;
    double thp_gbps = ((double)count * max_msg_size * 8) / nsec;
    double thp_ops = ((double)count * 1000000000) / nsec;
    std::cout << "timespan:" << msec << " millisecond." << std::endl;
    std::cout << "throughput:" << thp_gbps << "Gbit/s." << std::endl;
    std::cout << "throughput:" << thp_ops << "ops." << std::endl;

    // aggregate bandwidth from all nodes
    double avg_msec = aggregate_bandwidth(members_order, members_order[node_rank], msec);
    double avg_gbps = aggregate_bandwidth(members_order, members_order[node_rank], thp_gbps);
    double avg_ops = aggregate_bandwidth(members_order, members_order[node_rank], thp_ops);

    if(node_rank == 0) {
        log_results(exp_result{num_of_nodes, max_msg_size,
                               derecho::getConfUInt32(CONF_SUBGROUP_DEFAULT_WINDOW_SIZE), count,
                               avg_msec, avg_gbps, avg_ops},
                    "data_derecho_typed_subgroup_bw");
    }

    group.barrier_sync();
    group.leave();
}
<commit_msg>Now using TwoResultsSST from aggregate_bw<commit_after>#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <time.h>
#include <vector>

#include "aggregate_bandwidth.cpp"
#include "aggregate_bandwidth.hpp"
#include "bytes_object.hpp"
#include "log_results.hpp"
#include <derecho/conf/conf.hpp>
#include <derecho/core/derecho.hpp>
#include <derecho/mutils-serialization/SerializationSupport.hpp>
#include <derecho/persistent/Persistent.hpp>

using std::endl;
using test::Bytes;

/**
 * RPC Object with a single function that accepts a string
 */
class TestObject {
public:
    void fun(const std::string& words) {
    }

    void bytes_fun(const Bytes& bytes) {
    }

    bool finishing_call(int x) {
        return true;
    }

    REGISTER_RPC_FUNCTIONS(TestObject, fun, bytes_fun, finishing_call);
};

struct exp_result {
    int num_nodes;
    long long unsigned int max_msg_size;
    unsigned int window_size;
    int count;
    double avg_msec;
    double avg_gbps;
    double avg_ops;

    void print(std::ofstream& fout) {
        fout << num_nodes << " "
             << max_msg_size << " " << window_size << " "
             << count << " "
             << avg_msec << " " << avg_gbps << " "
             << avg_ops << endl;
    }
};

#define DEFAULT_PROC_NAME "typed_bw_test"

int main(int argc, char* argv[]) {
    int dashdash_pos = argc - 1;
    while(dashdash_pos > 0) {
        if(strcmp(argv[dashdash_pos], "--") == 0) {
            break;
        }
        dashdash_pos--;
    }

    if((argc - dashdash_pos) < 3) {
        std::cout << "Invalid command line arguments." << std::endl;
        std::cout << "USAGE: " << argv[0] << " [ derecho-config-list -- ] <num_of_nodes> <count> [proc_name]" << std::endl;
        std::cout << "Note: proc_name sets the process's name as displayed in ps and pkill commands, default is " DEFAULT_PROC_NAME << std::endl;
        return -1;
    }

    derecho::Conf::initialize(argc, argv);

    int num_of_nodes = std::stoi(argv[dashdash_pos + 1]);
    uint64_t max_msg_size = derecho::getConfUInt64(CONF_SUBGROUP_DEFAULT_MAX_PAYLOAD_SIZE);
    int count = std::stoi(argv[dashdash_pos + 2]);
    if(dashdash_pos + 3 < argc) {
        pthread_setname_np(pthread_self(), argv[dashdash_pos + 3]);
    } else {
        pthread_setname_np(pthread_self(), DEFAULT_PROC_NAME);
    }

    derecho::SubgroupInfo subgroup_info{[num_of_nodes](
                                                const std::vector<std::type_index>& subgroup_type_order,
                                                const std::unique_ptr<derecho::View>& prev_view, derecho::View& curr_view) {
        if(curr_view.num_members < num_of_nodes) {
            std::cout << "not enough members yet:" << curr_view.num_members << " < " << num_of_nodes << std::endl;
            throw derecho::subgroup_provisioning_exception();
        }
        derecho::subgroup_shard_layout_t subgroup_layout(1);

        std::vector<uint32_t> members(num_of_nodes);
        for(int i = 0; i < num_of_nodes; i++) {
            members[i] = i;
        }

        subgroup_layout[0].emplace_back(curr_view.make_subview(members));
        curr_view.next_unassigned_rank = std::max(curr_view.next_unassigned_rank, num_of_nodes);
        derecho::subgroup_allocation_map_t subgroup_allocation;
        subgroup_allocation.emplace(std::type_index(typeid(TestObject)), std::move(subgroup_layout));
        return subgroup_allocation;
    }};

    auto ba_factory = [](persistent::PersistentRegistry*, derecho::subgroup_id_t) { return std::make_unique<TestObject>(); };

    derecho::Group<TestObject> group({}, subgroup_info, {}, std::vector<derecho::view_upcall_t>{}, ba_factory);
    std::cout << "Finished constructing/joining Group" << std::endl;

    derecho::Replicated<TestObject>& handle = group.get_subgroup<TestObject>();
    //std::string str_1k(max_msg_size, 'x');
    char* bbuf = (char*)malloc(max_msg_size);
    bzero(bbuf, max_msg_size);
    Bytes bytes(bbuf, max_msg_size);

    struct timespec t1, t2;
    clock_gettime(CLOCK_REALTIME, &t1);

    for(int i = 0; i < count; i++) {
        //handle.ordered_send<RPC_NAME(fun)>(str_1k);
        handle.ordered_send<RPC_NAME(bytes_fun)>(bytes);
    }

    auto members_order = group.get_members();
    uint32_t node_rank = group.get_my_rank();
    if(node_rank == 0) {
        derecho::rpc::QueryResults<bool> results = handle.ordered_send<RPC_NAME(finishing_call)>(0);
        std::cout << "waiting for response..." << std::endl;
#pragma GCC diagnostic ignored "-Wunused-variable"
        decltype(results)::ReplyMap& replies = results.get();
#pragma GCC diagnostic pop
    }

    clock_gettime(CLOCK_REALTIME, &t2);
    free(bbuf);

    int64_t nsec = ((int64_t)t2.tv_sec - t1.tv_sec) * 1000000000 + t2.tv_nsec - t1.tv_nsec;
    double msec = (double)nsec / 1000000;
    double thp_gbps = ((double)count * max_msg_size * 8) / nsec;
    double thp_ops = ((double)count * 1000000000) / nsec;
    std::cout << "timespan:" << msec << " millisecond." << std::endl;
    std::cout << "throughput:" << thp_gbps << "Gbit/s." << std::endl;
    std::cout << "throughput:" << thp_ops << "ops." << std::endl;

    // aggregate bandwidth from all nodes
    std::pair<double, double> bw_laten(thp_gbps,msec);

    bw_laten = aggregate_bandwidth(members_order, members_order[node_rank], bw_laten);

    double avg_gbps = bw_laten.first;
    double avg_msec = bw_laten.second;

    if(node_rank == 0) {
        log_results(exp_result{num_of_nodes, max_msg_size,
                               derecho::getConfUInt32(CONF_SUBGROUP_DEFAULT_WINDOW_SIZE), count,
                               avg_msec, avg_gbps},
                    "data_derecho_typed_subgroup_bw");
    }

    group.barrier_sync();
    group.leave();
}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// transaction_manager_factory.h
//
// Identification: src/backend/concurrency/transaction_manager_factory.h
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "transaction_manager_factory.h"

namespace peloton {
namespace concurrency {
ConcurrencyType TransactionManagerFactory::protocol_ =
    CONCURRENCY_TYPE_PESSIMISTIC;
IsolationLevelType TransactionManagerFactory::isolation_level_ =
    ISOLATION_LEVEL_TYPE_FULL;
}
}
<commit_msg>Change default txn manager to occ<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// transaction_manager_factory.h
//
// Identification: src/backend/concurrency/transaction_manager_factory.h
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "transaction_manager_factory.h"

namespace peloton {
namespace concurrency {
ConcurrencyType TransactionManagerFactory::protocol_ =
    CONCURRENCY_TYPE_OPTIMISTIC;
IsolationLevelType TransactionManagerFactory::isolation_level_ =
    ISOLATION_LEVEL_TYPE_FULL;
}
}
<|endoftext|>


<commit_before>#include "rhodes.h"
#include "WebSocket.h"

#include "logging/RhoLog.h"
#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "WebSocket_impl"

#define WEBSOCKET_FACTORY_CLASS "com.websocket.WebSocketFactory"

extern "C" void Init_WebSocket_API(void);

extern "C" void Init_WebSocket(void)
{
    RAWTRACE(__FUNCTION__);

    JNIEnv *env = jnienv();
    if(env)
    {
        jclass cls = rho_find_class(env, WEBSOCKET_FACTORY_CLASS);
        if(!cls)
        {
            RAWLOG_ERROR1("Failed to find java class: %s", WEBSOCKET_FACTORY_CLASS);
            return;
        }
        jmethodID midFactory = env->GetMethodID(cls, "<init>", "()V");
        if(!midFactory)
        {
            RAWLOG_ERROR1("Failed to get constructor for java class %s", WEBSOCKET_FACTORY_CLASS);
            return;
        }
        jobject jFactory = env->NewObject(cls, midFactory);
        if(env->IsSameObject(jFactory, NULL))
        {
            RAWLOG_ERROR1("Failed to create %s instance", WEBSOCKET_FACTORY_CLASS);
            return;
        }

        RAWTRACE("Initializing Java factory");

        CWebSocketBase::setJavaFactory(env, jFactory);

        RAWTRACE("Deleting JNI reference");

        env->DeleteLocalRef(jFactory);

        RAWTRACE("Initializing API");

        Init_WebSocket_API();

        RAWTRACE("Init_WebSocket succeeded");
    }
    else
    {
        RAWLOG_ERROR("Failed to initialize WebSocket API: jnienv() is failed");
    }

}

extern "C" void Init_WebSocket_extension() {
    Init_WebSocket();
}
<commit_msg>WebSocket: fixed namespace<commit_after>#include "rhodes.h"
#include "WebSocket.h"

#include "logging/RhoLog.h"
#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "WebSocket_impl"

#define WEBSOCKET_FACTORY_CLASS "com.websocket.WebSocketFactory"

extern "C" void Init_WebSocket_API(void);

extern "C" void Init_WebSocket(void)
{
    RAWTRACE(__FUNCTION__);

    JNIEnv *env = jnienv();
    if(env)
    {
        jclass cls = rho_find_class(env, WEBSOCKET_FACTORY_CLASS);
        if(!cls)
        {
            RAWLOG_ERROR1("Failed to find java class: %s", WEBSOCKET_FACTORY_CLASS);
            return;
        }
        jmethodID midFactory = env->GetMethodID(cls, "<init>", "()V");
        if(!midFactory)
        {
            RAWLOG_ERROR1("Failed to get constructor for java class %s", WEBSOCKET_FACTORY_CLASS);
            return;
        }
        jobject jFactory = env->NewObject(cls, midFactory);
        if(env->IsSameObject(jFactory, NULL))
        {
            RAWLOG_ERROR1("Failed to create %s instance", WEBSOCKET_FACTORY_CLASS);
            return;
        }

        RAWTRACE("Initializing Java factory");

        rho::CWebSocketBase::setJavaFactory(env, jFactory);

        RAWTRACE("Deleting JNI reference");

        env->DeleteLocalRef(jFactory);

        RAWTRACE("Initializing API");

        Init_WebSocket_API();

        RAWTRACE("Init_WebSocket succeeded");
    }
    else
    {
        RAWLOG_ERROR("Failed to initialize WebSocket API: jnienv() is failed");
    }

}

extern "C" void Init_WebSocket_extension() {
    Init_WebSocket();
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include "Lex.h"
#include "CmdInputFactor.h"
#include "GrammarAnalyzer.h"
#include "JZLogger.h"

TEST(GrammarAnalyzer, EnumBasic0)
{
  int argc = 2;
  char argv0[128] = {0},argv1[128] = {0};
  strcpy(argv0,"tester");
  strcpy(argv1,"./test/GrammarSample/enum_sample_0");
  char* argv[2] = {argv0,argv1};

	//analyze command line input
	CmdInputFactor::getInstance()->analyze(argc, argv);

	//now begin to analyze the files input from command line
	string toCompileFile = CmdInputFactor::getInstance()->getNextFile();

  Lex lex;

  lex.analyzeAFile(toCompileFile);

  LexRecList recList = lex.getRecList();

  GrammarAnalyzer grammar = GrammarAnalyzer(recList);

  JZSetLoggerLevel(JZ_LOG_DEBUG|JZ_LOG_TRACE);
  uint32 ret = grammar.doAnalyze();

  ASSERT_EQ(eGrmErrNoError, ret);

  JZSetLoggerLevel(JZ_LOG_TEST);

//  GrammarBlock* topBlock = grammar.getTopBlock();

//  ASSERT_EQ(true, topBlock != NULL);

//  EnumDefine* enumDefTest = dynamic_cast<EnumDefine*>( topBlock->getDataDef("test") );
//  ASSERT_EQ(true, enumDefTest != NULL);
//
//  ASSERT_EQ(true, enumDefTest->fieldExist("hello"));
//  ASSERT_EQ(true, enumDefTest->fieldExist("hi"));
//  ASSERT_EQ(true, enumDefTest->fieldExist("nono"));

//  EnumDefine* enumDefTest1 = dynamic_cast<EnumDefine*>( topBlock->getDataDef("test1") );
//  ASSERT_EQ(true, enumDefTest1 != NULL);

//  ASSERT_EQ(true, enumDefTest1->fieldExist("no"));
//  ASSERT_EQ(true, enumDefTest1->fieldExist("yes"));
}

TEST(GrammarAnalyzer, EnumBasic1)
{
  int argc = 2;
  char argv0[128] = {0},argv1[128] = {0};
  strcpy(argv0,"tester");
  strcpy(argv1,"./test/GrammarSample/enum_sample_1");
  char* argv[2] = {argv0,argv1};

	//analyze command line input
	CmdInputFactor::getInstance()->analyze(argc, argv);

	//now begin to analyze the files input from command line
	string toCompileFile = CmdInputFactor::getInstance()->getNextFile();

  Lex lex;

  lex.analyzeAFile(toCompileFile);

  LexRecList recList = lex.getRecList();

//  GrammarAnalyzer grammar = GrammarAnalyzer(recList);

//  JZSetLoggerLevel(JZ_LOG_DEBUG|JZ_LOG_TRACE);
//  uint32 ret = grammar.doAnalyze();

//  ASSERT_EQ(eGrmErrNoError, ret);

  JZSetLoggerLevel(JZ_LOG_TEST);

//  GrammarBlock* topBlock = grammar.getTopBlock();

//  ASSERT_EQ(true, topBlock != NULL);

//  EnumDefine* enumDefTest = dynamic_cast<EnumDefine*>( topBlock->getDataDef("test") );
//  ASSERT_EQ(true, enumDefTest != NULL);
//
//  ASSERT_EQ(true, enumDefTest->fieldExist("hello"));
//  ASSERT_EQ(true, enumDefTest->fieldExist("hi"));
//  ASSERT_EQ(true, enumDefTest->fieldExist("nono"));

//  EnumDefine* enumDefTest1 = dynamic_cast<EnumDefine*>( topBlock->getDataDef("test1") );
//  ASSERT_EQ(true, enumDefTest1 != NULL);

//  ASSERT_EQ(true, enumDefTest1->fieldExist("no"));
//  ASSERT_EQ(true, enumDefTest1->fieldExist("yes"));
}

//test with attributes
TEST(GrammarAnalyzer, EnumAttributes)
{
  int argc = 2;
  char argv0[128] = {0},argv1[128] = {0};
  strcpy(argv0,"tester");
  strcpy(argv1,"./test/GrammarSample/enum_sample_2");
  char* argv[2] = {argv0,argv1};

	//analyze command line input
	CmdInputFactor::getInstance()->analyze(argc, argv);

	//now begin to analyze the files input from command line
	string toCompileFile = CmdInputFactor::getInstance()->getNextFile();

  Lex lex;

  lex.analyzeAFile(toCompileFile);

  LexRecList recList = lex.getRecList();

//  GrammarAnalyzer grammar = GrammarAnalyzer(recList);

//  JZSetLoggerLevel(JZ_LOG_DEBUG|JZ_LOG_TRACE);
//  uint32 ret = grammar.doAnalyze();
  JZSetLoggerLevel(JZ_LOG_TEST);

//  GrammarBlock* topBlock = grammar.getTopBlock();

//  ASSERT_EQ(true, topBlock != NULL);

//  EnumDefine* enumDefTest = dynamic_cast<EnumDefine*>( topBlock->getDataDef("test") );
//  ASSERT_EQ(true, enumDefTest != NULL);

//  ASSERT_EQ(true, enumDefTest->fieldExist("hello"));
}
<commit_msg>reopen the enum test<commit_after>#include <gtest/gtest.h>
#include "Lex.h"
#include "CmdInputFactor.h"
#include "GrammarAnalyzer.h"
#include "JZLogger.h"

TEST(GrammarAnalyzer, EnumBasic0)
{
  int argc = 2;
  char argv0[128] = {0},argv1[128] = {0};
  strcpy(argv0,"tester");
  strcpy(argv1,"./test/GrammarSample/enum_sample_0");
  char* argv[2] = {argv0,argv1};

	//analyze command line input
	CmdInputFactor::getInstance()->analyze(argc, argv);

	//now begin to analyze the files input from command line
	string toCompileFile = CmdInputFactor::getInstance()->getNextFile();

  Lex lex;

  lex.analyzeAFile(toCompileFile);

  LexRecList recList = lex.getRecList();

  GrammarAnalyzer grammar = GrammarAnalyzer(recList);

  JZSetLoggerLevel(JZ_LOG_DEBUG|JZ_LOG_TRACE);
  uint32 ret = grammar.doAnalyze();

  ASSERT_EQ(eGrmErrNoError, ret);

  JZSetLoggerLevel(JZ_LOG_TEST);

//  GrammarBlock* topBlock = grammar.getTopBlock();

//  ASSERT_EQ(true, topBlock != NULL);

//  EnumDefine* enumDefTest = dynamic_cast<EnumDefine*>( topBlock->getDataDef("test") );
//  ASSERT_EQ(true, enumDefTest != NULL);
//
//  ASSERT_EQ(true, enumDefTest->fieldExist("hello"));
//  ASSERT_EQ(true, enumDefTest->fieldExist("hi"));
//  ASSERT_EQ(true, enumDefTest->fieldExist("nono"));

//  EnumDefine* enumDefTest1 = dynamic_cast<EnumDefine*>( topBlock->getDataDef("test1") );
//  ASSERT_EQ(true, enumDefTest1 != NULL);

//  ASSERT_EQ(true, enumDefTest1->fieldExist("no"));
//  ASSERT_EQ(true, enumDefTest1->fieldExist("yes"));
}

TEST(GrammarAnalyzer, EnumBasic1)
{
  int argc = 2;
  char argv0[128] = {0},argv1[128] = {0};
  strcpy(argv0,"tester");
  strcpy(argv1,"./test/GrammarSample/enum_sample_1");
  char* argv[2] = {argv0,argv1};

	//analyze command line input
	CmdInputFactor::getInstance()->analyze(argc, argv);

	//now begin to analyze the files input from command line
	string toCompileFile = CmdInputFactor::getInstance()->getNextFile();

  Lex lex;

  lex.analyzeAFile(toCompileFile);

  LexRecList recList = lex.getRecList();

  GrammarAnalyzer grammar = GrammarAnalyzer(recList);

  JZSetLoggerLevel(JZ_LOG_DEBUG|JZ_LOG_TRACE);
  uint32 ret = grammar.doAnalyze();

  ASSERT_EQ(eGrmErrNoError, ret);

  JZSetLoggerLevel(JZ_LOG_TEST);

//  GrammarBlock* topBlock = grammar.getTopBlock();

//  ASSERT_EQ(true, topBlock != NULL);

//  EnumDefine* enumDefTest = dynamic_cast<EnumDefine*>( topBlock->getDataDef("test") );
//  ASSERT_EQ(true, enumDefTest != NULL);
//
//  ASSERT_EQ(true, enumDefTest->fieldExist("hello"));
//  ASSERT_EQ(true, enumDefTest->fieldExist("hi"));
//  ASSERT_EQ(true, enumDefTest->fieldExist("nono"));

//  EnumDefine* enumDefTest1 = dynamic_cast<EnumDefine*>( topBlock->getDataDef("test1") );
//  ASSERT_EQ(true, enumDefTest1 != NULL);

//  ASSERT_EQ(true, enumDefTest1->fieldExist("no"));
//  ASSERT_EQ(true, enumDefTest1->fieldExist("yes"));
}

//test with attributes
TEST(GrammarAnalyzer, EnumAttributes)
{
  int argc = 2;
  char argv0[128] = {0},argv1[128] = {0};
  strcpy(argv0,"tester");
  strcpy(argv1,"./test/GrammarSample/enum_sample_2");
  char* argv[2] = {argv0,argv1};

	//analyze command line input
	CmdInputFactor::getInstance()->analyze(argc, argv);

	//now begin to analyze the files input from command line
	string toCompileFile = CmdInputFactor::getInstance()->getNextFile();

  Lex lex;

  lex.analyzeAFile(toCompileFile);

  LexRecList recList = lex.getRecList();

  GrammarAnalyzer grammar = GrammarAnalyzer(recList);

  JZSetLoggerLevel(JZ_LOG_DEBUG|JZ_LOG_TRACE);
  uint32 ret = grammar.doAnalyze();
  ASSERT_EQ(eGrmErrNoError, ret);
  JZSetLoggerLevel(JZ_LOG_TEST);

//  GrammarBlock* topBlock = grammar.getTopBlock();

//  ASSERT_EQ(true, topBlock != NULL);

//  EnumDefine* enumDefTest = dynamic_cast<EnumDefine*>( topBlock->getDataDef("test") );
//  ASSERT_EQ(true, enumDefTest != NULL);

//  ASSERT_EQ(true, enumDefTest->fieldExist("hello"));
}
<|endoftext|>


<commit_before>/*
 * This program is just for personal experiments here on AVR features and C++ stuff
 * to check compilation and link of FastArduino port and pin API.
 * It does not do anything interesting as far as hardware is concerned.
 */

#include <fastarduino/boards/board.h>
#include <fastarduino/gpio.h>
#include <fastarduino/time.h>
#include <fastarduino/realtime_timer.h>
#include <fastarduino/utilities.h>
#include <fastarduino/flash.h>
#include <fastarduino/devices/hcsr04.h>
#include <fastarduino/int.h>
#include <fastarduino/pci.h>

REGISTER_RTT_ISR(0)

static constexpr const board::DigitalPin TRIGGER = board::DigitalPin::D2_PD2;
static constexpr const board::DigitalPin ECHO = board::InterruptPin::D3_PD3_PCI2;
static constexpr const board::Timer TIMER = board::Timer::TIMER0;

using RTT = timer::RTT<TIMER>;
using SONAR = devices::sonar::HCSR04<TIMER, TRIGGER, ECHO>;

//#define REGISTER_HCSR04_PCI_ISR_METHOD(TIMER, PCI_NUM, TRIGGER, ECHO, HANDLER, CALLBACK)	\
//CHECK_PCI_PIN_(ECHO, PCI_NUM)																\
//ISR(CAT3(PCINT, PCI_NUM, _vect))															\
//{																							\
//	using SERVO_HANDLER = devices::sonar::HCSR04<TIMER, TRIGGER, ECHO >;					\
//	using SERVO_HOLDER = HANDLER_HOLDER_(SERVO_HANDLER);									\
//	auto handler = SERVO_HOLDER::handler();													\
//	handler->on_echo();																		\
//	if (handler->ready())																	\
//		CALL_HANDLER_(HANDLER, CALLBACK, uint16_t)(handler->latest_echo_us());				\
//}

class SonarListener
{
public:
	SonarListener(uint16_t min_mm):MIN_US{devices::sonar::distance_mm_to_echo_us(min_mm)}, led_{gpio::PinMode::OUTPUT}
	{
		interrupt::register_handler(*this);
	}

	void on_sonar(uint16_t echo_us)
	{
		if (echo_us && echo_us <= MIN_US)
			led_.set();
		else
			led_.clear();
	}

private:
	const uint16_t MIN_US;
	gpio::FastPinType<board::DigitalPin::LED>::TYPE led_;
};

REGISTER_HCSR04_PCI_ISR_METHOD(TIMER, 2, TRIGGER, ECHO, SonarListener, &SonarListener::on_sonar)

int main() __attribute__((OS_main));
int main()
{
	sei();

	SonarListener listener{150};

	RTT rtt;
	rtt.register_rtt_handler();
	rtt.begin();
	typename interrupt::PCIType<ECHO>::TYPE signal;
	signal.enable_pin<ECHO>();
	signal.enable();
	SONAR sensor{rtt};

	while (true)
	{
		sensor.async_echo();
		sensor.await_echo_us();
	}
}
<commit_msg>Remove duplicate macro from sonar experiment code.<commit_after>/*
 * This program is just for personal experiments here on AVR features and C++ stuff
 * to check compilation and link of FastArduino port and pin API.
 * It does not do anything interesting as far as hardware is concerned.
 */

#include <fastarduino/boards/board.h>
#include <fastarduino/gpio.h>
#include <fastarduino/time.h>
#include <fastarduino/realtime_timer.h>
#include <fastarduino/utilities.h>
#include <fastarduino/flash.h>
#include <fastarduino/devices/hcsr04.h>
#include <fastarduino/int.h>
#include <fastarduino/pci.h>

REGISTER_RTT_ISR(0)

static constexpr const board::DigitalPin TRIGGER = board::DigitalPin::D2_PD2;
static constexpr const board::DigitalPin ECHO = board::InterruptPin::D3_PD3_PCI2;
static constexpr const board::Timer TIMER = board::Timer::TIMER0;

using RTT = timer::RTT<TIMER>;
using SONAR = devices::sonar::HCSR04<TIMER, TRIGGER, ECHO>;

class SonarListener
{
public:
	SonarListener(uint16_t min_mm):MIN_US{devices::sonar::distance_mm_to_echo_us(min_mm)}, led_{gpio::PinMode::OUTPUT}
	{
		interrupt::register_handler(*this);
	}

	void on_sonar(uint16_t echo_us)
	{
		if (echo_us && echo_us <= MIN_US)
			led_.set();
		else
			led_.clear();
	}

private:
	const uint16_t MIN_US;
	gpio::FastPinType<board::DigitalPin::LED>::TYPE led_;
};

REGISTER_HCSR04_PCI_ISR_METHOD(TIMER, 2, TRIGGER, ECHO, SonarListener, &SonarListener::on_sonar)

int main() __attribute__((OS_main));
int main()
{
	sei();

	SonarListener listener{150};

	RTT rtt;
	rtt.register_rtt_handler();
	rtt.begin();
	typename interrupt::PCIType<ECHO>::TYPE signal;
	signal.enable_pin<ECHO>();
	signal.enable();
	SONAR sensor{rtt};

	while (true)
	{
		sensor.async_echo();
		sensor.await_echo_us();
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 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/ref_counted.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/extensions/extension_devtools_browsertest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/extension_tabs_module.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/extensions/extension_shelf.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/devtools_messages.h"
#include "chrome/common/extensions/extension_error_reporter.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/net_util.h"

// Looks for an ExtensionHost whose URL has the given path component (including
// leading slash).  Also verifies that the expected number of hosts are loaded.
static ExtensionHost* FindHostWithPath(ExtensionProcessManager* manager,
                                       const std::string& path,
                                       int expected_hosts) {
  ExtensionHost* host = NULL;
  int num_hosts = 0;
  for (ExtensionProcessManager::const_iterator iter = manager->begin();
       iter != manager->end(); ++iter) {
    if ((*iter)->GetURL().path() == path) {
      EXPECT_FALSE(host);
      host = *iter;
    }
    num_hosts++;
  }
  EXPECT_EQ(expected_hosts, num_hosts);
  EXPECT_TRUE(host);
  return host;
}

// Tests for the experimental timeline extensions API.
IN_PROC_BROWSER_TEST_F(ExtensionDevToolsBrowserTest, DISABLED_TimelineApi) {
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("devtools").AppendASCII("timeline_api")));

  // Get the ExtensionHost that is hosting our background page.
  ExtensionProcessManager* manager =
      browser()->profile()->GetExtensionProcessManager();
  ExtensionHost* host = FindHostWithPath(manager, "/background.html", 1);

  // Grab a handle to the DevToolsManager so we can forward messages to it.
  DevToolsManager* devtools_manager = DevToolsManager::GetInstance();

  // Grab the tab_id of whatever tab happens to be first.
  TabContents* tab_contents = browser()->tabstrip_model()->GetTabContentsAt(0);
  ASSERT_TRUE(tab_contents);
  int tab_id = ExtensionTabUtil::GetTabId(tab_contents);

  // Test setup.
  bool result = false;
  std::wstring register_listeners_js = StringPrintf(L"setListenersOnTab(%d)",
                                                    tab_id);
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      host->render_view_host(), L"", register_listeners_js, &result);
  EXPECT_TRUE(result);

  // Setting the events should have caused an ExtensionDevToolsBridge to be
  // registered for the tab's RenderViewHost.
  DevToolsClientHost* devtools_client_host =
      devtools_manager->GetDevToolsClientHostFor(
          tab_contents->render_view_host());
  ASSERT_TRUE(devtools_client_host);

  // Test onPageEvent event.
  result = false;

  DevToolsMessageData message_data;
  message_data.class_name = "ApuAgentDelegate";
  message_data.method_name = "DispatchToApu";
  message_data.arguments.push_back("");
  DevToolsClientMsg_RpcMessage pageEventMessage(message_data);
  devtools_client_host->SendMessageToClient(pageEventMessage);
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      host->render_view_host(), L"", L"testReceivePageEvent()", &result);
  EXPECT_TRUE(result);

  // Test onTabClose event.
  result = false;
  devtools_manager->UnregisterDevToolsClientHostFor(
      tab_contents->render_view_host());
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      host->render_view_host(), L"", L"testReceiveTabCloseEvent()", &result);
  EXPECT_TRUE(result);
}

// Tests that ref counting of listeners from multiple processes works.
IN_PROC_BROWSER_TEST_F(ExtensionDevToolsBrowserTest, ProcessRefCounting) {
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("devtools").AppendASCII("timeline_api")));

  // Get the ExtensionHost that is hosting our background page.
  ExtensionProcessManager* manager =
      browser()->profile()->GetExtensionProcessManager();
  ExtensionHost* host_one = FindHostWithPath(manager, "/background.html", 1);

  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("devtools").AppendASCII("timeline_api_two")));
  ExtensionHost* host_two = FindHostWithPath(manager,
                                             "/background_two.html", 2);

  DevToolsManager* devtools_manager = DevToolsManager::GetInstance();

  // Grab the tab_id of whatever tab happens to be first.
  TabContents* tab_contents = browser()->tabstrip_model()->GetTabContentsAt(0);
  ASSERT_TRUE(tab_contents);
  int tab_id = ExtensionTabUtil::GetTabId(tab_contents);

  // Test setup.
  bool result = false;
  std::wstring register_listeners_js = StringPrintf(L"setListenersOnTab(%d)",
                                                    tab_id);
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      host_one->render_view_host(), L"", register_listeners_js, &result);
  EXPECT_TRUE(result);

  // Setting the event listeners should have caused an ExtensionDevToolsBridge
  // to be registered for the tab's RenderViewHost.
  ASSERT_TRUE(devtools_manager->GetDevToolsClientHostFor(
      tab_contents->render_view_host()));

  // Register listeners from the second extension as well.
  std::wstring script = StringPrintf(L"registerListenersForTab(%d)", tab_id);
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      host_two->render_view_host(), L"", script, &result);
  EXPECT_TRUE(result);

  // Removing the listeners from the first extension should leave the bridge
  // alive.
  result = false;
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      host_one->render_view_host(), L"", L"unregisterListeners()", &result);
  EXPECT_TRUE(result);
  ASSERT_TRUE(devtools_manager->GetDevToolsClientHostFor(
      tab_contents->render_view_host()));

  // Removing the listeners from the second extension should tear the bridge
  // down.
  result = false;
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      host_two->render_view_host(), L"", L"unregisterListeners()", &result);
  EXPECT_TRUE(result);
  ASSERT_FALSE(devtools_manager->GetDevToolsClientHostFor(
      tab_contents->render_view_host()));
}
<commit_msg>Reenable ExtensionDevToolsBrowserTest.TimelineApi<commit_after>// Copyright (c) 2009 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/ref_counted.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/extensions/extension_devtools_browsertest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/extension_tabs_module.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/extensions/extension_shelf.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/devtools_messages.h"
#include "chrome/common/extensions/extension_error_reporter.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/net_util.h"

// Looks for an ExtensionHost whose URL has the given path component (including
// leading slash).  Also verifies that the expected number of hosts are loaded.
static ExtensionHost* FindHostWithPath(ExtensionProcessManager* manager,
                                       const std::string& path,
                                       int expected_hosts) {
  ExtensionHost* host = NULL;
  int num_hosts = 0;
  for (ExtensionProcessManager::const_iterator iter = manager->begin();
       iter != manager->end(); ++iter) {
    if ((*iter)->GetURL().path() == path) {
      EXPECT_FALSE(host);
      host = *iter;
    }
    num_hosts++;
  }
  EXPECT_EQ(expected_hosts, num_hosts);
  EXPECT_TRUE(host);
  return host;
}

// Tests for the experimental timeline extensions API.
IN_PROC_BROWSER_TEST_F(ExtensionDevToolsBrowserTest, TimelineApi) {
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("devtools").AppendASCII("timeline_api")));

  // Get the ExtensionHost that is hosting our background page.
  ExtensionProcessManager* manager =
      browser()->profile()->GetExtensionProcessManager();
  ExtensionHost* host = FindHostWithPath(manager, "/background.html", 1);

  // Grab a handle to the DevToolsManager so we can forward messages to it.
  DevToolsManager* devtools_manager = DevToolsManager::GetInstance();

  // Grab the tab_id of whatever tab happens to be first.
  TabContents* tab_contents = browser()->tabstrip_model()->GetTabContentsAt(0);
  ASSERT_TRUE(tab_contents);
  int tab_id = ExtensionTabUtil::GetTabId(tab_contents);

  // Test setup.
  bool result = false;
  std::wstring register_listeners_js = StringPrintf(L"setListenersOnTab(%d)",
                                                    tab_id);
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      host->render_view_host(), L"", register_listeners_js, &result);
  EXPECT_TRUE(result);

  // Setting the events should have caused an ExtensionDevToolsBridge to be
  // registered for the tab's RenderViewHost.
  DevToolsClientHost* devtools_client_host =
      devtools_manager->GetDevToolsClientHostFor(
          tab_contents->render_view_host());
  ASSERT_TRUE(devtools_client_host);

  // Test onPageEvent event.
  result = false;

  DevToolsMessageData message_data;
  message_data.class_name = "ApuAgentDelegate";
  message_data.method_name = "DispatchToApu";
  message_data.arguments.push_back("");
  DevToolsClientMsg_RpcMessage pageEventMessage(message_data);
  devtools_client_host->SendMessageToClient(pageEventMessage);
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      host->render_view_host(), L"", L"testReceivePageEvent()", &result);
  EXPECT_TRUE(result);

  // Test onTabClose event.
  result = false;
  devtools_manager->UnregisterDevToolsClientHostFor(
      tab_contents->render_view_host());
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      host->render_view_host(), L"", L"testReceiveTabCloseEvent()", &result);
  EXPECT_TRUE(result);
}

// Tests that ref counting of listeners from multiple processes works.
IN_PROC_BROWSER_TEST_F(ExtensionDevToolsBrowserTest, ProcessRefCounting) {
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("devtools").AppendASCII("timeline_api")));

  // Get the ExtensionHost that is hosting our background page.
  ExtensionProcessManager* manager =
      browser()->profile()->GetExtensionProcessManager();
  ExtensionHost* host_one = FindHostWithPath(manager, "/background.html", 1);

  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("devtools").AppendASCII("timeline_api_two")));
  ExtensionHost* host_two = FindHostWithPath(manager,
                                             "/background_two.html", 2);

  DevToolsManager* devtools_manager = DevToolsManager::GetInstance();

  // Grab the tab_id of whatever tab happens to be first.
  TabContents* tab_contents = browser()->tabstrip_model()->GetTabContentsAt(0);
  ASSERT_TRUE(tab_contents);
  int tab_id = ExtensionTabUtil::GetTabId(tab_contents);

  // Test setup.
  bool result = false;
  std::wstring register_listeners_js = StringPrintf(L"setListenersOnTab(%d)",
                                                    tab_id);
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      host_one->render_view_host(), L"", register_listeners_js, &result);
  EXPECT_TRUE(result);

  // Setting the event listeners should have caused an ExtensionDevToolsBridge
  // to be registered for the tab's RenderViewHost.
  ASSERT_TRUE(devtools_manager->GetDevToolsClientHostFor(
      tab_contents->render_view_host()));

  // Register listeners from the second extension as well.
  std::wstring script = StringPrintf(L"registerListenersForTab(%d)", tab_id);
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      host_two->render_view_host(), L"", script, &result);
  EXPECT_TRUE(result);

  // Removing the listeners from the first extension should leave the bridge
  // alive.
  result = false;
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      host_one->render_view_host(), L"", L"unregisterListeners()", &result);
  EXPECT_TRUE(result);
  ASSERT_TRUE(devtools_manager->GetDevToolsClientHostFor(
      tab_contents->render_view_host()));

  // Removing the listeners from the second extension should tear the bridge
  // down.
  result = false;
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      host_two->render_view_host(), L"", L"unregisterListeners()", &result);
  EXPECT_TRUE(result);
  ASSERT_FALSE(devtools_manager->GetDevToolsClientHostFor(
      tab_contents->render_view_host()));
}
<|endoftext|>