<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   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 .
 */

#ifndef INCLUDED_CHART2_SOURCE_CONTROLLER_INC_DLG_CREATIONWIZARD_HXX
#define INCLUDED_CHART2_SOURCE_CONTROLLER_INC_DLG_CREATIONWIZARD_HXX

#include "ServiceMacros.hxx"
#include "TimerTriggeredControllerLock.hxx"
#include "TabPageNotifiable.hxx"

#include <com/sun/star/chart2/XChartDocument.hpp>
#include <svtools/roadmapwizard.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>

#include <boost/noncopyable.hpp>
#include <boost/scoped_ptr.hpp>

namespace chart
{

class RangeChooserTabPage;
class DataSourceTabPage;
class ChartTypeTemplateProvider;
class DialogModel;

class CreationWizard : public svt::RoadmapWizard, public TabPageNotifiable, private boost::noncopyable
{
public:
    CreationWizard( Window* pParent,
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::frame::XModel >& xChartModel
        , const ::com::sun::star::uno::Reference<
        ::com::sun::star::uno::XComponentContext >& xContext
        , sal_Int32 nOnePageOnlyIndex=-1 );//if nOnePageOnlyIndex is an index of an exsisting  page starting with 0, then only this page is displayed without next/previous and roadmap
    virtual ~CreationWizard();

    bool isClosable() { /*@todo*/ return m_bIsClosable;}

    // TabPageNotifiable
    virtual void setInvalidPage( TabPage * pTabPage ) SAL_OVERRIDE;
    virtual void setValidPage( TabPage * pTabPage ) SAL_OVERRIDE;

protected:
    virtual bool            leaveState( WizardState _nState ) SAL_OVERRIDE;
    virtual WizardState     determineNextState(WizardState nCurrentState) const SAL_OVERRIDE;
    virtual void            enterState(WizardState nState) SAL_OVERRIDE;

    virtual OUString        getStateDisplayName( WizardState nState ) const SAL_OVERRIDE;

private:
    //no default constructor
    CreationWizard();

    virtual svt::OWizardPage* createPage(WizardState nState) SAL_OVERRIDE;

    ::com::sun::star::uno::Reference<
                       ::com::sun::star::chart2::XChartDocument >   m_xChartModel;
    ::com::sun::star::uno::Reference<
                       ::com::sun::star::uno::XComponentContext>    m_xCC;
    bool m_bIsClosable;
    sal_Int32 m_nOnePageOnlyIndex;//if nOnePageOnlyIndex is an index of an exsisting page starting with 0, then only this page is displayed without next/previous and roadmap
    ChartTypeTemplateProvider*   m_pTemplateProvider;
    boost::scoped_ptr<DialogModel> m_pDialogModel;

    WizardState m_nFirstState;
    WizardState m_nLastState;

    TimerTriggeredControllerLock   m_aTimerTriggeredControllerLock;

//     RangeChooserTabPage * m_pRangeChooserTabePage;
//     DataSourceTabPage *   m_pDataSourceTabPage;
    bool                  m_bCanTravel;
};
} //namespace chart
#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>CreationWizard already inherits boost::noncopyable via OutputDevice<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   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 .
 */

#ifndef INCLUDED_CHART2_SOURCE_CONTROLLER_INC_DLG_CREATIONWIZARD_HXX
#define INCLUDED_CHART2_SOURCE_CONTROLLER_INC_DLG_CREATIONWIZARD_HXX

#include "ServiceMacros.hxx"
#include "TimerTriggeredControllerLock.hxx"
#include "TabPageNotifiable.hxx"

#include <com/sun/star/chart2/XChartDocument.hpp>
#include <svtools/roadmapwizard.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>

#include <boost/noncopyable.hpp>
#include <boost/scoped_ptr.hpp>

namespace chart
{

class RangeChooserTabPage;
class DataSourceTabPage;
class ChartTypeTemplateProvider;
class DialogModel;

class CreationWizard : public svt::RoadmapWizard, public TabPageNotifiable
{
public:
    CreationWizard( Window* pParent,
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::frame::XModel >& xChartModel
        , const ::com::sun::star::uno::Reference<
        ::com::sun::star::uno::XComponentContext >& xContext
        , sal_Int32 nOnePageOnlyIndex=-1 );//if nOnePageOnlyIndex is an index of an exsisting  page starting with 0, then only this page is displayed without next/previous and roadmap
    virtual ~CreationWizard();

    bool isClosable() { /*@todo*/ return m_bIsClosable;}

    // TabPageNotifiable
    virtual void setInvalidPage( TabPage * pTabPage ) SAL_OVERRIDE;
    virtual void setValidPage( TabPage * pTabPage ) SAL_OVERRIDE;

protected:
    virtual bool            leaveState( WizardState _nState ) SAL_OVERRIDE;
    virtual WizardState     determineNextState(WizardState nCurrentState) const SAL_OVERRIDE;
    virtual void            enterState(WizardState nState) SAL_OVERRIDE;

    virtual OUString        getStateDisplayName( WizardState nState ) const SAL_OVERRIDE;

private:
    //no default constructor
    CreationWizard();

    virtual svt::OWizardPage* createPage(WizardState nState) SAL_OVERRIDE;

    ::com::sun::star::uno::Reference<
                       ::com::sun::star::chart2::XChartDocument >   m_xChartModel;
    ::com::sun::star::uno::Reference<
                       ::com::sun::star::uno::XComponentContext>    m_xCC;
    bool m_bIsClosable;
    sal_Int32 m_nOnePageOnlyIndex;//if nOnePageOnlyIndex is an index of an exsisting page starting with 0, then only this page is displayed without next/previous and roadmap
    ChartTypeTemplateProvider*   m_pTemplateProvider;
    boost::scoped_ptr<DialogModel> m_pDialogModel;

    WizardState m_nFirstState;
    WizardState m_nLastState;

    TimerTriggeredControllerLock   m_aTimerTriggeredControllerLock;

//     RangeChooserTabPage * m_pRangeChooserTabePage;
//     DataSourceTabPage *   m_pDataSourceTabPage;
    bool                  m_bCanTravel;
};
} //namespace chart
#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/**
 / _____)             _              | |
( (____  _____ ____ _| |_ _____  ____| |__
 \____ \| ___ |    (_   _) ___ |/ ___)  _ \
 _____) ) ____| | | || |_| ____( (___| | | |
(______/|_____)_|_|_| \__)_____)\____)_| |_|
    (C)2013 Semtech
 ___ _____ _   ___ _  _____ ___  ___  ___ ___
/ __|_   _/_\ / __| |/ / __/ _ \| _ \/ __| __|
\__ \ | |/ _ \ (__| ' <| _| (_) |   / (__| _|
|___/ |_/_/ \_\___|_|\_\_| \___/|_|_\\___|___|
embedded.connectivity.solutions===============

Description: LoRaWAN stack layer that controls both MAC and PHY underneath

License: Revised BSD License, see LICENSE.TXT file include in the project

Maintainer: Miguel Luis ( Semtech ), Gregory Cristian ( Semtech ) and Daniel Jaeckle ( STACKFORCE )

Copyright (c) 2017, Arm Limited and affiliates.

SPDX-License-Identifier: BSD-3-Clause
*/

#include "LoRaMacChannelPlan.h"

LoRaMacChannelPlan::LoRaMacChannelPlan() : _lora_phy(NULL)
{
}

LoRaMacChannelPlan::~LoRaMacChannelPlan()
{
}

void LoRaMacChannelPlan::activate_channelplan_subsystem(LoRaPHY *phy)
{
    _lora_phy = phy;
}

lorawan_status_t LoRaMacChannelPlan::set_plan(const lorawan_channelplan_t& plan)
{
    channel_params_t mac_layer_ch_params;
    lorawan_status_t status;

    uint8_t max_num_channels;

    if (!_lora_phy->is_custom_channel_plan_supported()) {
        return LORAWAN_STATUS_SERVICE_UNKNOWN;
    }

    max_num_channels = _lora_phy->get_max_nb_channels();

    // check if user is setting more channels than supported
    if (plan.nb_channels > max_num_channels) {
        return LORAWAN_STATUS_PARAMETER_INVALID;
    }

    for (uint8_t i = 0; i < plan.nb_channels; i++) {

        mac_layer_ch_params.band = plan.channels[i].ch_param.band;

        mac_layer_ch_params.dr_range.fields.max = plan.channels[i].ch_param.dr_range.fields.max;
        mac_layer_ch_params.dr_range.fields.min = plan.channels[i].ch_param.dr_range.fields.min;
        mac_layer_ch_params.dr_range.value = plan.channels[i].ch_param.dr_range.value;
        mac_layer_ch_params.frequency = plan.channels[i].ch_param.frequency;
        mac_layer_ch_params.rx1_frequency = plan.channels[i].ch_param.rx1_frequency;

        status = _lora_phy->add_channel(&mac_layer_ch_params, plan.channels[i].id);

        if (status != LORAWAN_STATUS_OK) {
            return status;
        }
    }

    return LORAWAN_STATUS_OK;
}

lorawan_status_t LoRaMacChannelPlan::get_plan(lorawan_channelplan_t& plan,
                                              const channel_params_t* channel_list)
{
    uint8_t max_num_channels;
    uint16_t *channel_mask;
    uint8_t count = 0;

    if (!_lora_phy->is_custom_channel_plan_supported()) {
        return LORAWAN_STATUS_SERVICE_UNKNOWN;
    }

    max_num_channels = _lora_phy->get_max_nb_channels();

    channel_mask = _lora_phy->get_channel_mask(false);

    for (uint8_t i = 0; i < max_num_channels; i++) {
        // skip the channels which are not enabled
        if (_lora_phy->mask_bit_test(channel_mask, i) == 0) {
            continue;
        }

        // otherwise add them to the channel_plan struct
        plan.channels[count].id = i;
        plan.channels[count].ch_param.frequency = channel_list[i].frequency;
        plan.channels[count].ch_param.dr_range.value = channel_list[i].dr_range.value;
        plan.channels[count].ch_param.dr_range.fields.min = channel_list[i].dr_range.fields.min;
        plan.channels[count].ch_param.dr_range.fields.max = channel_list[i].dr_range.fields.max;
        plan.channels[count].ch_param.band = channel_list[i].band;
        plan.channels[count].ch_param.rx1_frequency = channel_list[i].rx1_frequency;
        count++;
    }

    plan.nb_channels = count;

    return LORAWAN_STATUS_OK;
}

lorawan_status_t LoRaMacChannelPlan::remove_plan()
{
    lorawan_status_t status = LORAWAN_STATUS_OK;

    uint8_t max_num_channels;
    uint16_t *channel_mask;
    uint16_t *default_channel_mask;

    if (!_lora_phy->is_custom_channel_plan_supported()) {
        return LORAWAN_STATUS_SERVICE_UNKNOWN;
    }

    max_num_channels = _lora_phy->get_max_nb_channels();

    channel_mask = _lora_phy->get_channel_mask(false);

    default_channel_mask = _lora_phy->get_channel_mask(true);

    for (uint8_t i = 0; i < max_num_channels; i++) {
        // skip any default channels
        if (_lora_phy->mask_bit_test(default_channel_mask, i) != 0) {
            continue;
        }

        // skip any channels which are not currently enabled
        if (_lora_phy->mask_bit_test(channel_mask, i) == 0) {
            continue;
        }

        status = remove_single_channel(i);

        if (status != LORAWAN_STATUS_OK) {
            return status;
        }
    }

    return status;
}

lorawan_status_t LoRaMacChannelPlan::remove_single_channel(uint8_t channel_id)
{
    uint8_t max_num_channels;

    if (!_lora_phy->is_custom_channel_plan_supported()) {
        return LORAWAN_STATUS_SERVICE_UNKNOWN;
    }

    max_num_channels = _lora_phy->get_max_nb_channels();

    // According to specification channel IDs start from 0 and last valid
    // channel ID is N-1 where N=MAX_NUM_CHANNELS.
    // So any ID which is larger or equal to the Max number of channels is invalid
    if (channel_id >= max_num_channels) {
        return LORAWAN_STATUS_PARAMETER_INVALID;
    }

    if (_lora_phy->remove_channel(channel_id) == false) {
        return LORAWAN_STATUS_PARAMETER_INVALID;
    }

    _lora_phy->put_radio_to_sleep();

    return LORAWAN_STATUS_OK;
}

<commit_msg>Remove useless extraction<commit_after>/**
 / _____)             _              | |
( (____  _____ ____ _| |_ _____  ____| |__
 \____ \| ___ |    (_   _) ___ |/ ___)  _ \
 _____) ) ____| | | || |_| ____( (___| | | |
(______/|_____)_|_|_| \__)_____)\____)_| |_|
    (C)2013 Semtech
 ___ _____ _   ___ _  _____ ___  ___  ___ ___
/ __|_   _/_\ / __| |/ / __/ _ \| _ \/ __| __|
\__ \ | |/ _ \ (__| ' <| _| (_) |   / (__| _|
|___/ |_/_/ \_\___|_|\_\_| \___/|_|_\\___|___|
embedded.connectivity.solutions===============

Description: LoRaWAN stack layer that controls both MAC and PHY underneath

License: Revised BSD License, see LICENSE.TXT file include in the project

Maintainer: Miguel Luis ( Semtech ), Gregory Cristian ( Semtech ) and Daniel Jaeckle ( STACKFORCE )

Copyright (c) 2017, Arm Limited and affiliates.

SPDX-License-Identifier: BSD-3-Clause
*/

#include "LoRaMacChannelPlan.h"

LoRaMacChannelPlan::LoRaMacChannelPlan() : _lora_phy(NULL)
{
}

LoRaMacChannelPlan::~LoRaMacChannelPlan()
{
}

void LoRaMacChannelPlan::activate_channelplan_subsystem(LoRaPHY *phy)
{
    _lora_phy = phy;
}

lorawan_status_t LoRaMacChannelPlan::set_plan(const lorawan_channelplan_t& plan)
{
    lorawan_status_t status;

    uint8_t max_num_channels;

    if (!_lora_phy->is_custom_channel_plan_supported()) {
        return LORAWAN_STATUS_SERVICE_UNKNOWN;
    }

    max_num_channels = _lora_phy->get_max_nb_channels();

    // check if user is setting more channels than supported
    if (plan.nb_channels > max_num_channels) {
        return LORAWAN_STATUS_PARAMETER_INVALID;
    }

    for (uint8_t i = 0; i < plan.nb_channels; i++) {
        status = _lora_phy->add_channel(&plan.channels[i].ch_param, plan.channels[i].id);

        if (status != LORAWAN_STATUS_OK) {
            return status;
        }
    }

    return LORAWAN_STATUS_OK;
}

lorawan_status_t LoRaMacChannelPlan::get_plan(lorawan_channelplan_t& plan,
                                              const channel_params_t* channel_list)
{
    uint8_t max_num_channels;
    uint16_t *channel_mask;
    uint8_t count = 0;

    if (!_lora_phy->is_custom_channel_plan_supported()) {
        return LORAWAN_STATUS_SERVICE_UNKNOWN;
    }

    max_num_channels = _lora_phy->get_max_nb_channels();

    channel_mask = _lora_phy->get_channel_mask(false);

    for (uint8_t i = 0; i < max_num_channels; i++) {
        // skip the channels which are not enabled
        if (_lora_phy->mask_bit_test(channel_mask, i) == 0) {
            continue;
        }

        // otherwise add them to the channel_plan struct
        plan.channels[count].id = i;
        plan.channels[count].ch_param.frequency = channel_list[i].frequency;
        plan.channels[count].ch_param.dr_range.value = channel_list[i].dr_range.value;
        plan.channels[count].ch_param.dr_range.fields.min = channel_list[i].dr_range.fields.min;
        plan.channels[count].ch_param.dr_range.fields.max = channel_list[i].dr_range.fields.max;
        plan.channels[count].ch_param.band = channel_list[i].band;
        plan.channels[count].ch_param.rx1_frequency = channel_list[i].rx1_frequency;
        count++;
    }

    plan.nb_channels = count;

    return LORAWAN_STATUS_OK;
}

lorawan_status_t LoRaMacChannelPlan::remove_plan()
{
    lorawan_status_t status = LORAWAN_STATUS_OK;

    uint8_t max_num_channels;
    uint16_t *channel_mask;
    uint16_t *default_channel_mask;

    if (!_lora_phy->is_custom_channel_plan_supported()) {
        return LORAWAN_STATUS_SERVICE_UNKNOWN;
    }

    max_num_channels = _lora_phy->get_max_nb_channels();

    channel_mask = _lora_phy->get_channel_mask(false);

    default_channel_mask = _lora_phy->get_channel_mask(true);

    for (uint8_t i = 0; i < max_num_channels; i++) {
        // skip any default channels
        if (_lora_phy->mask_bit_test(default_channel_mask, i) != 0) {
            continue;
        }

        // skip any channels which are not currently enabled
        if (_lora_phy->mask_bit_test(channel_mask, i) == 0) {
            continue;
        }

        status = remove_single_channel(i);

        if (status != LORAWAN_STATUS_OK) {
            return status;
        }
    }

    return status;
}

lorawan_status_t LoRaMacChannelPlan::remove_single_channel(uint8_t channel_id)
{
    uint8_t max_num_channels;

    if (!_lora_phy->is_custom_channel_plan_supported()) {
        return LORAWAN_STATUS_SERVICE_UNKNOWN;
    }

    max_num_channels = _lora_phy->get_max_nb_channels();

    // According to specification channel IDs start from 0 and last valid
    // channel ID is N-1 where N=MAX_NUM_CHANNELS.
    // So any ID which is larger or equal to the Max number of channels is invalid
    if (channel_id >= max_num_channels) {
        return LORAWAN_STATUS_PARAMETER_INVALID;
    }

    if (_lora_phy->remove_channel(channel_id) == false) {
        return LORAWAN_STATUS_PARAMETER_INVALID;
    }

    _lora_phy->put_radio_to_sleep();

    return LORAWAN_STATUS_OK;
}

<|endoftext|>


<commit_before>// Copyright (c) 2006-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.

// This file is here so other GLES2 related files can have a common set of
// includes where appropriate.

#include <windows.h>
#include <windowsx.h>
#include <shellapi.h>
#include <stdlib.h>
#include <stdio.h>
#include "base/ref_counted.h"
#include "base/shared_memory.h"
#include "base/scoped_ptr.h"
#include "gpu/command_buffer/service/gpu_processor.h"
#include "gpu/command_buffer/service/command_buffer_service.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "gpu/command_buffer/client/gles2_lib.h"
#include "gpu/command_buffer/client/gles2_demo_c.h"
#include "gpu/command_buffer/client/gles2_demo_cc.h"

using base::SharedMemory;
using command_buffer::GPUProcessor;
using command_buffer::CommandBufferService;
using command_buffer::gles2::GLES2CmdHelper;
using command_buffer::gles2::GLES2Implementation;

class GLES2Demo {
 public:
  GLES2Demo();

  bool GLES2Demo::Setup(void* hwnd, int32 size);

 private:
  DISALLOW_COPY_AND_ASSIGN(GLES2Demo);
};

GLES2Demo::GLES2Demo() {
}

bool GLES2Demo::Setup(void* hwnd, int32 size) {
  scoped_ptr<SharedMemory> ring_buffer(new SharedMemory);
  if (!ring_buffer->Create(std::wstring(), false, false, size)) {
    return NULL;
  }

  if (!ring_buffer->Map(size)) {
    return NULL;
  }

  scoped_ptr<CommandBufferService> command_buffer(new CommandBufferService);
  if (!command_buffer->Initialize(ring_buffer.release())) {
    return NULL;
  }

  scoped_refptr<GPUProcessor> gpu_processor(
      new GPUProcessor(command_buffer.get()));
  if (!gpu_processor->Initialize(reinterpret_cast<HWND>(hwnd))) {
    return NULL;
  }

  command_buffer->SetPutOffsetChangeCallback(
      NewCallback(gpu_processor.get(), &GPUProcessor::ProcessCommands));

  GLES2CmdHelper* helper = new GLES2CmdHelper(command_buffer.get());
  if (!helper->Initialize()) {
    // TODO(gman): cleanup.
    return false;
  }

  size_t transfer_buffer_size = 512 * 1024;
  int32 transfer_buffer_id =
      command_buffer->CreateTransferBuffer(transfer_buffer_size);
  ::base::SharedMemory* shared_memory =
      command_buffer->GetTransferBuffer(transfer_buffer_id);
  if (!shared_memory->Map(transfer_buffer_size)) {
    return false;
  }
  void* transfer_buffer = shared_memory->memory();
  if (!transfer_buffer) {
    return false;
  }

  gles2::g_gl_impl = new GLES2Implementation(helper,
                                             transfer_buffer_size,
                                             transfer_buffer,
                                             transfer_buffer_id);

  return command_buffer.release() != NULL;
}

#if defined(OS_WIN)
LRESULT CALLBACK WindowProc(
    HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param) {
  switch (msg) {
    case WM_CLOSE:
      DestroyWindow(hwnd);
      break;
    case WM_DESTROY:
      PostQuitMessage(0);
      break;
    case WM_PAINT: {
      GLFromCPPTestFunction();
      GLFromCTestFunction();
      // TODO(gman): Not sure how SwapBuffer should be exposed.
      gles2::GetGLContext()->SwapBuffers();
      break;
    }
    default:
      return ::DefWindowProc(hwnd, msg, w_param, l_param);
  }
  return 0;
}

HINSTANCE GetInstance(void) {
  HWND hwnd = GetConsoleWindow();
  return reinterpret_cast<HINSTANCE>(GetWindowLong(hwnd, GWL_HINSTANCE));
}

void ProcessMessages(void* in_hwnd) {
  HWND hwnd = reinterpret_cast<HWND>(in_hwnd);
  MSG msg;

  bool done = false;
  while (!done) {
    while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
      if (msg.message == WM_QUIT) {
        done = true;
      }
      // dispatch the message
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
    if (!done) {
      InvalidateRect(hwnd, NULL, TRUE);
    }
  }
}

#endif

void* SetupWindow() {
#if defined(OS_WIN)
  HINSTANCE instance = GetInstance();
  WNDCLASSEX wc = {0};
  wc.lpszClassName = L"MY_WINDOWS_CLASS";
  wc.cbSize = sizeof(WNDCLASSEX);
  wc.style = CS_HREDRAW | CS_VREDRAW;
  wc.lpfnWndProc = ::WindowProc;
  wc.cbClsExtra = 0;
  wc.cbWndExtra = 0;
  wc.hInstance = instance;
  wc.hIcon = ::LoadIcon(instance, IDI_APPLICATION);
  wc.hIconSm = NULL;
  wc.hCursor = ::LoadCursor(instance, IDC_ARROW);
  wc.hbrBackground = static_cast<HBRUSH>(::GetStockObject(BLACK_BRUSH));
  wc.lpszMenuName = NULL;

  if (!::RegisterClassEx(&wc))
    return false;

  // Leaving this window onscreen leads to a redraw error which makes it
  // a hassle to debug tests in an IDE, so we place the window somewhere that
  // won't happen.
  HWND hwnd = ::CreateWindowExW(
      NULL,
      wc.lpszClassName,
      L"",
      WS_OVERLAPPEDWINDOW,
      10,
      0,
      512,
      512,
      0,
      0,
      instance,
      0);

  if (hwnd == NULL) {
    return false;
  }

  ::ShowWindow(hwnd, SW_SHOWNORMAL);

  return hwnd;
#else
#error Need code.
#endif
}

int main(int argc, const char** argv) {
  const int32 kCommandBufferSize = 1024 * 1024;
  GLES2Demo* demo = new GLES2Demo();

  void* hwnd = SetupWindow();
  if (!hwnd) {
    ::fprintf(stdout, "Could not setup window.\n");
    return EXIT_FAILURE;
  }

  demo->Setup(hwnd, kCommandBufferSize);

  ProcessMessages(hwnd);

  return EXIT_SUCCESS;
}

<commit_msg>Update initialization of gles2_demo.cc to match requirements of using Chrome base.<commit_after>// Copyright (c) 2006-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.

// This file implements a standalone executable demo of using GLES2 over
// command buffers. This code is temporary as the setup that happens
// here is in a state of flux. Eventually there will be several versions of
// setup, one for trusted code, one for pepper, one for NaCl, and maybe others.

#include <windows.h>
#include <windowsx.h>
#include <shellapi.h>
#include <stdlib.h>
#include <stdio.h>
#include "base/at_exit.h"
#include "base/message_loop.h"
#include "base/ref_counted.h"
#include "base/shared_memory.h"
#include "base/scoped_ptr.h"
#include "gpu/command_buffer/service/gpu_processor.h"
#include "gpu/command_buffer/service/command_buffer_service.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "gpu/command_buffer/client/gles2_lib.h"
#include "gpu/command_buffer/client/gles2_demo_c.h"
#include "gpu/command_buffer/client/gles2_demo_cc.h"

using base::SharedMemory;
using command_buffer::GPUProcessor;
using command_buffer::CommandBufferService;
using command_buffer::gles2::GLES2CmdHelper;
using command_buffer::gles2::GLES2Implementation;

class GLES2Demo {
 public:
  GLES2Demo();

  bool GLES2Demo::Setup(void* hwnd, int32 size);

 private:
  DISALLOW_COPY_AND_ASSIGN(GLES2Demo);
};

GLES2Demo::GLES2Demo() {
}

bool GLES2Demo::Setup(void* hwnd, int32 size) {
  scoped_ptr<SharedMemory> ring_buffer(new SharedMemory);
  if (!ring_buffer->Create(std::wstring(), false, false, size)) {
    return NULL;
  }

  if (!ring_buffer->Map(size)) {
    return NULL;
  }

  scoped_ptr<CommandBufferService> command_buffer(new CommandBufferService);
  if (!command_buffer->Initialize(ring_buffer.release())) {
    return NULL;
  }

  scoped_refptr<GPUProcessor> gpu_processor(
      new GPUProcessor(command_buffer.get()));
  if (!gpu_processor->Initialize(reinterpret_cast<HWND>(hwnd))) {
    return NULL;
  }

  command_buffer->SetPutOffsetChangeCallback(
      NewCallback(gpu_processor.get(), &GPUProcessor::ProcessCommands));

  GLES2CmdHelper* helper = new GLES2CmdHelper(command_buffer.get());
  if (!helper->Initialize()) {
    // TODO(gman): cleanup.
    return false;
  }

  size_t transfer_buffer_size = 512 * 1024;
  int32 transfer_buffer_id =
      command_buffer->CreateTransferBuffer(transfer_buffer_size);
  ::base::SharedMemory* shared_memory =
      command_buffer->GetTransferBuffer(transfer_buffer_id);
  if (!shared_memory->Map(transfer_buffer_size)) {
    return false;
  }
  void* transfer_buffer = shared_memory->memory();
  if (!transfer_buffer) {
    return false;
  }

  gles2::g_gl_impl = new GLES2Implementation(helper,
                                             transfer_buffer_size,
                                             transfer_buffer,
                                             transfer_buffer_id);

  return command_buffer.release() != NULL;
}

#if defined(OS_WIN)
LRESULT CALLBACK WindowProc(
    HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param) {
  switch (msg) {
    case WM_CLOSE:
      DestroyWindow(hwnd);
      break;
    case WM_DESTROY:
      PostQuitMessage(0);
      break;
    case WM_PAINT: {
      GLFromCPPTestFunction();
      GLFromCTestFunction();
      // TODO(gman): Not sure how SwapBuffer should be exposed.
      gles2::GetGLContext()->SwapBuffers();
      break;
    }
    default:
      return ::DefWindowProc(hwnd, msg, w_param, l_param);
  }
  return 0;
}

HINSTANCE GetInstance(void) {
  HWND hwnd = GetConsoleWindow();
  return reinterpret_cast<HINSTANCE>(GetWindowLong(hwnd, GWL_HINSTANCE));
}

void ProcessMessages(void* in_hwnd) {
  HWND hwnd = reinterpret_cast<HWND>(in_hwnd);
  MSG msg;

  bool done = false;
  while (!done) {
    while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
      if (msg.message == WM_QUIT) {
        done = true;
      }
      // dispatch the message
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
    if (!done) {
      InvalidateRect(hwnd, NULL, TRUE);
    }
  }
}

#endif

void* SetupWindow() {
#if defined(OS_WIN)
  HINSTANCE instance = GetInstance();
  WNDCLASSEX wc = {0};
  wc.lpszClassName = L"MY_WINDOWS_CLASS";
  wc.cbSize = sizeof(WNDCLASSEX);
  wc.style = CS_HREDRAW | CS_VREDRAW;
  wc.lpfnWndProc = ::WindowProc;
  wc.cbClsExtra = 0;
  wc.cbWndExtra = 0;
  wc.hInstance = instance;
  wc.hIcon = ::LoadIcon(instance, IDI_APPLICATION);
  wc.hIconSm = NULL;
  wc.hCursor = ::LoadCursor(instance, IDC_ARROW);
  wc.hbrBackground = static_cast<HBRUSH>(::GetStockObject(BLACK_BRUSH));
  wc.lpszMenuName = NULL;

  if (!::RegisterClassEx(&wc))
    return false;

  // Leaving this window onscreen leads to a redraw error which makes it
  // a hassle to debug tests in an IDE, so we place the window somewhere that
  // won't happen.
  HWND hwnd = ::CreateWindowExW(
      NULL,
      wc.lpszClassName,
      L"",
      WS_OVERLAPPEDWINDOW,
      10,
      0,
      512,
      512,
      0,
      0,
      instance,
      0);

  if (hwnd == NULL) {
    return false;
  }

  ::ShowWindow(hwnd, SW_SHOWNORMAL);

  return hwnd;
#else
#error Need code.
#endif
}

int main(int argc, const char** argv) {
  const int32 kCommandBufferSize = 1024 * 1024;

  base::AtExitManager at_exit_manager;
  MessageLoopForUI message_loop;

  GLES2Demo* demo = new GLES2Demo();

  void* hwnd = SetupWindow();
  if (!hwnd) {
    ::fprintf(stdout, "Could not setup window.\n");
    return EXIT_FAILURE;
  }

  demo->Setup(hwnd, kCommandBufferSize);

  ProcessMessages(hwnd);

  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>//
//  IsingGridTest.cpp
//  jdemon
//
//  Created by Mark Larus on 3/11/13.
//  Copyright (c) 2013 Kenyon College. All rights reserved.
//

#include <boost/test/unit_test.hpp>
#include <boost/container/set.hpp>
#include <algorithm>

#include "IsingGrid.h"

using namespace boost::unit_test;
using namespace Ising;
typedef boost::container::set<Ising::Cell*> CellSet;

struct IsingGridFixture {
    Ising::Grid grid;
    IsingGridFixture() : grid(6) {}
};

BOOST_FIXTURE_TEST_SUITE(DetailedIsingGridTest, IsingGridFixture)

BOOST_AUTO_TEST_CASE( testEvenOddIteratorsDisjoint ) {
    CellSet evenSet;
    evenSet.insert(grid.evenIterator(),grid.endIterator());
    CellSet oddSet;
    oddSet.insert(grid.oddIterator(),grid.endIterator());

    for (CellSet::iterator it = evenSet.begin(); it!=evenSet.end(); ++it) {
        BOOST_REQUIRE(!oddSet.count(*it));
    }

    for (CellSet::iterator it = oddSet.begin(); it!=oddSet.end(); ++it) {
        BOOST_REQUIRE(!evenSet.count(*it));
    }
}

BOOST_AUTO_TEST_CASE( testEvenCellsCount ) {
    int count = 0;
    for (Grid::iterator it = grid.evenIterator(); it!=grid.endIterator(); ++it) {
        ++count;
    }
    BOOST_REQUIRE_EQUAL(count,grid.getDimension()*grid.getDimension()/2);
}

BOOST_AUTO_TEST_CASE( testOddCellsCount ) {
    int count = 0;
    for (Grid::iterator it = grid.oddIterator(); it!=grid.endIterator(); ++it) {
        ++count;
    }
    BOOST_REQUIRE_EQUAL(count,grid.getDimension()*grid.getDimension()/2);
}

BOOST_AUTO_TEST_CASE( testAllCellsCount ) {
    int count = 0;
    for (Grid::iterator it = grid.allIterator(); it!=grid.endIterator(); ++it) {
        ++count;
    }
    BOOST_REQUIRE_EQUAL(count, grid.getDimension()*grid.getDimension());
}

BOOST_AUTO_TEST_CASE( testAllCellsInEvenOdd ) {
    CellSet evenOddSet, allSet;
    evenOddSet.insert(grid.evenIterator(), grid.endIterator());
    evenOddSet.insert(grid.oddIterator(),grid.endIterator());

    allSet.insert(grid.allIterator(),grid.endIterator());
    for (CellSet::iterator it = allSet.begin(); it!=allSet.end(); ++it) {
        BOOST_REQUIRE(!evenOddSet.count(*it));
    }

    for (CellSet::iterator it = allSet.begin(); it!=allSet.end(); ++it) {
        BOOST_REQUIRE(!allSet.count(*it));
    }
}

BOOST_AUTO_TEST_CASE( testNeighborCount ) {
    for(Grid::iterator it = grid.allIterator(); it!=grid.endIterator(); ++it) {
        int count = 0;
        Cell::Neighbors neighbors = it->getNeighbors();
        for (Cell::Neighbors::iterator neighbor = neighbors.begin();
             neighbor!=neighbors.end();
             ++neighbor) {
            ++count;
        }
        BOOST_REQUIRE_EQUAL(count, 4);
    }
}

BOOST_AUTO_TEST_CASE( testNoNeighborsInOdd ) {

}

BOOST_AUTO_TEST_CASE( testGetDimension ) {
    Grid grid(10);
    BOOST_REQUIRE_EQUAL(grid.getDimension(),10);
}

BOOST_AUTO_TEST_CASE( testNeighborsTransitive ) {
    for(Grid::iterator it = grid.allIterator(); it!=grid.endIterator(); ++it) {
        Cell::Neighbors neighbors = it->getNeighbors();
        for (Cell::Neighbors::iterator neighbor = neighbors.begin(); neighbor!=neighbors.end(); ++neighbor) {
            Cell::Neighbors reverseNeighbors = (*neighbor)->getNeighbors();
            long count = std::count(reverseNeighbors.begin(), reverseNeighbors.end(), *it);
            BOOST_REQUIRE_EQUAL(count, 1);
        }
    }
}

BOOST_AUTO_TEST_CASE( testSetValue ) {
    Cell cell;
    cell.setValue(0);
    BOOST_REQUIRE_EQUAL(cell.getValue(), 0);
    cell.setValue(1);
    BOOST_REQUIRE_EQUAL(cell.getValue(), 1);
    BOOST_REQUIRE_THROW(cell.setValue(2), InvalidCellValue);
}

BOOST_AUTO_TEST_SUITE_END()<commit_msg>Properly dereference neighbor iterators in Ising::Grid tests.<commit_after>//
//  IsingGridTest.cpp
//  jdemon
//
//  Created by Mark Larus on 3/11/13.
//  Copyright (c) 2013 Kenyon College. All rights reserved.
//

#include <boost/test/unit_test.hpp>
#include <boost/container/set.hpp>
#include <algorithm>

#include "IsingGrid.h"

using namespace boost::unit_test;
using namespace Ising;
typedef boost::container::set<Ising::Cell*> CellSet;

struct IsingGridFixture {
    Ising::Grid grid;
    IsingGridFixture() : grid(6) {}
};

BOOST_FIXTURE_TEST_SUITE(DetailedIsingGridTest, IsingGridFixture)

BOOST_AUTO_TEST_CASE( testEvenOddIteratorsDisjoint ) {
    CellSet evenSet;
    evenSet.insert(grid.evenIterator(),grid.endIterator());
    CellSet oddSet;
    oddSet.insert(grid.oddIterator(),grid.endIterator());

    for (CellSet::iterator it = evenSet.begin(); it!=evenSet.end(); ++it) {
        BOOST_REQUIRE(!oddSet.count(*it));
    }

    for (CellSet::iterator it = oddSet.begin(); it!=oddSet.end(); ++it) {
        BOOST_REQUIRE(!evenSet.count(*it));
    }
}

BOOST_AUTO_TEST_CASE( testEvenCellsCount ) {
    int count = 0;
    for (Grid::iterator it = grid.evenIterator(); it!=grid.endIterator(); ++it) {
        ++count;
    }
    BOOST_REQUIRE_EQUAL(count,grid.getDimension()*grid.getDimension()/2);
}

BOOST_AUTO_TEST_CASE( testOddCellsCount ) {
    int count = 0;
    for (Grid::iterator it = grid.oddIterator(); it!=grid.endIterator(); ++it) {
        ++count;
    }
    BOOST_REQUIRE_EQUAL(count,grid.getDimension()*grid.getDimension()/2);
}

BOOST_AUTO_TEST_CASE( testAllCellsCount ) {
    int count = 0;
    for (Grid::iterator it = grid.allIterator(); it!=grid.endIterator(); ++it) {
        ++count;
    }
    BOOST_REQUIRE_EQUAL(count, grid.getDimension()*grid.getDimension());
}

BOOST_AUTO_TEST_CASE( testAllCellsInEvenOdd ) {
    CellSet evenOddSet, allSet;
    evenOddSet.insert(grid.evenIterator(), grid.endIterator());
    evenOddSet.insert(grid.oddIterator(),grid.endIterator());

    allSet.insert(grid.allIterator(),grid.endIterator());
    for (CellSet::iterator it = allSet.begin(); it!=allSet.end(); ++it) {
        BOOST_REQUIRE(!evenOddSet.count(*it));
    }

    for (CellSet::iterator it = allSet.begin(); it!=allSet.end(); ++it) {
        BOOST_REQUIRE(!allSet.count(*it));
    }
}

BOOST_AUTO_TEST_CASE( testNeighborCount ) {
    for(Grid::iterator it = grid.allIterator(); it!=grid.endIterator(); ++it) {
        int count = 0;
        Cell::Neighbors neighbors = (*it)->getNeighbors();
        for (Cell::Neighbors::iterator neighbor = neighbors.begin();
             neighbor!=neighbors.end();
             ++neighbor) {
            ++count;
        }
        BOOST_REQUIRE_EQUAL(count, 4);
    }
}

BOOST_AUTO_TEST_CASE( testNoNeighborsInOdd ) {

}

BOOST_AUTO_TEST_CASE( testGetDimension ) {
    Grid grid(10);
    BOOST_REQUIRE_EQUAL(grid.getDimension(),10);
}

BOOST_AUTO_TEST_CASE( testNeighborsTransitive ) {
    for(Grid::iterator it = grid.allIterator(); it!=grid.endIterator(); ++it) {
        Cell::Neighbors neighbors = (*it)->getNeighbors();
        for (Cell::Neighbors::iterator neighbor = neighbors.begin(); neighbor!=neighbors.end(); ++neighbor) {
            Cell::Neighbors reverseNeighbors = (*neighbor)->getNeighbors();
            long count = std::count(reverseNeighbors.begin(), reverseNeighbors.end(), *it);
            BOOST_REQUIRE_EQUAL(count, 1);
        }
    }
}

BOOST_AUTO_TEST_CASE( testSetValue ) {
    Cell cell;
    cell.setValue(0);
    BOOST_REQUIRE_EQUAL(cell.getValue(), 0);
    cell.setValue(1);
    BOOST_REQUIRE_EQUAL(cell.getValue(), 1);
    BOOST_REQUIRE_THROW(cell.setValue(2), InvalidCellValue);
}

BOOST_AUTO_TEST_SUITE_END()<|endoftext|>


<commit_before>#ifndef SIGNALLP1FILTER_HPP_INCLUDED
#define SIGNALLP1FILTER_HPP_INCLUDED

#include "HopsanCore.h"

class SignalLP1Filter : public ComponentSignal
{

private:
    double mCofrequency;
    double mTimestep;
    TransferFunction Filter;
    enum {in, out};

public:
    static Component *Creator()
    {
        std::cout << "running lp1 filter creator" << std::endl;
        return new SignalLP1Filter("DefaultLP1FilterName");
    }

    SignalLP1Filter(const string name,
                 const double cofrequency = 100,
                 const double timestep = 0.001)
	: ComponentSignal(name, timestep)
    {
        mCofrequency = cofrequency;
        mTimestep = timestep;

        addReadPort("in", "NodeSignal", in);
        addWritePort("out", "NodeSignal", out);

        registerParameter("Frequency", "Cut-Off Frequency", "[rad/s]", mCofrequency);
    }

	void initialize()
	{
	    double num [3] = {1.0, 0.0, 0.0};
	    double den [3] = {1.0, 1.0/mCofrequency, 0.0};
        Filter.setCoefficients(num, den, mTimestep);
	}

    void simulateOneTimestep()
    {

        //Get variable values from nodes
        double u = mPortPtrs[in]->readNode(NodeSignal::VALUE);

        //Filter equations
		double y = Filter.getValue(u);

        //Write new values to nodes
        mPortPtrs[out]->writeNode(NodeSignal::VALUE, y);

        //Update filter:
        //Filter.update(u);
    }
};

#endif // SIGNALLP1FILTER_HPP_INCLUDED

<commit_msg>added initialize of the transfer function used<commit_after>#ifndef SIGNALLP1FILTER_HPP_INCLUDED
#define SIGNALLP1FILTER_HPP_INCLUDED

#include "HopsanCore.h"

class SignalLP1Filter : public ComponentSignal
{

private:
    double mCofrequency;
    double mTimestep;
    TransferFunction Filter;
    enum {in, out};

public:
    static Component *Creator()
    {
        std::cout << "running lp1 filter creator" << std::endl;
        return new SignalLP1Filter("DefaultLP1FilterName");
    }

    SignalLP1Filter(const string name,
                 const double cofrequency = 100,
                 const double timestep = 0.001)
	: ComponentSignal(name, timestep)
    {
        mCofrequency = cofrequency;
        mTimestep = timestep;

        addReadPort("in", "NodeSignal", in);
        addWritePort("out", "NodeSignal", out);

        registerParameter("Frequency", "Cut-Off Frequency", "[rad/s]", mCofrequency);
    }

	void initialize()
	{
	    double num [3] = {1.0, 0.0, 0.0};
	    double den [3] = {1.0, 1.0/mCofrequency, 0.0};
	    Filter.initialize(0.0, 0.0, mTime);
        Filter.setCoefficients(num, den, mTimestep);
	}

    void simulateOneTimestep()
    {

        //Get variable values from nodes
        double u = mPortPtrs[in]->readNode(NodeSignal::VALUE);

        //Filter equations
		double y = Filter.getValue(u);

        //Write new values to nodes
        mPortPtrs[out]->writeNode(NodeSignal::VALUE, y);

        //Update filter:
        //Filter.update(u);
    }
};

#endif // SIGNALLP1FILTER_HPP_INCLUDED

<|endoftext|>


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

#include "base/command_line.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"

namespace {

// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
 public:
  explicit BrowserClosedObserver(Browser* browser) {
    registrar_.Add(this, NotificationType::BROWSER_CLOSED,
                   Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    MessageLoopForUI::current()->Quit();
  }

 private:
  NotificationRegistrar registrar_;
  DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};

// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;

const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html";
const char kPauseWhenLoadingDevTools[] =
    "files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
    "files/devtools/pause_when_script_is_running.html";
const char kPageWithContentScript[] =
    "files/devtools/page_with_content_script.html";

class DevToolsSanityTest : public InProcessBrowserTest {
 public:
  DevToolsSanityTest() {
    set_show_window(true);
    EnableDOMAutomation();
  }

 protected:
  void RunTest(const std::string& test_name, const std::string& test_page) {
    OpenDevToolsWindow(test_page);
    std::string result;

    // At first check that JavaScript part of the front-end is loaded by
    // checking that global variable uiTests exists(it's created after all js
    // files have been loaded) and has runTest method.
    ASSERT_TRUE(
        ui_test_utils::ExecuteJavaScriptAndExtractString(
            client_contents_->render_view_host(),
            L"",
            L"window.domAutomationController.send("
            L"'' + (window.uiTests && (typeof uiTests.runTest)));",
            &result));

    if (result == "function") {
      ASSERT_TRUE(
          ui_test_utils::ExecuteJavaScriptAndExtractString(
              client_contents_->render_view_host(),
              L"",
              UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
                                      test_name.c_str())),
              &result));
      EXPECT_EQ("[OK]", result);
    } else {
      FAIL() << "DevTools front-end is broken.";
    }
    CloseDevToolsWindow();
  }

  void OpenDevToolsWindow(const std::string& test_page) {
    ASSERT_TRUE(test_server()->Start());
    GURL url = test_server()->GetURL(test_page);
    ui_test_utils::NavigateToURL(browser(), url);

    inspected_rvh_ = GetInspectedTab()->render_view_host();
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    devtools_manager->OpenDevToolsWindow(inspected_rvh_);

    DevToolsClientHost* client_host =
        devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
    window_ = client_host->AsDevToolsWindow();
    RenderViewHost* client_rvh = window_->GetRenderViewHost();
    client_contents_ = client_rvh->delegate()->GetAsTabContents();
    ui_test_utils::WaitForNavigation(&client_contents_->controller());
  }

  TabContents* GetInspectedTab() {
    return browser()->GetTabContentsAt(0);
  }

  void CloseDevToolsWindow() {
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    // UnregisterDevToolsClientHostFor may destroy window_ so store the browser
    // first.
    Browser* browser = window_->browser();
    devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);

    // Wait only when DevToolsWindow has a browser. For docked DevTools, this
    // is NULL and we skip the wait.
    if (browser)
      BrowserClosedObserver close_observer(browser);
  }

  TabContents* client_contents_;
  DevToolsWindow* window_;
  RenderViewHost* inspected_rvh_;
};

class CancelableQuitTask : public Task {
 public:
  explicit CancelableQuitTask(const std::string& timeout_message)
      : timeout_message_(timeout_message),
        cancelled_(false) {
  }

  void cancel() {
    cancelled_ = true;
  }

  virtual void Run() {
    if (cancelled_) {
      return;
    }
    FAIL() << timeout_message_;
    MessageLoop::current()->Quit();
  }

 private:
  std::string timeout_message_;
  bool cancelled_;
};

// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
                                   public NotificationObserver {
 public:
  DevToolsExtensionDebugTest() : DevToolsSanityTest() {
    PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
    test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
    test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
  }

 protected:
  // Load an extention from test\data\devtools\extensions\<extension_name>
  void LoadExtension(const char* extension_name) {
    FilePath path = test_extensions_dir_.AppendASCII(extension_name);
    ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
  }

 private:
  bool LoadExtensionFromPath(const FilePath& path) {
    ExtensionService* service = browser()->profile()->GetExtensionService();
    size_t num_before = service->extensions()->size();
    {
      NotificationRegistrar registrar;
      registrar.Add(this, NotificationType::EXTENSION_LOADED,
                    NotificationService::AllSources());
      CancelableQuitTask* delayed_quit =
          new CancelableQuitTask("Extension load timed out.");
      MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
          4*1000);
      service->LoadExtension(path);
      ui_test_utils::RunMessageLoop();
      delayed_quit->cancel();
    }
    size_t num_after = service->extensions()->size();
    if (num_after != (num_before + 1))
      return false;

    return WaitForExtensionHostsToLoad();
  }

  bool WaitForExtensionHostsToLoad() {
    // Wait for all the extension hosts that exist to finish loading.
    // NOTE: This assumes that the extension host list is not changing while
    // this method is running.

    NotificationRegistrar registrar;
    registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
                  NotificationService::AllSources());
    CancelableQuitTask* delayed_quit =
        new CancelableQuitTask("Extension host load timed out.");
    MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
        4*1000);

    ExtensionProcessManager* manager =
          browser()->profile()->GetExtensionProcessManager();
    for (ExtensionProcessManager::const_iterator iter = manager->begin();
         iter != manager->end();) {
      if ((*iter)->did_stop_loading())
        ++iter;
      else
        ui_test_utils::RunMessageLoop();
    }

    delayed_quit->cancel();
    return true;
  }

  void Observe(NotificationType type,
               const NotificationSource& source,
               const NotificationDetails& details) {
    switch (type.value) {
      case NotificationType::EXTENSION_LOADED:
      case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
        MessageLoopForUI::current()->Quit();
        break;
      default:
        NOTREACHED();
        break;
    }
  }

  FilePath test_extensions_dir_;
};

// Tests heap profiler.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) {
  RunTest("testHeapProfiler", kHeapProfilerPage);
}

// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
  RunTest("testShowScriptsTab", kDebuggerTestPage);
}

// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
// Marked as disabled: crbug/73289.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       DISABLED_TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
  // Clear inspector settings to ensure that Elements will be
  // current panel when DevTools window is open.
  GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();
  RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
          kDebuggerTestPage);
}

// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
                       TestContentScriptIsPresent) {
  LoadExtension("simple_content_script");
  RunTest("testContentScriptIsPresent", kPageWithContentScript);
}

// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       TestNoScriptDuplicatesOnPanelSwitch) {
  RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}

// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
  RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}

// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
  RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}

}  // namespace
<commit_msg>Enable back DevToolsSanityTest.TestScriptsTabIsPopulatedOnInspectedPageRefresh Should pass after the last WK roll (r75275).<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"

namespace {

// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
 public:
  explicit BrowserClosedObserver(Browser* browser) {
    registrar_.Add(this, NotificationType::BROWSER_CLOSED,
                   Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    MessageLoopForUI::current()->Quit();
  }

 private:
  NotificationRegistrar registrar_;
  DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};

// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;

const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html";
const char kPauseWhenLoadingDevTools[] =
    "files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
    "files/devtools/pause_when_script_is_running.html";
const char kPageWithContentScript[] =
    "files/devtools/page_with_content_script.html";

class DevToolsSanityTest : public InProcessBrowserTest {
 public:
  DevToolsSanityTest() {
    set_show_window(true);
    EnableDOMAutomation();
  }

 protected:
  void RunTest(const std::string& test_name, const std::string& test_page) {
    OpenDevToolsWindow(test_page);
    std::string result;

    // At first check that JavaScript part of the front-end is loaded by
    // checking that global variable uiTests exists(it's created after all js
    // files have been loaded) and has runTest method.
    ASSERT_TRUE(
        ui_test_utils::ExecuteJavaScriptAndExtractString(
            client_contents_->render_view_host(),
            L"",
            L"window.domAutomationController.send("
            L"'' + (window.uiTests && (typeof uiTests.runTest)));",
            &result));

    if (result == "function") {
      ASSERT_TRUE(
          ui_test_utils::ExecuteJavaScriptAndExtractString(
              client_contents_->render_view_host(),
              L"",
              UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
                                      test_name.c_str())),
              &result));
      EXPECT_EQ("[OK]", result);
    } else {
      FAIL() << "DevTools front-end is broken.";
    }
    CloseDevToolsWindow();
  }

  void OpenDevToolsWindow(const std::string& test_page) {
    ASSERT_TRUE(test_server()->Start());
    GURL url = test_server()->GetURL(test_page);
    ui_test_utils::NavigateToURL(browser(), url);

    inspected_rvh_ = GetInspectedTab()->render_view_host();
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    devtools_manager->OpenDevToolsWindow(inspected_rvh_);

    DevToolsClientHost* client_host =
        devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
    window_ = client_host->AsDevToolsWindow();
    RenderViewHost* client_rvh = window_->GetRenderViewHost();
    client_contents_ = client_rvh->delegate()->GetAsTabContents();
    ui_test_utils::WaitForNavigation(&client_contents_->controller());
  }

  TabContents* GetInspectedTab() {
    return browser()->GetTabContentsAt(0);
  }

  void CloseDevToolsWindow() {
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    // UnregisterDevToolsClientHostFor may destroy window_ so store the browser
    // first.
    Browser* browser = window_->browser();
    devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);

    // Wait only when DevToolsWindow has a browser. For docked DevTools, this
    // is NULL and we skip the wait.
    if (browser)
      BrowserClosedObserver close_observer(browser);
  }

  TabContents* client_contents_;
  DevToolsWindow* window_;
  RenderViewHost* inspected_rvh_;
};

class CancelableQuitTask : public Task {
 public:
  explicit CancelableQuitTask(const std::string& timeout_message)
      : timeout_message_(timeout_message),
        cancelled_(false) {
  }

  void cancel() {
    cancelled_ = true;
  }

  virtual void Run() {
    if (cancelled_) {
      return;
    }
    FAIL() << timeout_message_;
    MessageLoop::current()->Quit();
  }

 private:
  std::string timeout_message_;
  bool cancelled_;
};

// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
                                   public NotificationObserver {
 public:
  DevToolsExtensionDebugTest() : DevToolsSanityTest() {
    PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
    test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
    test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
  }

 protected:
  // Load an extention from test\data\devtools\extensions\<extension_name>
  void LoadExtension(const char* extension_name) {
    FilePath path = test_extensions_dir_.AppendASCII(extension_name);
    ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
  }

 private:
  bool LoadExtensionFromPath(const FilePath& path) {
    ExtensionService* service = browser()->profile()->GetExtensionService();
    size_t num_before = service->extensions()->size();
    {
      NotificationRegistrar registrar;
      registrar.Add(this, NotificationType::EXTENSION_LOADED,
                    NotificationService::AllSources());
      CancelableQuitTask* delayed_quit =
          new CancelableQuitTask("Extension load timed out.");
      MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
          4*1000);
      service->LoadExtension(path);
      ui_test_utils::RunMessageLoop();
      delayed_quit->cancel();
    }
    size_t num_after = service->extensions()->size();
    if (num_after != (num_before + 1))
      return false;

    return WaitForExtensionHostsToLoad();
  }

  bool WaitForExtensionHostsToLoad() {
    // Wait for all the extension hosts that exist to finish loading.
    // NOTE: This assumes that the extension host list is not changing while
    // this method is running.

    NotificationRegistrar registrar;
    registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
                  NotificationService::AllSources());
    CancelableQuitTask* delayed_quit =
        new CancelableQuitTask("Extension host load timed out.");
    MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
        4*1000);

    ExtensionProcessManager* manager =
          browser()->profile()->GetExtensionProcessManager();
    for (ExtensionProcessManager::const_iterator iter = manager->begin();
         iter != manager->end();) {
      if ((*iter)->did_stop_loading())
        ++iter;
      else
        ui_test_utils::RunMessageLoop();
    }

    delayed_quit->cancel();
    return true;
  }

  void Observe(NotificationType type,
               const NotificationSource& source,
               const NotificationDetails& details) {
    switch (type.value) {
      case NotificationType::EXTENSION_LOADED:
      case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
        MessageLoopForUI::current()->Quit();
        break;
      default:
        NOTREACHED();
        break;
    }
  }

  FilePath test_extensions_dir_;
};

// Tests heap profiler.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) {
  RunTest("testHeapProfiler", kHeapProfilerPage);
}

// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
  RunTest("testShowScriptsTab", kDebuggerTestPage);
}

// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
  // Clear inspector settings to ensure that Elements will be
  // current panel when DevTools window is open.
  GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();
  RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
          kDebuggerTestPage);
}

// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
                       TestContentScriptIsPresent) {
  LoadExtension("simple_content_script");
  RunTest("testContentScriptIsPresent", kPageWithContentScript);
}

// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       TestNoScriptDuplicatesOnPanelSwitch) {
  RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}

// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
  RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}

// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
  RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}

}  // namespace
<|endoftext|>


<commit_before>/***************************************************************************
* This file is part of libmygpo-qt                                         *
* Copyright (c) 2010 - 2012 Stefan Derkits <stefan@derkits.at>             *
*                                                                          *
* This library is free software; you can redistribute it and/or            *
* modify it under the terms of the GNU Lesser General Public               *
* License as published by the Free Software Foundation; either             *
* version 2.1 of the License, or (at your option) any later version.       *
*                                                                          *
* This library is distributed in the hope that it will be useful,          *
* but WITHOUT ANY WARRANTY; without even the implied warranty of           *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU        *
* Lesser General Public License for more details.                          *
*                                                                          *
* You should have received a copy of the GNU Lesser General Public         *
* License along with this library; if not, write to the Free Software      *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 *
* USA                                                                      *
***************************************************************************/

#include "Config_p.h"
#include "Version.h"

#include <QString>
#include <QStringBuilder>
#include <QLatin1String>

using namespace mygpo;

ConfigPrivate::ConfigPrivate( Config* qq ) : q( qq )
{

}

ConfigPrivate::~ConfigPrivate()
{

}

int ConfigPrivate::majorVersion() const
{
    return MYGPO_QT_VERSION_MAJOR;
}

int ConfigPrivate::minorVersion() const
{
    return MYGPO_QT_VERSION_MINOR;
}

int ConfigPrivate::patchVersion() const
{
    return MYGPO_QT_VERSION_PATCH;
}

QString ConfigPrivate::version() const
{
    return QString( majorVersion() ) % QLatin1String( "." ) % QString( minorVersion() ) % QLatin1String( "." ) % QString( patchVersion() );
}

Config::Config() : d( new ConfigPrivate( this ) )
{

}

Config::~Config()
{
    delete d;
}

int Config::majorVersion() const
{
    return d->majorVersion();
}

int Config::minorVersion() const
{
    return d->minorVersion();
}

int Config::patchVersion() const
{
    return d->patchVersion();
}

QString Config::version() const
{
    return d->version();
}

Config* Config::instance()
{
    if ( !s_instance ) {
        s_instance = new Config;
    }

    return s_instance;
}
<commit_msg>fixed bug with undefined reference to Device::s_instance (initialization was missing)<commit_after>/***************************************************************************
* This file is part of libmygpo-qt                                         *
* Copyright (c) 2010 - 2012 Stefan Derkits <stefan@derkits.at>             *
*                                                                          *
* This library is free software; you can redistribute it and/or            *
* modify it under the terms of the GNU Lesser General Public               *
* License as published by the Free Software Foundation; either             *
* version 2.1 of the License, or (at your option) any later version.       *
*                                                                          *
* This library is distributed in the hope that it will be useful,          *
* but WITHOUT ANY WARRANTY; without even the implied warranty of           *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU        *
* Lesser General Public License for more details.                          *
*                                                                          *
* You should have received a copy of the GNU Lesser General Public         *
* License along with this library; if not, write to the Free Software      *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 *
* USA                                                                      *
***************************************************************************/

#include "Config_p.h"
#include "Version.h"

#include <QString>
#include <QStringBuilder>
#include <QLatin1String>

using namespace mygpo;

Config* Config::s_instance = 0;

ConfigPrivate::ConfigPrivate( Config* qq ) : q( qq )
{

}

ConfigPrivate::~ConfigPrivate()
{

}

int ConfigPrivate::majorVersion() const
{
    return MYGPO_QT_VERSION_MAJOR;
}

int ConfigPrivate::minorVersion() const
{
    return MYGPO_QT_VERSION_MINOR;
}

int ConfigPrivate::patchVersion() const
{
    return MYGPO_QT_VERSION_PATCH;
}

QString ConfigPrivate::version() const
{
    return QString( majorVersion() ) % QLatin1String( "." ) % QString( minorVersion() ) % QLatin1String( "." ) % QString( patchVersion() );
}

Config::Config() : d( new ConfigPrivate( this ) )
{

}

Config::~Config()
{
    delete d;
}

int Config::majorVersion() const
{
    return d->majorVersion();
}

int Config::minorVersion() const
{
    return d->minorVersion();
}

int Config::patchVersion() const
{
    return d->patchVersion();
}

QString Config::version() const
{
    return d->version();
}

Config* Config::instance()
{
    if ( !s_instance ) {
        s_instance = new Config;
    }

    return s_instance;
}
<|endoftext|>


<commit_before>/**
 * @file
 * @brief Implementation of module to read weighting fields
 * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
 * This software is distributed under the terms of the MIT License, copied
 * verbatim in the file "LICENSE.md".
 * In applying this license, CERN does not waive the privileges and immunities
 * granted to it by virtue of its status as an
 * Intergovernmental Organization or submit itself to any jurisdiction.
 */

#include "WeightingFieldReaderModule.hpp"

#include <fstream>
#include <limits>
#include <memory>
#include <new>
#include <stdexcept>
#include <string>
#include <utility>

#include <Math/RotationZ.h>
#include <Math/Vector3D.h>
#include <TH2F.h>

#include "core/config/exceptions.h"
#include "core/geometry/DetectorModel.hpp"
#include "core/utils/log.h"
#include "core/utils/unit.h"

using namespace allpix;

WeightingFieldReaderModule::WeightingFieldReaderModule(Configuration& config, Messenger*, std::shared_ptr<Detector> detector)
    : Module(config, detector), detector_(std::move(detector)) {}

void WeightingFieldReaderModule::init() {

    auto field_model = config_.get<std::string>("model");

    // Calculate thickness domain
    auto model = detector_->getModel();
    auto sensor_max_z = model->getSensorCenter().z() + model->getSensorSize().z() / 2.0;
    auto thickness_domain = std::make_pair(sensor_max_z - model->getSensorSize().z(), sensor_max_z);

    // Calculate the field depending on the configuration
    if(field_model == "init") {
        auto field_data = read_init_field(thickness_domain);

        // Calculate field scale from field size and pixel pitch:
        auto pixel_size = model->getPixelSize();
        std::array<double, 2> field_scale{
            {std::get<2>(field_data)[0] / pixel_size.x(), std::get<2>(field_data)[1] / pixel_size.y()}};

        detector_->setWeightingFieldGrid(
            std::get<0>(field_data), std::get<1>(field_data), field_scale, std::array<double, 2>{0, 0}, thickness_domain);
    } else if(field_model == "pad") {
        LOG(TRACE) << "Adding weighting field from pad in plane condenser";

        // Get pixel implant size from the detector model:
        auto implant = model->getImplantSize();
        FieldFunction<ROOT::Math::XYZVector> function = get_pad_field_function(implant, thickness_domain);
        detector_->setWeightingFieldFunction(function, thickness_domain, FieldType::CUSTOM);
    } else {
        throw InvalidValueError(config_, "model", "model should be 'init' or `pad`");
    }

    // Produce histograms if needed
    if(config_.get<bool>("output_plots", false)) {
        create_output_plots();
    }
}

/**
 * Implement weighting field from doi:10.1016/j.nima.2014.08.44 and return it as a lookup function.
 */
FieldFunction<ROOT::Math::XYZVector>
WeightingFieldReaderModule::get_pad_field_function(const ROOT::Math::XYVector& implant,
                                                   std::pair<double, double> thickness_domain) {

    LOG(TRACE) << "Calculating function for the plane condenser weighting field." << std::endl;

    return [implant, thickness_domain](const ROOT::Math::XYZPoint& pos) {
        // Calculate values of the "g" function for all three components
        auto g = [implant](double x, double y, double u) {
            // Calculate terms derived from the arctan functions in the potential for all components
            auto fraction = [](double a, double b, double c) {
                double denominator = std::sqrt(a * a + b * b + c * c);
                // Three different components required since the derivatives have different solutions
                return ROOT::Math::XYZVector(b * c / ((a * a + c * c) * denominator),
                                             a * c / ((b * b + c * c) * denominator),
                                             a * b * (a * a + b * b + 2 * c * c) /
                                                 ((a * a + c * c) * (b * b + c * c) * denominator));
            };

            // Shift the x and y coordinates by plus/minus half the implant size:
            double x1 = x - implant.x() / 2;
            double x2 = x + implant.x() / 2;
            double y1 = y - implant.y() / 2;
            double y2 = y + implant.y() / 2;

            // Sum the four components of the "g" function and return:
            return (fraction(x1, y1, u) + fraction(x2, y2, u) - fraction(x1, y2, u) - fraction(x2, y1, u));
        };

        // Transform into coordinate system with sensor between d/2 < z < -d/2:
        auto d = thickness_domain.second - thickness_domain.first;
        auto local_z = -pos.z() + thickness_domain.second;

        // Calculate the series expansion
        ROOT::Math::XYZVector sum;
        for(int n = 1; n <= 100; n++) {
            sum += g(pos.x(), pos.y(), 2 * n * d - local_z) +
                   ROOT::Math::RotationZ(M_PI) * g(pos.x(), pos.y(), 2 * n * d + local_z);
        }

        return (1 / (2 * M_PI) * (ROOT::Math::RotationZ(M_PI) * g(pos.x(), pos.y(), local_z) + sum));
    };
}

void WeightingFieldReaderModule::create_output_plots() {
    LOG(TRACE) << "Creating output plots";

    auto steps = config_.get<size_t>("output_plots_steps", 500);
    auto position = config_.get<ROOT::Math::XYPoint>("output_plots_position", ROOT::Math::XYPoint(0, 0));

    auto model = detector_->getModel();

    double min = model->getSensorCenter().z() - model->getSensorSize().z() / 2.0;
    double max = model->getSensorCenter().z() + model->getSensorSize().z() / 2.0;

    // Create 1D histograms
    auto histogramX =
        new TH1F("field1d_x", "E_{w}/V_{w} (x-component);x (mm);field strength (1/cm)", static_cast<int>(steps), min, max);
    auto histogramY =
        new TH1F("field1d_y", "E_{w}/V_{w} (y-component);y (mm);field strength (1/cm)", static_cast<int>(steps), min, max);
    auto histogramZ =
        new TH1F("field1d_z", "E_{w}/V_{w} (z-component);z (mm);field strength (1/cm)", static_cast<int>(steps), min, max);

    // Get the weighting field at every index
    for(size_t j = 0; j < steps; ++j) {
        double z = min + ((static_cast<double>(j) + 0.5) / static_cast<double>(steps)) * (max - min);

        // Get field strength from detector
        auto field = detector_->getWeightingField(ROOT::Math::XYZPoint(position.x(), position.y(), z), 0, 0);
        auto field_x_strength = Units::convert(field.x(), "1/cm");
        auto field_y_strength = Units::convert(field.y(), "1/cm");
        auto field_z_strength = Units::convert(field.z(), "1/cm");

        // Fill the histograms
        histogramX->Fill(z, static_cast<double>(field_x_strength));
        histogramY->Fill(z, static_cast<double>(field_y_strength));
        histogramZ->Fill(z, static_cast<double>(field_z_strength));
    }

    // Create 2D histogram
    auto histogram = new TH2F("field_z",
                              "E_{w}/V_{w} (z-component);x (mm); z (mm); field strength (1/cm)",
                              static_cast<int>(steps),
                              -1.5 * model->getPixelSize().x(),
                              1.5 * model->getPixelSize().x(),
                              static_cast<int>(steps),
                              min,
                              max);
    // histogram->SetMinimum(0);

    // Get the weighting field at every index
    for(size_t j = 0; j < steps; ++j) {
        LOG_PROGRESS(INFO, "plotting") << "Plotting progress " << 100 * j * steps / (steps * steps) << "%";
        for(size_t k = 0; k < steps; ++k) {
            double z = min + ((static_cast<double>(j) + 0.5) / static_cast<double>(steps)) * (max - min);
            double x = -0.5 * model->getPixelSize().x() +
                       ((static_cast<double>(k) + 0.5) / static_cast<double>(steps)) * 3 * model->getPixelSize().x();

            // LOG(DEBUG) << "Requesting field ad local coords (" << Units::display(x, {"cm", "mm", "um"}) << "," << 0;
            // Get field strength from detector
            auto field = detector_->getWeightingField(ROOT::Math::XYZPoint(x, 0, z), 1, 0);
            auto field_z_strength = Units::convert(field.z(), "1/cm");

            // Fill the histograms, shift x-axis by one pixel so the reference electrode in centered.
            histogram->Fill(x - model->getPixelSize().x(), z, static_cast<double>(field_z_strength));
        }
    }

    // Write the histogram to module file
    histogramX->Write();
    histogramY->Write();
    histogramZ->Write();
    histogram->Write();
}

/**
 * The field read from the INIT format are shared between module instantiations
 * using the static WeightingFieldReaderModule::get_by_file_name method.
 */
FieldParser<double, 3> WeightingFieldReaderModule::field_parser_("");
FieldData<double> WeightingFieldReaderModule::read_init_field(std::pair<double, double> thickness_domain) {
    using namespace ROOT::Math;

    try {
        LOG(TRACE) << "Fetching weighting field from init file";

        // Get field from file
        auto field_data = field_parser_.get_by_file_name(config_.getPath("file_name", true));

        // Check if electric field matches chip
        check_detector_match(std::get<2>(field_data), thickness_domain);

        LOG(INFO) << "Set weighting field with " << std::get<1>(field_data).at(0) << "x" << std::get<1>(field_data).at(1)
                  << "x" << std::get<1>(field_data).at(2) << " cells";

        // Return the field data
        return field_data;
    } catch(std::invalid_argument& e) {
        throw InvalidValueError(config_, "file_name", e.what());
    } catch(std::runtime_error& e) {
        throw InvalidValueError(config_, "file_name", e.what());
    } catch(std::bad_alloc& e) {
        throw InvalidValueError(config_, "file_name", "file too large");
    }
}

/**
 * @brief Check if the detector matches the file header
 */
void WeightingFieldReaderModule::check_detector_match(std::array<double, 3> dimensions,
                                                      std::pair<double, double> thickness_domain) {
    auto xpixsz = dimensions[0];
    auto ypixsz = dimensions[1];
    auto thickness = dimensions[2];

    auto model = detector_->getModel();
    // Do a several checks with the detector model
    if(model != nullptr) {
        // Check field dimension in z versus the requested thickness domain:
        auto eff_thickness = thickness_domain.second - thickness_domain.first;
        if(std::fabs(thickness - eff_thickness) > std::numeric_limits<double>::epsilon()) {
            LOG(WARNING) << "Thickness of weighting field is " << Units::display(thickness, "um")
                         << " but the depleted region is " << Units::display(eff_thickness, "um");
        }

        // Check that the total field size is n*pitch:
        if(std::fmod(xpixsz, model->getPixelSize().x()) > std::numeric_limits<double>::epsilon() ||
           std::fmod(ypixsz, model->getPixelSize().y()) > std::numeric_limits<double>::epsilon()) {
            LOG(WARNING) << "Field size is (" << Units::display(xpixsz, {"um", "mm"}) << ","
                         << Units::display(ypixsz, {"um", "mm"}) << ") but expecting a multiple of the pixel pitch ("
                         << Units::display(model->getPixelSize().x(), {"um", "mm"}) << ", "
                         << Units::display(model->getPixelSize().y(), {"um", "mm"}) << ")";
        }
    }
}
<commit_msg>WeightingFieldReader: add double curly brackets for array initializer list<commit_after>/**
 * @file
 * @brief Implementation of module to read weighting fields
 * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
 * This software is distributed under the terms of the MIT License, copied
 * verbatim in the file "LICENSE.md".
 * In applying this license, CERN does not waive the privileges and immunities
 * granted to it by virtue of its status as an
 * Intergovernmental Organization or submit itself to any jurisdiction.
 */

#include "WeightingFieldReaderModule.hpp"

#include <fstream>
#include <limits>
#include <memory>
#include <new>
#include <stdexcept>
#include <string>
#include <utility>

#include <Math/RotationZ.h>
#include <Math/Vector3D.h>
#include <TH2F.h>

#include "core/config/exceptions.h"
#include "core/geometry/DetectorModel.hpp"
#include "core/utils/log.h"
#include "core/utils/unit.h"

using namespace allpix;

WeightingFieldReaderModule::WeightingFieldReaderModule(Configuration& config, Messenger*, std::shared_ptr<Detector> detector)
    : Module(config, detector), detector_(std::move(detector)) {}

void WeightingFieldReaderModule::init() {

    auto field_model = config_.get<std::string>("model");

    // Calculate thickness domain
    auto model = detector_->getModel();
    auto sensor_max_z = model->getSensorCenter().z() + model->getSensorSize().z() / 2.0;
    auto thickness_domain = std::make_pair(sensor_max_z - model->getSensorSize().z(), sensor_max_z);

    // Calculate the field depending on the configuration
    if(field_model == "init") {
        auto field_data = read_init_field(thickness_domain);

        // Calculate field scale from field size and pixel pitch:
        auto pixel_size = model->getPixelSize();
        std::array<double, 2> field_scale{
            {std::get<2>(field_data)[0] / pixel_size.x(), std::get<2>(field_data)[1] / pixel_size.y()}};

        detector_->setWeightingFieldGrid(
            std::get<0>(field_data), std::get<1>(field_data), field_scale, std::array<double, 2>{{0, 0}}, thickness_domain);
    } else if(field_model == "pad") {
        LOG(TRACE) << "Adding weighting field from pad in plane condenser";

        // Get pixel implant size from the detector model:
        auto implant = model->getImplantSize();
        FieldFunction<ROOT::Math::XYZVector> function = get_pad_field_function(implant, thickness_domain);
        detector_->setWeightingFieldFunction(function, thickness_domain, FieldType::CUSTOM);
    } else {
        throw InvalidValueError(config_, "model", "model should be 'init' or `pad`");
    }

    // Produce histograms if needed
    if(config_.get<bool>("output_plots", false)) {
        create_output_plots();
    }
}

/**
 * Implement weighting field from doi:10.1016/j.nima.2014.08.44 and return it as a lookup function.
 */
FieldFunction<ROOT::Math::XYZVector>
WeightingFieldReaderModule::get_pad_field_function(const ROOT::Math::XYVector& implant,
                                                   std::pair<double, double> thickness_domain) {

    LOG(TRACE) << "Calculating function for the plane condenser weighting field." << std::endl;

    return [implant, thickness_domain](const ROOT::Math::XYZPoint& pos) {
        // Calculate values of the "g" function for all three components
        auto g = [implant](double x, double y, double u) {
            // Calculate terms derived from the arctan functions in the potential for all components
            auto fraction = [](double a, double b, double c) {
                double denominator = std::sqrt(a * a + b * b + c * c);
                // Three different components required since the derivatives have different solutions
                return ROOT::Math::XYZVector(b * c / ((a * a + c * c) * denominator),
                                             a * c / ((b * b + c * c) * denominator),
                                             a * b * (a * a + b * b + 2 * c * c) /
                                                 ((a * a + c * c) * (b * b + c * c) * denominator));
            };

            // Shift the x and y coordinates by plus/minus half the implant size:
            double x1 = x - implant.x() / 2;
            double x2 = x + implant.x() / 2;
            double y1 = y - implant.y() / 2;
            double y2 = y + implant.y() / 2;

            // Sum the four components of the "g" function and return:
            return (fraction(x1, y1, u) + fraction(x2, y2, u) - fraction(x1, y2, u) - fraction(x2, y1, u));
        };

        // Transform into coordinate system with sensor between d/2 < z < -d/2:
        auto d = thickness_domain.second - thickness_domain.first;
        auto local_z = -pos.z() + thickness_domain.second;

        // Calculate the series expansion
        ROOT::Math::XYZVector sum;
        for(int n = 1; n <= 100; n++) {
            sum += g(pos.x(), pos.y(), 2 * n * d - local_z) +
                   ROOT::Math::RotationZ(M_PI) * g(pos.x(), pos.y(), 2 * n * d + local_z);
        }

        return (1 / (2 * M_PI) * (ROOT::Math::RotationZ(M_PI) * g(pos.x(), pos.y(), local_z) + sum));
    };
}

void WeightingFieldReaderModule::create_output_plots() {
    LOG(TRACE) << "Creating output plots";

    auto steps = config_.get<size_t>("output_plots_steps", 500);
    auto position = config_.get<ROOT::Math::XYPoint>("output_plots_position", ROOT::Math::XYPoint(0, 0));

    auto model = detector_->getModel();

    double min = model->getSensorCenter().z() - model->getSensorSize().z() / 2.0;
    double max = model->getSensorCenter().z() + model->getSensorSize().z() / 2.0;

    // Create 1D histograms
    auto histogramX =
        new TH1F("field1d_x", "E_{w}/V_{w} (x-component);x (mm);field strength (1/cm)", static_cast<int>(steps), min, max);
    auto histogramY =
        new TH1F("field1d_y", "E_{w}/V_{w} (y-component);y (mm);field strength (1/cm)", static_cast<int>(steps), min, max);
    auto histogramZ =
        new TH1F("field1d_z", "E_{w}/V_{w} (z-component);z (mm);field strength (1/cm)", static_cast<int>(steps), min, max);

    // Get the weighting field at every index
    for(size_t j = 0; j < steps; ++j) {
        double z = min + ((static_cast<double>(j) + 0.5) / static_cast<double>(steps)) * (max - min);

        // Get field strength from detector
        auto field = detector_->getWeightingField(ROOT::Math::XYZPoint(position.x(), position.y(), z), 0, 0);
        auto field_x_strength = Units::convert(field.x(), "1/cm");
        auto field_y_strength = Units::convert(field.y(), "1/cm");
        auto field_z_strength = Units::convert(field.z(), "1/cm");

        // Fill the histograms
        histogramX->Fill(z, static_cast<double>(field_x_strength));
        histogramY->Fill(z, static_cast<double>(field_y_strength));
        histogramZ->Fill(z, static_cast<double>(field_z_strength));
    }

    // Create 2D histogram
    auto histogram = new TH2F("field_z",
                              "E_{w}/V_{w} (z-component);x (mm); z (mm); field strength (1/cm)",
                              static_cast<int>(steps),
                              -1.5 * model->getPixelSize().x(),
                              1.5 * model->getPixelSize().x(),
                              static_cast<int>(steps),
                              min,
                              max);
    // histogram->SetMinimum(0);

    // Get the weighting field at every index
    for(size_t j = 0; j < steps; ++j) {
        LOG_PROGRESS(INFO, "plotting") << "Plotting progress " << 100 * j * steps / (steps * steps) << "%";
        for(size_t k = 0; k < steps; ++k) {
            double z = min + ((static_cast<double>(j) + 0.5) / static_cast<double>(steps)) * (max - min);
            double x = -0.5 * model->getPixelSize().x() +
                       ((static_cast<double>(k) + 0.5) / static_cast<double>(steps)) * 3 * model->getPixelSize().x();

            // LOG(DEBUG) << "Requesting field ad local coords (" << Units::display(x, {"cm", "mm", "um"}) << "," << 0;
            // Get field strength from detector
            auto field = detector_->getWeightingField(ROOT::Math::XYZPoint(x, 0, z), 1, 0);
            auto field_z_strength = Units::convert(field.z(), "1/cm");

            // Fill the histograms, shift x-axis by one pixel so the reference electrode in centered.
            histogram->Fill(x - model->getPixelSize().x(), z, static_cast<double>(field_z_strength));
        }
    }

    // Write the histogram to module file
    histogramX->Write();
    histogramY->Write();
    histogramZ->Write();
    histogram->Write();
}

/**
 * The field read from the INIT format are shared between module instantiations
 * using the static WeightingFieldReaderModule::get_by_file_name method.
 */
FieldParser<double, 3> WeightingFieldReaderModule::field_parser_("");
FieldData<double> WeightingFieldReaderModule::read_init_field(std::pair<double, double> thickness_domain) {
    using namespace ROOT::Math;

    try {
        LOG(TRACE) << "Fetching weighting field from init file";

        // Get field from file
        auto field_data = field_parser_.get_by_file_name(config_.getPath("file_name", true));

        // Check if electric field matches chip
        check_detector_match(std::get<2>(field_data), thickness_domain);

        LOG(INFO) << "Set weighting field with " << std::get<1>(field_data).at(0) << "x" << std::get<1>(field_data).at(1)
                  << "x" << std::get<1>(field_data).at(2) << " cells";

        // Return the field data
        return field_data;
    } catch(std::invalid_argument& e) {
        throw InvalidValueError(config_, "file_name", e.what());
    } catch(std::runtime_error& e) {
        throw InvalidValueError(config_, "file_name", e.what());
    } catch(std::bad_alloc& e) {
        throw InvalidValueError(config_, "file_name", "file too large");
    }
}

/**
 * @brief Check if the detector matches the file header
 */
void WeightingFieldReaderModule::check_detector_match(std::array<double, 3> dimensions,
                                                      std::pair<double, double> thickness_domain) {
    auto xpixsz = dimensions[0];
    auto ypixsz = dimensions[1];
    auto thickness = dimensions[2];

    auto model = detector_->getModel();
    // Do a several checks with the detector model
    if(model != nullptr) {
        // Check field dimension in z versus the requested thickness domain:
        auto eff_thickness = thickness_domain.second - thickness_domain.first;
        if(std::fabs(thickness - eff_thickness) > std::numeric_limits<double>::epsilon()) {
            LOG(WARNING) << "Thickness of weighting field is " << Units::display(thickness, "um")
                         << " but the depleted region is " << Units::display(eff_thickness, "um");
        }

        // Check that the total field size is n*pitch:
        if(std::fmod(xpixsz, model->getPixelSize().x()) > std::numeric_limits<double>::epsilon() ||
           std::fmod(ypixsz, model->getPixelSize().y()) > std::numeric_limits<double>::epsilon()) {
            LOG(WARNING) << "Field size is (" << Units::display(xpixsz, {"um", "mm"}) << ","
                         << Units::display(ypixsz, {"um", "mm"}) << ") but expecting a multiple of the pixel pitch ("
                         << Units::display(model->getPixelSize().x(), {"um", "mm"}) << ", "
                         << Units::display(model->getPixelSize().y(), {"um", "mm"}) << ")";
        }
    }
}
<|endoftext|>


<commit_before>#include <string>
#include <vector>
#include <iostream>
#include "timer.h"

#include <boost/mpi.hpp>
#include <boost/serialization/string.hpp>
#include <iostream>

#include "network_node.h"
#include "rdma_resource.h"
#include <pthread.h>
using namespace std;
struct Thread_config{
  int id;
  boost::mpi::communicator* world;
};
int socket_0[] = {
  0,2,4,6,8,10,12,14,16,18
};
void pin_to_core(size_t core) {
  cpu_set_t  mask;
  CPU_ZERO(&mask);
  CPU_SET(core , &mask);
  int result=sched_setaffinity(0, sizeof(mask), &mask);
}
#define NUM_SENDER 4
#define NUM_RECVER 1
#define NUM_THREAD (NUM_RECVER+NUM_SENDER)

void* Run(void *ptr) {
  struct Thread_config *config = (struct Thread_config*) ptr;
  pin_to_core(socket_0[config->id]);

  Network_Node *node = new Network_Node(config->world->rank(),config->id);
  //str[0]-'0' is machine id;
  //str[1]-'0' is thread id;
  string str="";
  str.push_back(config->world->rank());
  str.push_back(config->id);
  str.push_back(0);
  for(int i=0;i<97;i++){
  	str.push_back('0');
  }
  unsigned int seed=config->world->rank()*100+config->id;
  if(config->id < NUM_RECVER){
  	//recv
  	int end_num=0;
  	timer t1;
  	timer t2;
  	while(true){
  		string tmp=node->Recv();
  		int mid=tmp[0];
  		int tid=tmp[1];
  		int count=tmp[2];
  		if(count==10){
  			end_num++;
  			if(end_num==10000){
  				end_num=0;
	  			t2.reset();
	  			cout<<endl<<"finished in "<<t2.diff(t1)<<" ms"<<endl;
	  			t1.reset();
  			}
  		}
  		else{
  			tmp[2]=tmp[2]+1;
  			node->Send(rand_r(&seed)%config->world->size(), rand_r(&seed)%NUM_RECVER, tmp);
  		}
  	}
  } else {
  	//send
  	sleep(1);
	timer t1;

	for(int i=0;i<1000*10000;i++){
		node->Send(i%config->world->size(), rand_r(&seed)%NUM_RECVER, str);
		usleep(1);
	}
	timer t2;

	cout<<endl<<"requests finished in "<<t2.diff(t1)<<" ms"<<endl;

  }
}

int main(int argc, char * argv[])
{

	boost::mpi::environment env(argc, argv);
	boost::mpi::communicator world;

	uint64_t rdma_size = 1024*1024*1024;  //1G
  	uint64_t slot_per_thread= 1024*1024*128;
  	//rdma_size = rdma_size*20; //20G
  	uint64_t total_size=rdma_size+slot_per_thread*NUM_THREAD;
	Network_Node *node = new Network_Node(world.rank(),NUM_THREAD);
	char *buffer= (char*) malloc(total_size);
	RdmaResource *rdma=new RdmaResource(world.size(),NUM_THREAD,world.rank(),buffer,total_size,slot_per_thread,rdma_size);
	rdma->node = node;
	rdma->Servicing();
	rdma->Connect();

	uint64_t *local_buffer = (uint64_t *)rdma->GetMsgAddr(0);
  	uint64_t start_addr=0;
  	//rdma->RdmaRead(0,(world.rank()+1)%world.size() ,(char *)local_buffer,100,start_addr);
  	//cout<<"Fucking OK"<<endl;

	Thread_config *configs = new Thread_config[NUM_THREAD];
  	pthread_t     *thread  = new pthread_t[NUM_THREAD];
	for(size_t id = 0;id < NUM_THREAD;++id) {
      configs[id].id = id;
      configs[id].world = &world;
      pthread_create (&(thread[id]), NULL, Run, (void *) &(configs[id]));
    }
    for(size_t t = 0 ; t < NUM_THREAD; t++) {
      int rc = pthread_join(thread[t], NULL);
      if (rc) {
        printf("ERROR; return code from pthread_join() is %d\n", rc);
        exit(-1);
      }
    }
    return 0;
}
<commit_msg>refine micro_bench code<commit_after>#include <string>
#include <vector>
#include <iostream>
#include "timer.h"

#include <boost/mpi.hpp>
#include <boost/serialization/string.hpp>
#include <iostream>

#include "network_node.h"
#include "rdma_resource.h"
#include <pthread.h>
using namespace std;
struct Thread_config{
  int id;
  boost::mpi::communicator* world;
};
int socket_0[] = {
  0,2,4,6,8,10,12,14,16,18
};
void pin_to_core(size_t core) {
  cpu_set_t  mask;
  CPU_ZERO(&mask);
  CPU_SET(core , &mask);
  int result=sched_setaffinity(0, sizeof(mask), &mask);
}
// #define NUM_SENDER 4
// #define NUM_RECVER 1
// #define NUM_THREAD (NUM_RECVER+NUM_SENDER)

int NUM_SENDER;
int NUM_RECVER;
int NUM_THREAD;
int batch_factor;
int extra_work;
void* Run(void *ptr) {
  struct Thread_config *config = (struct Thread_config*) ptr;
  pin_to_core(socket_0[config->id]);

  Network_Node *node = new Network_Node(config->world->rank(),config->id);
  //str[0]-'0' is machine id;
  //str[1]-'0' is thread id;
  string str="";
  str.push_back(config->world->rank());
  str.push_back(config->id);
  str.push_back(0);
  for(int i=0;i<97;i++){
  	str.push_back('0');
  }
  unsigned int seed=config->world->rank()*100+config->id;
  if(config->id < NUM_RECVER){
  	//recv
  	int end_num=0;
  	timer t1;
  	timer t2;
  	while(true){
  		string tmp=node->Recv();
      for(int times=0;times<extra_work;times++){
        for(int i=3;i<tmp.size();i++){
          tmp[i]++;
        }
      }
  		int mid=tmp[0];
  		int tid=tmp[1];
  		int count=tmp[2];
  		if(count==10){
        node->Send(mid, tid, tmp);
  			end_num++;
  			if(end_num==10000){
  				end_num=0;
	  			t2.reset();
          if(config->world->rank()==0 && config->id==0)
	  			  cout<<NUM_SENDER<<"\t"<<NUM_RECVER <<"\t"
                <<batch_factor<<"\t"<<extra_work <<"\t"
                <<t2.diff(t1)<<" ms"<<endl;
          //cout<<"("<<config->world->rank()<<","<<config->id<<") finished in "<<t2.diff(t1)<<" ms"<<endl;
	  			t1.reset();
  			}
  		}
  		else{
  			tmp[2]=tmp[2]+1;
  			node->Send(rand_r(&seed)%config->world->size(), rand_r(&seed)%NUM_RECVER, tmp);
  		}
  	}
  } else {
  	//send
  	sleep(1);
	timer t1;

  for(int i=0;i<batch_factor;i++){
    node->Send(rand_r(&seed)%config->world->size(), rand_r(&seed)%NUM_RECVER, str);
  }
	for(int i=0;i<1000*10000;i++){
    node->Recv();
		node->Send(rand_r(&seed)%config->world->size(), rand_r(&seed)%NUM_RECVER, str);
		//usleep(1);
	}
	timer t2;

	cout<<endl<<"requests finished in "<<t2.diff(t1)<<" ms"<<endl;

  }
}

int main(int argc, char * argv[])
{
  if(argc!=5){
    printf("Wrong parameters\n");
    exit(0);
  }
  NUM_SENDER=atoi(argv[1]);
  NUM_RECVER=atoi(argv[2]);
  batch_factor=atoi(argv[3]);
  extra_work=atoi(argv[4]);
  NUM_THREAD=NUM_SENDER+NUM_RECVER;

	boost::mpi::environment env(argc, argv);
	boost::mpi::communicator world;

	uint64_t rdma_size = 1024*1024*1024;  //1G
  	uint64_t slot_per_thread= 1024*1024*128;
  	//rdma_size = rdma_size*20; //20G
  	uint64_t total_size=rdma_size+slot_per_thread*NUM_THREAD;
	Network_Node *node = new Network_Node(world.rank(),NUM_THREAD);
	char *buffer= (char*) malloc(total_size);
	RdmaResource *rdma=new RdmaResource(world.size(),NUM_THREAD,world.rank(),buffer,total_size,slot_per_thread,rdma_size);
	rdma->node = node;
	rdma->Servicing();
	rdma->Connect();

	uint64_t *local_buffer = (uint64_t *)rdma->GetMsgAddr(0);
  	uint64_t start_addr=0;
  	//rdma->RdmaRead(0,(world.rank()+1)%world.size() ,(char *)local_buffer,100,start_addr);
    //cout<<"Fucking OK"<<endl;

	Thread_config *configs = new Thread_config[NUM_THREAD];
  	pthread_t     *thread  = new pthread_t[NUM_THREAD];
	for(size_t id = 0;id < NUM_THREAD;++id) {
      configs[id].id = id;
      configs[id].world = &world;
      pthread_create (&(thread[id]), NULL, Run, (void *) &(configs[id]));
    }
    for(size_t t = 0 ; t < NUM_THREAD; t++) {
      int rc = pthread_join(thread[t], NULL);
      if (rc) {
        printf("ERROR; return code from pthread_join() is %d\n", rc);
        exit(-1);
      }
    }
    return 0;
}
<|endoftext|>