<commit_before>/*
 * Copyright (c) 2012, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <ORGANIZATION> nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

// Author: E. Gil Jones

#include <moveit_visualization_ros/planning_scene_file_menu.h>
#include <moveit_visualization_ros/qt_helper_functions.h>

#include <QAction>
#include <QFileDialog>

namespace moveit_visualization_ros
{

PlanningSceneFileMenu::PlanningSceneFileMenu(QWidget* parent)
  : QMenu("Scene Files", parent)
{
  database_dialog_ = new PlanningSceneDatabaseDialog(this);

  QAction* connect_to_new_database = addAction("Connect to Planning Scene Database");
  save_current_scene_ = addAction("Save Current Planning Scene");
  save_current_scene_->setDisabled(true);
  load_planning_scene_ = addAction("Load Scene From Database");
  load_planning_scene_->setDisabled(true);
  //QAction* new_planning_scene = addAction("Create New Planning Scene...");

  connect(connect_to_new_database, SIGNAL(triggered()), SLOT(connectToNewDatabaseSignalled()));
  connect(save_current_scene_, SIGNAL(triggered()), SLOT(saveCurrentPlanningSceneSignalled()));
  connect(load_planning_scene_, SIGNAL(triggered()), SLOT(loadPlanningSceneSignalled()));
}

void PlanningSceneFileMenu::updatePlanningSceneSignalled(planning_scene::PlanningSceneConstPtr planning_scene)
{
  planning_scene_ = planning_scene;
}

void PlanningSceneFileMenu::connectToNewDatabaseSignalled() {
  QFileDialog dialog(this);
  dialog.setFileMode(QFileDialog::DirectoryOnly);
  dialog.setOption(QFileDialog::ShowDirsOnly, true);
  if(dialog.exec()) {
    QStringList dirnames = dialog.selectedFiles();
    warehouse_connector_.connectToDatabase(dirnames[0].toStdString(), storage_);
    save_current_scene_->setEnabled(true);
    load_planning_scene_->setEnabled(true);
  }
}

void PlanningSceneFileMenu::loadPlanningSceneSignalled() {
  database_dialog_->populateDatabaseDialog(storage_);
  database_dialog_->exec();
}

void PlanningSceneFileMenu::saveCurrentPlanningSceneSignalled() {
  moveit_msgs::PlanningScene scene;
  planning_scene_->getPlanningSceneMsg(scene);
  scene.robot_state.joint_state.header.stamp = ros::Time(ros::WallTime::now().toSec());
  storage_->addPlanningScene(scene);
}

}
<commit_msg>Updating given change in warehouse<commit_after>/*
 * Copyright (c) 2012, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <ORGANIZATION> nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

// Author: E. Gil Jones

#include <moveit_visualization_ros/planning_scene_file_menu.h>
#include <moveit_visualization_ros/qt_helper_functions.h>

#include <QAction>
#include <QFileDialog>

namespace moveit_visualization_ros
{

PlanningSceneFileMenu::PlanningSceneFileMenu(QWidget* parent)
  : QMenu("Scene Files", parent),
    warehouse_connector_("/opt/ros/fuerte/stacks/warehousewg/mongodb/mongo/bin/mongod")
{
  database_dialog_ = new PlanningSceneDatabaseDialog(this);

  QAction* connect_to_new_database = addAction("Connect to Planning Scene Database");
  save_current_scene_ = addAction("Save Current Planning Scene");
  save_current_scene_->setDisabled(true);
  load_planning_scene_ = addAction("Load Scene From Database");
  load_planning_scene_->setDisabled(true);
  //QAction* new_planning_scene = addAction("Create New Planning Scene...");

  connect(connect_to_new_database, SIGNAL(triggered()), SLOT(connectToNewDatabaseSignalled()));
  connect(save_current_scene_, SIGNAL(triggered()), SLOT(saveCurrentPlanningSceneSignalled()));
  connect(load_planning_scene_, SIGNAL(triggered()), SLOT(loadPlanningSceneSignalled()));
}

void PlanningSceneFileMenu::updatePlanningSceneSignalled(planning_scene::PlanningSceneConstPtr planning_scene)
{
  planning_scene_ = planning_scene;
}

void PlanningSceneFileMenu::connectToNewDatabaseSignalled() {
  QFileDialog dialog(this);
  dialog.setFileMode(QFileDialog::DirectoryOnly);
  dialog.setOption(QFileDialog::ShowDirsOnly, true);
  if(dialog.exec()) {
    QStringList dirnames = dialog.selectedFiles();
    warehouse_connector_.connectToDatabase(dirnames[0].toStdString(), storage_);
    save_current_scene_->setEnabled(true);
    load_planning_scene_->setEnabled(true);
  }
}

void PlanningSceneFileMenu::loadPlanningSceneSignalled() {
  database_dialog_->populateDatabaseDialog(storage_);
  database_dialog_->exec();
}

void PlanningSceneFileMenu::saveCurrentPlanningSceneSignalled() {
  moveit_msgs::PlanningScene scene;
  planning_scene_->getPlanningSceneMsg(scene);
  scene.robot_state.joint_state.header.stamp = ros::Time(ros::WallTime::now().toSec());
  storage_->addPlanningScene(scene);
}

}
<|endoftext|>


<commit_before>/**
 * @file neuron_layer.hpp
 * @author Marcus Edel
 * @author Shangtong Zhang
 *
 * Definition of the NeuronLayer class, which implements a standard network
 * layer for 1-dimensional or 2-dimensional data.
 */
#ifndef __MLPACK_METHOS_ANN_LAYER_NEURON_LAYER_HPP
#define __MLPACK_METHOS_ANN_LAYER_NEURON_LAYER_HPP

#include <mlpack/core.hpp>
#include <mlpack/methods/ann/layer/layer_traits.hpp>
#include <mlpack/methods/ann/activation_functions/logistic_function.hpp>
#include <mlpack/methods/ann/activation_functions/rectifier_function.hpp>

namespace mlpack {
namespace ann /** Artificial Neural Network. */ {

/**
 * An implementation of a standard network layer.
 *
 * This class allows the specification of the type of the activation function.
 *
 * A few convenience typedefs are given:
 *
 *  - InputLayer
 *  - HiddenLayer
 *  - ReluLayer
 *
 * @tparam ActivationFunction Activation function used for the embedding layer.
 * @tparam DataType Type of data (arma::mat or arma::colvec).
 */
template <
    class ActivationFunction = LogisticFunction,
    typename DataType = arma::colvec
>
class NeuronLayer
{
 public:
  /**
   * Create 2-dimensional NeuronLayer object using the specified rows and columns.
   * In this case, DataType must be aram::mat or other matrix type.
   *
   * @param layerRows The number of rows of neurons.
   * @param layerCols The number of columns of neurons.
   */
  NeuronLayer(const size_t layerRows, const size_t layerCols) :
      layerRows(layerRows), layerCols(layerCols),
      localInputAcitvations(arma::ones<DataType>(layerRows, layerCols)),
      inputActivations(localInputAcitvations),
      localDelta(arma::zeros<DataType>(layerRows, layerCols)),
      delta(localDelta)
  {
    // Nothing to do.
  }

  /**
   * Create 2-dimensional NeuronLayer object using the specified inputActivations and delta.
   * This allow shared memory among layers,
   * which make it easier to combine layers together in some special condition.
   *
   * @param inputActivations Outside storage for storing input activations.
   * @param delta Outside storage for storing delta,
   *        the passed error in backward propagation.
   */
  NeuronLayer(DataType& inputActivations, DataType& delta) :
      layerRows(inputActivations.n_rows),
      layerCols(inputActivations.n_cols),
      inputActivations(inputActivations),
      delta(delta)
  {
    // Nothing to do.
  }

  /**
   * Create 1-dimensional NeuronLayer object using the specified layer size.
   * In this case, DataType must be aram::colvec or other vector type.
   *
   * @param layerSize The number of neurons.
   */
  NeuronLayer(const size_t layerSize) :
      layerRows(layerSize), layerCols(1),
      localInputAcitvations(arma::ones<DataType>(layerRows)),
      inputActivations(localInputAcitvations),
      localDelta(arma::zeros<DataType>(layerRows)),
      delta(localDelta)
  {
    // Nothing to do.
  }

  /**
   * Copy Constructor
   */
  NeuronLayer(const NeuronLayer& l) :
      layerRows(l.layerRows), layerCols(l.layerCols),
      localInputAcitvations(l.localInputAcitvations),
      inputActivations(l.localInputAcitvations.n_elem == 0 ?
                       l.inputActivations : localInputAcitvations),
      localDelta(l.localDelta),
      delta(l.localDelta.n_elem == 0 ? l.delta : localDelta)
  {
    // Nothing to do.
  }

  /**
   * Ordinary feed forward pass of a neural network, evaluating the function
   * f(x) by propagating the activity forward through f.
   *
   * @param inputActivation Input data used for evaluating the specified
   * activity function.
   * @param outputActivation Data to store the resulting output activation.
   */
  void FeedForward(const DataType& inputActivation, DataType& outputActivation)
  {
    ActivationFunction::fn(inputActivation, outputActivation);
  }

  /**
   * Ordinary feed backward pass of a neural network, calculating the function
   * f(x) by propagating x backwards trough f. Using the results from the feed
   * forward pass.
   *
   * @param inputActivation Input data used for calculating the function f(x).
   * @param error The backpropagated error.
   * @param delta The passed error in backward propagation.
   */
  void FeedBackward(const DataType& inputActivation,
                    const DataType& error,
                    DataType& delta)
  {
    DataType derivative;
    ActivationFunction::deriv(inputActivation, derivative);
    delta = error % derivative;
  }

  //! Get the input activations.
  DataType& InputActivation() const { return inputActivations; }
  //! Modify the input activations.
  DataType& InputActivation() { return inputActivations; }

  //! Get the error passed in backward propagation.
  DataType& Delta() const { return delta; }
  //! Modify the error passed in backward propagation.
  DataType& Delta() { return delta; }

  //! Get the number of layer rows.
  size_t LayerRows() const { return layerRows; }

  //! Get the number of layer colums.
  size_t LayerCols() const { return layerCols; }

  /**
   * Get the number of layer size.
   * Only for 1-dimsenional type.
   */
  size_t InputSize() const { return layerRows; }

  /**
   * Get the number of lyaer size.
   * Only for 1-dimsenional type.
   */
  size_t OutputSize() const { return layerRows; }

 private:
  //! Locally-stored number of layer rows.
  size_t layerRows;

  //! Locally-stored number of layer cols.
  size_t layerCols;

  //! Locally-stored input activation object.
  DataType localInputAcitvations;

  //! Reference to locally-stored or outside input activation object.
  DataType& inputActivations;

  //! Locally-stored delta object.
  DataType localDelta;

  //! Reference to locally-stored or outside delta object.
  DataType& delta;

}; // class NeuronLayer

// Convenience typedefs.

/**
 * Standard Input-Layer using the logistic activation function.
 */
template <
    class ActivationFunction = LogisticFunction,
    typename DataType = arma::colvec
>
using InputLayer = NeuronLayer<ActivationFunction, DataType>;

/**
 * Standard Hidden-Layer using the logistic activation function.
 */
template <
    class ActivationFunction = LogisticFunction,
    typename DataType = arma::colvec
>
using HiddenLayer = NeuronLayer<ActivationFunction, DataType>;

/**
 * Layer of rectified linear units (relu) using the rectifier activation
 * function.
 */
template <
    class ActivationFunction = RectifierFunction,
    typename DataType = arma::colvec
>
using ReluLayer = NeuronLayer<ActivationFunction, DataType>;

}; // namespace ann
}; // namespace mlpack

#endif
<commit_msg>Refactor neuron layer class to support 3rd order tensors.<commit_after>/**
 * @file neuron_layer.hpp
 * @author Marcus Edel
 * @author Shangtong Zhang
 *
 * Definition of the NeuronLayer class, which implements a standard network
 * layer.
 */
#ifndef __MLPACK_METHOS_ANN_LAYER_NEURON_LAYER_HPP
#define __MLPACK_METHOS_ANN_LAYER_NEURON_LAYER_HPP

#include <mlpack/core.hpp>
#include <mlpack/methods/ann/layer/layer_traits.hpp>
#include <mlpack/methods/ann/activation_functions/logistic_function.hpp>
#include <mlpack/methods/ann/activation_functions/rectifier_function.hpp>

namespace mlpack {
namespace ann /** Artificial Neural Network. */ {

/**
 * An implementation of a standard network layer.
 *
 * This class allows the specification of the type of the activation function.
 *
 * A few convenience typedefs are given:
 *
 *  - InputLayer
 *  - HiddenLayer
 *  - ReluLayer
 *
 * @tparam ActivationFunction Activation function used for the embedding layer.
 * @tparam DataType Type of data (arma::colvec, arma::mat or arma::sp_mat,
 * arma::cube).
 */
template <
    class ActivationFunction = LogisticFunction,
    typename DataType = arma::colvec
>
class NeuronLayer

{
 public:
  /**
   * Create the NeuronLayer object using the specified number of neurons.
   *
   * @param layerSize The number of neurons.
   */
  NeuronLayer(const size_t layerSize) :
      inputActivations(arma::zeros<DataType>(layerSize)),
      delta(arma::zeros<DataType>(layerSize)),
      layerRows(layerSize),
      layerSlices(1)
  {
    // Nothing to do here.
  }

  NeuronLayer(const size_t layerRows, const size_t layerCols) :
      inputActivations(arma::zeros<DataType>(layerRows, layerCols)),
      delta(arma::zeros<DataType>(layerRows, layerCols)),
      layerRows(layerRows),
      layerCols(layerCols),
      layerSlices(1)
  {
    // Nothing to do here.
  }

  NeuronLayer(const size_t layerRows,
              const size_t layerCols,
              const size_t layerSlices) :
      inputActivations(arma::zeros<DataType>(layerRows, layerCols, layerSlices)),
      delta(arma::zeros<DataType>(layerRows, layerCols, layerSlices)),
      layerRows(layerRows),
      layerCols(layerCols),
      layerSlices(layerSlices)
  {
    // Nothing to do here.
  }

  /**
   * Ordinary feed forward pass of a neural network, evaluating the function
   * f(x) by propagating the activity forward through f.
   *
   * @param inputActivation Input data used for evaluating the specified
   * activity function.
   * @param outputActivation Data to store the resulting output activation.
   */
  void FeedForward(const DataType& inputActivation,
                   DataType& outputActivation)
  {
    ActivationFunction::fn(inputActivation, outputActivation);
  }

  /**
   * Ordinary feed backward pass of a neural network, calculating the function
   * f(x) by propagating x backwards trough f. Using the results from the feed
   * forward pass.
   *
   * @param inputActivation Input data used for calculating the function f(x).
   * @param error The backpropagated error.
   * @param delta The calculating delta using the partial derivative of the
   * error with respect to a weight.
   */
  void FeedBackward(const DataType& inputActivation,
                    const DataType& error,
                    DataType& delta)
  {
    DataType derivative;
    ActivationFunction::deriv(inputActivation, derivative);
    delta = error % derivative;
  }

  /**
   * Ordinary feed backward pass of a neural network, calculating the function
   * f(x) by propagating x backwards trough f. Using the results from the feed
   * forward pass.
   *
   * @param inputActivation Input data used for calculating the function f(x).
   * @param error The backpropagated error.
   * @param delta The calculating delta using the partial derivative of the
   * error with respect to a weight.
   */
  template<typename eT>
  void FeedBackward(const arma::Cube<eT>& inputActivation,
                    const arma::Mat<eT>& error,
                    arma::Cube<eT>& delta)
  {
    DataType derivative;
    ActivationFunction::deriv(inputActivation, derivative);
    delta = arma::cube(error.memptr(), inputActivation.n_rows,
        inputActivation.n_cols, inputActivation.n_slices) % derivative;
  }

  //! Get the input activations.
  DataType& InputActivation() const { return inputActivations; }
  //  //! Modify the input activations.
  DataType& InputActivation() { return inputActivations; }

  //! Get the detla.
  DataType& Delta() const { return delta; }
  //! Modify the delta.
  DataType& Delta() { return delta; }

  //! Get input size.
  size_t InputSize() const { return layerRows; }
  //! Modify the delta.
  size_t& InputSize() { return layerRows; }

  //! Get output size.
  size_t OutputSize() const { return layerRows; }
  //! Modify the output size.
  size_t& OutputSize() { return layerRows; }

  //! Get the number of layer rows.
  size_t LayerRows() const { return layerRows; }
  //! Modify the number of layer rows.
  size_t& LayerRows() { return layerRows; }

  //! Get the number of layer columns.
  size_t LayerCols() const { return layerCols; }
  //! Modify the number of layer columns.
  size_t& LayerCols() { return layerCols; }

  //! Get the number of layer slices.
  size_t LayerSlices() const { return layerSlices; }

 private:
  //! Locally-stored input activation object.
  DataType inputActivations;

  //! Locally-stored delta object.
  DataType delta;

  //! Locally-stored number of layer rows.
  size_t layerRows;

  //! Locally-stored number of layer cols.
  size_t layerCols;

  //! Locally-stored number of layer slices.
  size_t layerSlices;
}; // class NeuronLayer

// Convenience typedefs.

/**
 * Standard Input-Layer using the logistic activation function.
 */
template <
    class ActivationFunction = LogisticFunction,
    typename DataType = arma::colvec
>
using InputLayer = NeuronLayer<ActivationFunction, DataType>;

/**
 * Standard Hidden-Layer using the logistic activation function.
 */
template <
    class ActivationFunction = LogisticFunction,
    typename DataType = arma::colvec
>
using HiddenLayer = NeuronLayer<ActivationFunction, DataType>;

/**
 * Layer of rectified linear units (relu) using the rectifier activation
 * function.
 */
template <
    class ActivationFunction = RectifierFunction,
    typename DataType = arma::colvec
>
using ReluLayer = NeuronLayer<ActivationFunction, DataType>;

}; // namespace ann
}; // namespace mlpack

#endif
<|endoftext|>


<commit_before><commit_msg>[ADD] added a buggy select implementation (commented out for now) and a proper shutdown of the socket to avoid being stuck accept. Solution seems suboptimal but works as expected<commit_after><|endoftext|>


<commit_before>/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "modules/video_coding/codecs/test/stats.h"

#include <algorithm>  // min_element, max_element
#include <cassert>
#include <cstdio>

namespace webrtc {
namespace test {

Stats::Stats() {}

Stats::~Stats() {}

bool LessForEncodeTime(const FrameStatistic& s1, const FrameStatistic& s2) {
    return s1.encode_time_in_us < s2.encode_time_in_us;
}

bool LessForDecodeTime(const FrameStatistic& s1, const FrameStatistic& s2) {
    return s1.decode_time_in_us < s2.decode_time_in_us;
}

bool LessForEncodedSize(const FrameStatistic& s1, const FrameStatistic& s2) {
    return s1.encoded_frame_length_in_bytes < s2.encoded_frame_length_in_bytes;
}

bool LessForBitRate(const FrameStatistic& s1, const FrameStatistic& s2) {
    return s1.bit_rate_in_kbps < s2.bit_rate_in_kbps;
}

FrameStatistic& Stats::NewFrame(int frame_number) {
  assert(frame_number >= 0);
  FrameStatistic stat;
  stat.frame_number = frame_number;
  stats_.push_back(stat);
  return stats_[frame_number];
}

void Stats::PrintSummary() {
  printf("Processing summary:\n");
  if (stats_.size() == 0) {
    printf("No frame statistics have been logged yet.\n");
    return;
  }

  // Calculate min, max, average and total encoding time
  int total_encoding_time_in_us = 0;
  int total_decoding_time_in_us = 0;
  int total_encoded_frames_lengths = 0;
  int total_encoded_key_frames_lengths = 0;
  int total_encoded_nonkey_frames_lengths = 0;
  int nbr_keyframes = 0;
  int nbr_nonkeyframes = 0;

  for (FrameStatisticsIterator it = stats_.begin();
      it != stats_.end(); ++it) {
    total_encoding_time_in_us += it->encode_time_in_us;
    total_decoding_time_in_us += it->decode_time_in_us;
    total_encoded_frames_lengths += it->encoded_frame_length_in_bytes;
    if (it->frame_type == webrtc::kKeyFrame) {
      total_encoded_key_frames_lengths += it->encoded_frame_length_in_bytes;
      nbr_keyframes++;
    } else {
      total_encoded_nonkey_frames_lengths += it->encoded_frame_length_in_bytes;
      nbr_nonkeyframes++;
    }
  }

  FrameStatisticsIterator frame;

  // ENCODING
  printf("Encoding time:\n");
  frame = min_element(stats_.begin(),
                      stats_.end(), LessForEncodeTime);
  printf("  Min     : %7d us (frame %d)\n",
         frame->encode_time_in_us, frame->frame_number);

  frame = max_element(stats_.begin(),
                      stats_.end(), LessForEncodeTime);
  printf("  Max     : %7d us (frame %d)\n",
         frame->encode_time_in_us, frame->frame_number);

  printf("  Average : %7d us\n",
         total_encoding_time_in_us / stats_.size());

  // DECODING
  printf("Decoding time:\n");
  // only consider frames that were successfully decoded (packet loss may cause
  // failures)
  std::vector<FrameStatistic> decoded_frames;
  for (std::vector<FrameStatistic>::iterator it = stats_.begin();
      it != stats_.end(); ++it) {
    if (it->decoding_successful) {
      decoded_frames.push_back(*it);
    }
  }
  if (decoded_frames.size() == 0) {
    printf("No successfully decoded frames exist in this statistics.\n");
  } else {
    frame = min_element(decoded_frames.begin(),
                        decoded_frames.end(), LessForDecodeTime);
    printf("  Min     : %7d us (frame %d)\n",
           frame->decode_time_in_us, frame->frame_number);

    frame = max_element(decoded_frames.begin(),
                        decoded_frames.end(), LessForDecodeTime);
    printf("  Max     : %7d us (frame %d)\n",
           frame->decode_time_in_us, frame->frame_number);

    printf("  Average : %7d us\n",
           total_decoding_time_in_us / decoded_frames.size());
    printf("  Failures: %d frames failed to decode.\n",
        (stats_.size() - decoded_frames.size()));
  }

  // SIZE
  printf("Frame sizes:\n");
  frame = min_element(stats_.begin(),
                      stats_.end(), LessForEncodedSize);
  printf("  Min     : %7d bytes (frame %d)\n",
         frame->encoded_frame_length_in_bytes, frame->frame_number);

  frame = max_element(stats_.begin(),
                      stats_.end(), LessForEncodedSize);
  printf("  Max     : %7d bytes (frame %d)\n",
         frame->encoded_frame_length_in_bytes, frame->frame_number);

  printf("  Average : %7d bytes\n",
         total_encoded_frames_lengths / stats_.size());
  if (nbr_keyframes > 0) {
    printf("  Average key frame size    : %7d bytes (%d keyframes)\n",
           total_encoded_key_frames_lengths / nbr_keyframes,
           nbr_keyframes);
  }
  if (nbr_nonkeyframes > 0) {
    printf("  Average non-key frame size: %7d bytes (%d frames)\n",
           total_encoded_nonkey_frames_lengths / nbr_nonkeyframes,
           nbr_nonkeyframes);
  }

  // BIT RATE
  printf("Bit rates:\n");
  frame = min_element(stats_.begin(),
                      stats_.end(), LessForBitRate);
  printf("  Min bit rate: %7d kbps (frame %d)\n",
         frame->bit_rate_in_kbps, frame->frame_number);

  frame = max_element(stats_.begin(),
                      stats_.end(), LessForBitRate);
  printf("  Max bit rate: %7d kbps (frame %d)\n",
         frame->bit_rate_in_kbps, frame->frame_number);

  printf("\n");
  printf("Total encoding time  : %7d ms.\n",
         total_encoding_time_in_us / 1000);
  printf("Total decoding time  : %7d ms.\n",
         total_decoding_time_in_us / 1000);
  printf("Total processing time: %7d ms.\n",
         (total_encoding_time_in_us + total_decoding_time_in_us) / 1000);
}

}  // namespace test
}  // namespace webrtc
<commit_msg>Fixing compilation error on Linux 64-bit<commit_after>/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "modules/video_coding/codecs/test/stats.h"

#include <algorithm>  // min_element, max_element
#include <cassert>
#include <cstdio>

namespace webrtc {
namespace test {

Stats::Stats() {}

Stats::~Stats() {}

bool LessForEncodeTime(const FrameStatistic& s1, const FrameStatistic& s2) {
    return s1.encode_time_in_us < s2.encode_time_in_us;
}

bool LessForDecodeTime(const FrameStatistic& s1, const FrameStatistic& s2) {
    return s1.decode_time_in_us < s2.decode_time_in_us;
}

bool LessForEncodedSize(const FrameStatistic& s1, const FrameStatistic& s2) {
    return s1.encoded_frame_length_in_bytes < s2.encoded_frame_length_in_bytes;
}

bool LessForBitRate(const FrameStatistic& s1, const FrameStatistic& s2) {
    return s1.bit_rate_in_kbps < s2.bit_rate_in_kbps;
}

FrameStatistic& Stats::NewFrame(int frame_number) {
  assert(frame_number >= 0);
  FrameStatistic stat;
  stat.frame_number = frame_number;
  stats_.push_back(stat);
  return stats_[frame_number];
}

void Stats::PrintSummary() {
  printf("Processing summary:\n");
  if (stats_.size() == 0) {
    printf("No frame statistics have been logged yet.\n");
    return;
  }

  // Calculate min, max, average and total encoding time
  int total_encoding_time_in_us = 0;
  int total_decoding_time_in_us = 0;
  int total_encoded_frames_lengths = 0;
  int total_encoded_key_frames_lengths = 0;
  int total_encoded_nonkey_frames_lengths = 0;
  int nbr_keyframes = 0;
  int nbr_nonkeyframes = 0;

  for (FrameStatisticsIterator it = stats_.begin();
      it != stats_.end(); ++it) {
    total_encoding_time_in_us += it->encode_time_in_us;
    total_decoding_time_in_us += it->decode_time_in_us;
    total_encoded_frames_lengths += it->encoded_frame_length_in_bytes;
    if (it->frame_type == webrtc::kKeyFrame) {
      total_encoded_key_frames_lengths += it->encoded_frame_length_in_bytes;
      nbr_keyframes++;
    } else {
      total_encoded_nonkey_frames_lengths += it->encoded_frame_length_in_bytes;
      nbr_nonkeyframes++;
    }
  }

  FrameStatisticsIterator frame;

  // ENCODING
  printf("Encoding time:\n");
  frame = min_element(stats_.begin(),
                      stats_.end(), LessForEncodeTime);
  printf("  Min     : %7d us (frame %d)\n",
         frame->encode_time_in_us, frame->frame_number);

  frame = max_element(stats_.begin(),
                      stats_.end(), LessForEncodeTime);
  printf("  Max     : %7d us (frame %d)\n",
         frame->encode_time_in_us, frame->frame_number);

  printf("  Average : %7d us\n",
         static_cast<int>(total_encoding_time_in_us / stats_.size()));

  // DECODING
  printf("Decoding time:\n");
  // only consider frames that were successfully decoded (packet loss may cause
  // failures)
  std::vector<FrameStatistic> decoded_frames;
  for (std::vector<FrameStatistic>::iterator it = stats_.begin();
      it != stats_.end(); ++it) {
    if (it->decoding_successful) {
      decoded_frames.push_back(*it);
    }
  }
  if (decoded_frames.size() == 0) {
    printf("No successfully decoded frames exist in this statistics.\n");
  } else {
    frame = min_element(decoded_frames.begin(),
                        decoded_frames.end(), LessForDecodeTime);
    printf("  Min     : %7d us (frame %d)\n",
           frame->decode_time_in_us, frame->frame_number);

    frame = max_element(decoded_frames.begin(),
                        decoded_frames.end(), LessForDecodeTime);
    printf("  Max     : %7d us (frame %d)\n",
           frame->decode_time_in_us, frame->frame_number);

    printf("  Average : %7d us\n",
           static_cast<int>(total_decoding_time_in_us / decoded_frames.size()));
    printf("  Failures: %d frames failed to decode.\n",
           static_cast<int>(stats_.size() - decoded_frames.size()));
  }

  // SIZE
  printf("Frame sizes:\n");
  frame = min_element(stats_.begin(),
                      stats_.end(), LessForEncodedSize);
  printf("  Min     : %7d bytes (frame %d)\n",
         frame->encoded_frame_length_in_bytes, frame->frame_number);

  frame = max_element(stats_.begin(),
                      stats_.end(), LessForEncodedSize);
  printf("  Max     : %7d bytes (frame %d)\n",
         frame->encoded_frame_length_in_bytes, frame->frame_number);

  printf("  Average : %7d bytes\n",
         static_cast<int>(total_encoded_frames_lengths / stats_.size()));
  if (nbr_keyframes > 0) {
    printf("  Average key frame size    : %7d bytes (%d keyframes)\n",
           total_encoded_key_frames_lengths / nbr_keyframes,
           nbr_keyframes);
  }
  if (nbr_nonkeyframes > 0) {
    printf("  Average non-key frame size: %7d bytes (%d frames)\n",
           total_encoded_nonkey_frames_lengths / nbr_nonkeyframes,
           nbr_nonkeyframes);
  }

  // BIT RATE
  printf("Bit rates:\n");
  frame = min_element(stats_.begin(),
                      stats_.end(), LessForBitRate);
  printf("  Min bit rate: %7d kbps (frame %d)\n",
         frame->bit_rate_in_kbps, frame->frame_number);

  frame = max_element(stats_.begin(),
                      stats_.end(), LessForBitRate);
  printf("  Max bit rate: %7d kbps (frame %d)\n",
         frame->bit_rate_in_kbps, frame->frame_number);

  printf("\n");
  printf("Total encoding time  : %7d ms.\n",
         total_encoding_time_in_us / 1000);
  printf("Total decoding time  : %7d ms.\n",
         total_decoding_time_in_us / 1000);
  printf("Total processing time: %7d ms.\n",
         (total_encoding_time_in_us + total_decoding_time_in_us) / 1000);
}

}  // namespace test
}  // namespace webrtc
<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

=========================================================================*/
#include "otbWrapperQtWidgetParameterGroup.h"
#include "otbWrapperQtWidgetChoiceParameter.h"
#include "otbWrapperQtWidgetParameterLabel.h"
#include "otbWrapperQtWidgetParameterFactory.h"

namespace otb
{
namespace Wrapper
{

QtWidgetParameterGroup::QtWidgetParameterGroup(ParameterGroup::Pointer paramList, QtWidgetModel* m)
: QtWidgetParameterBase(paramList, m),
  m_ParamList(paramList)
{
}

QtWidgetParameterGroup::~QtWidgetParameterGroup()
{
}

void QtWidgetParameterGroup::DoUpdateGUI()
{
  WidgetListIteratorType it = m_WidgetList.begin();
  for (it = m_WidgetList.begin(); it != m_WidgetList.end(); ++it)
    {
    (*it)->UpdateGUI();
    }
}

void QtWidgetParameterGroup::DoCreateWidget()
{
  // a GridLayout with two columns : parameter label / parameter widget
  QGridLayout *gridLayout = new QGridLayout;
  gridLayout->setSpacing(1);
  gridLayout->setContentsMargins(0, 0, 0, 0);

  unsigned int nbParams = m_ParamList->GetNumberOfParameters();
  for (unsigned int i = 0; i < nbParams; ++i)
    {
    Parameter* param = m_ParamList->GetParameterByIndex(i);

    if (param != 0)
      {
      ParameterGroup* paramAsGroup = dynamic_cast<ParameterGroup*>(param);
      ChoiceParameter* paramAsChoice = dynamic_cast<ChoiceParameter*>(param);

      if (paramAsGroup == 0 && paramAsChoice == 0)
        {
        // Label (col 0)
        QWidget* label = new QtWidgetParameterLabel( param );
        gridLayout->addWidget(label, i, 1);

        // Parameter Widget (col 2)
        QtWidgetParameterBase* specificWidget = QtWidgetParameterFactory::CreateQtWidget( param, GetModel() );
        gridLayout->addWidget(specificWidget, i, 2 );

        // CheckBox (col 1)
        QCheckBox * checkBox = new QCheckBox;
        connect( checkBox, SIGNAL(clicked(bool)), specificWidget, SLOT(SetActivationState(bool)));
        connect( checkBox, SIGNAL(clicked(bool)), GetModel(), SLOT(NotifyUpdate()) );
        connect( specificWidget, SIGNAL(ParameterActiveStatus(bool)), checkBox, SLOT(setChecked(bool)));
        connect( specificWidget, SIGNAL(ParameterActiveStatus(bool)), specificWidget, SLOT(SetActivationState(bool)));

        if (param->IsRoot())
           {
          // if Mandatory make the checkbox checked and deactivated
          if (param->GetMandatory())
            {
            checkBox->setCheckState(Qt::Checked);
            checkBox->setEnabled(false);
            specificWidget->setEnabled(true);
            }
          else
            {
            checkBox->setCheckState(Qt::Unchecked);
            checkBox->setEnabled(true);
            specificWidget->setEnabled(false);
            }
          }
        else
          {
          // If this widget belongs to a Group, make it disabled by
          // defaut
          specificWidget->setEnabled(false);
          }
        gridLayout->addWidget(checkBox, i, 0);

        m_WidgetList.push_back(specificWidget);
        }
      else
        {
        QtWidgetParameterBase* specificWidget = QtWidgetParameterFactory::CreateQtWidget( param, GetModel() );

        QVBoxLayout* vboxLayout = new QVBoxLayout;
        vboxLayout->addWidget(specificWidget);
        QGroupBox* group = new QGroupBox;
        group->setLayout(vboxLayout);

        // Make the paramter Group checkable when it is not mandatory
        if (!param->GetMandatory() )
          {
          group->setCheckable(true);
          }
        connect(group, SIGNAL(clicked(bool)), specificWidget, SLOT(SetActivationState(bool)));

        group->setTitle(param->GetName());
        gridLayout->addWidget(group, i, 0, 1, -1);

        m_WidgetList.push_back(specificWidget);
        }
      }
    }

  this->setLayout(gridLayout);
}

// Slot connected to the signal emitted the checkBox relative to
// current widget
void QtWidgetParameterGroup::SetActivationState( bool value )
{
  // First call the superclass implementation
  this->QtWidgetParameterBase::SetActivationState(value);

  // Update the Group status
  this->setEnabled(value);

  // Update iteratively the children status
  for (unsigned int idx = 0; idx < m_ParamList->GetChildrenList().size(); ++idx)
    {
    this->ProcessChild(m_ParamList->GetChildrenList()[idx], value);
    }
}

// Activate iteratively  the children
void QtWidgetParameterGroup::ProcessChild(Parameter* currentNode, bool status)
{
  // Activate the current node if it was checked
  if ( currentNode->IsChecked() && status)
    {
    currentNode->SetActive(status);
    }

  // If the status is false (deactivating) deactivate all the children
  // tree
  if (!status)
    {
    currentNode->SetActive(status);
    }

  unsigned int counter = 0;
  while(counter < currentNode->GetChildrenList().size())
    {
    this->ProcessChild(currentNode->GetChildrenList()[counter], status);
    ++counter;
    }
}

}
}
<commit_msg>ENH: Better handling of a Group and its parameter      Mandatory Group : no checkbox, all the mandatory params are activated      Non Mandatory Group : checkbox (non checked by default), all the params are deactivated<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

=========================================================================*/
#include "otbWrapperQtWidgetParameterGroup.h"
#include "otbWrapperQtWidgetChoiceParameter.h"
#include "otbWrapperQtWidgetParameterLabel.h"
#include "otbWrapperQtWidgetParameterFactory.h"

namespace otb
{
namespace Wrapper
{

QtWidgetParameterGroup::QtWidgetParameterGroup(ParameterGroup::Pointer paramList, QtWidgetModel* m)
: QtWidgetParameterBase(paramList, m),
  m_ParamList(paramList)
{
}

QtWidgetParameterGroup::~QtWidgetParameterGroup()
{
}

void QtWidgetParameterGroup::DoUpdateGUI()
{
  WidgetListIteratorType it = m_WidgetList.begin();
  for (it = m_WidgetList.begin(); it != m_WidgetList.end(); ++it)
    {
    (*it)->UpdateGUI();
    }
}

void QtWidgetParameterGroup::DoCreateWidget()
{
  // a GridLayout with two columns : parameter label / parameter widget
  QGridLayout *gridLayout = new QGridLayout;
  gridLayout->setSpacing(1);
  gridLayout->setContentsMargins(0, 0, 0, 0);

  unsigned int nbParams = m_ParamList->GetNumberOfParameters();
  for (unsigned int i = 0; i < nbParams; ++i)
    {
    Parameter* param = m_ParamList->GetParameterByIndex(i);

    if (param != 0)
      {
      ParameterGroup* paramAsGroup = dynamic_cast<ParameterGroup*>(param);
      ChoiceParameter* paramAsChoice = dynamic_cast<ChoiceParameter*>(param);

      if (paramAsGroup == 0 && paramAsChoice == 0)
        {
        // Label (col 0)
        QWidget* label = new QtWidgetParameterLabel( param );
        gridLayout->addWidget(label, i, 1);

        // Parameter Widget (col 2)
        QtWidgetParameterBase* specificWidget = QtWidgetParameterFactory::CreateQtWidget( param, GetModel() );
        gridLayout->addWidget(specificWidget, i, 2 );

        // CheckBox (col 1)
        QCheckBox * checkBox = new QCheckBox;
        connect( checkBox, SIGNAL(clicked(bool)), specificWidget, SLOT(SetActivationState(bool)));
        connect( checkBox, SIGNAL(clicked(bool)), GetModel(), SLOT(NotifyUpdate()) );
        connect( specificWidget, SIGNAL(ParameterActiveStatus(bool)), checkBox, SLOT(setChecked(bool)));
        connect( specificWidget, SIGNAL(ParameterActiveStatus(bool)), specificWidget, SLOT(SetActivationState(bool)));

        // if Mandatory make the checkbox checked and deactivated
        if (param->GetMandatory())
          {
          checkBox->setCheckState(Qt::Checked);
          checkBox->setEnabled(false);
          specificWidget->setEnabled(true);
          }
        else
          {
          checkBox->setCheckState(Qt::Unchecked);
          checkBox->setEnabled(true);
          specificWidget->setEnabled(false);
          }

        gridLayout->addWidget(checkBox, i, 0);
        m_WidgetList.push_back(specificWidget);
        }
      else
        {
        QtWidgetParameterBase* specificWidget = QtWidgetParameterFactory::CreateQtWidget( param, GetModel() );

        QVBoxLayout* vboxLayout = new QVBoxLayout;
        vboxLayout->addWidget(specificWidget);
        QGroupBox* group = new QGroupBox;
        group->setLayout(vboxLayout);

        // Make the paramter Group checkable when it is not mandatory
        if (!param->GetMandatory() )
          {
          group->setCheckable(true);
          group->setChecked(false);

          // Update iteratively the children status
          for (unsigned int idx = 0; idx < param->GetChildrenList().size(); ++idx)
            {
            // deactivate the children tree
            this->ProcessChild(param->GetChildrenList()[idx], false);
            }
          }
        else
          {
          param->SetActive(true);
          }
        connect(group, SIGNAL(clicked(bool)), specificWidget, SLOT(SetActivationState(bool)));

        group->setTitle(param->GetName());
        gridLayout->addWidget(group, i, 0, 1, -1);

        m_WidgetList.push_back(specificWidget);
        }
      }
    }

  this->setLayout(gridLayout);
}

// Slot connected to the signal emitted the checkBox relative to
// current widget
void QtWidgetParameterGroup::SetActivationState( bool value )
{
  // First call the superclass implementation
  this->QtWidgetParameterBase::SetActivationState(value);

  // Update the Group status
  this->setEnabled(value);

  // Update iteratively the children status
  for (unsigned int idx = 0; idx < m_ParamList->GetChildrenList().size(); ++idx)
    {
    this->ProcessChild(m_ParamList->GetChildrenList()[idx], value);
    }
}

// Activate iteratively  the children
void QtWidgetParameterGroup::ProcessChild(Parameter* currentNode, bool status)
{
  // Activate the current node if it was checked
  if ( currentNode->IsChecked() && status)
    {
    currentNode->SetActive(status);
    }

  // If the status is false (deactivating) deactivate all the children
  // tree
  if (!status)
    {
    currentNode->SetActive(status);
    }

  unsigned int counter = 0;
  while(counter < currentNode->GetChildrenList().size())
    {
    this->ProcessChild(currentNode->GetChildrenList()[counter], status);
    ++counter;
    }
}

}
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 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 "chrome/browser/net/pref_proxy_config_service.h"

#include "base/command_line.h"
#include "base/file_path.h"
#include "chrome/browser/net/chrome_url_request_context.h"
#include "chrome/browser/prefs/pref_service_mock_builder.h"
#include "chrome/browser/prefs/proxy_config_dictionary.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/testing_pref_service.h"
#include "net/proxy/proxy_config_service_common_unittest.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using testing::_;
using testing::Mock;

namespace {

const char kFixedPacUrl[] = "http://chromium.org/fixed_pac_url";

// Testing proxy config service that allows us to fire notifications at will.
class TestProxyConfigService : public net::ProxyConfigService {
 public:
  TestProxyConfigService(const net::ProxyConfig& config,
                         ConfigAvailability availability)
      : config_(config),
        availability_(availability) {}

  void SetProxyConfig(const net::ProxyConfig config,
                      ConfigAvailability availability) {
    config_ = config;
    availability_ = availability;
    FOR_EACH_OBSERVER(net::ProxyConfigService::Observer, observers_,
                      OnProxyConfigChanged(config, availability));
  }

 private:
  virtual void AddObserver(net::ProxyConfigService::Observer* observer) {
    observers_.AddObserver(observer);
  }

  virtual void RemoveObserver(net::ProxyConfigService::Observer* observer) {
    observers_.RemoveObserver(observer);
  }

  virtual net::ProxyConfigService::ConfigAvailability GetLatestProxyConfig(
      net::ProxyConfig* config) {
    *config = config_;
    return availability_;
  }

  net::ProxyConfig config_;
  ConfigAvailability availability_;
  ObserverList<net::ProxyConfigService::Observer, true> observers_;
};

// A mock observer for capturing callbacks.
class MockObserver : public net::ProxyConfigService::Observer {
 public:
  MOCK_METHOD2(OnProxyConfigChanged,
               void(const net::ProxyConfig&,
                    net::ProxyConfigService::ConfigAvailability));
};

template<typename TESTBASE>
class PrefProxyConfigServiceTestBase : public TESTBASE {
 protected:
  PrefProxyConfigServiceTestBase()
      : ui_thread_(BrowserThread::UI, &loop_),
        io_thread_(BrowserThread::IO, &loop_) {}

  virtual void Init(PrefService* pref_service) {
    ASSERT_TRUE(pref_service);
    PrefProxyConfigService::RegisterPrefs(pref_service);
    fixed_config_.set_pac_url(GURL(kFixedPacUrl));
    delegate_service_ =
        new TestProxyConfigService(fixed_config_,
                                   net::ProxyConfigService::CONFIG_VALID);
    proxy_config_tracker_ = new PrefProxyConfigTracker(pref_service);
    proxy_config_service_.reset(
        new PrefProxyConfigService(proxy_config_tracker_.get(),
                                   delegate_service_));
  }

  virtual void TearDown() {
    proxy_config_tracker_->DetachFromPrefService();
    loop_.RunAllPending();
    proxy_config_service_.reset();
  }

  MessageLoop loop_;
  TestProxyConfigService* delegate_service_; // weak
  scoped_ptr<PrefProxyConfigService> proxy_config_service_;
  net::ProxyConfig fixed_config_;

 private:
  scoped_refptr<PrefProxyConfigTracker> proxy_config_tracker_;
  BrowserThread ui_thread_;
  BrowserThread io_thread_;
};

class PrefProxyConfigServiceTest
    : public PrefProxyConfigServiceTestBase<testing::Test> {
 protected:
  virtual void SetUp() {
    pref_service_.reset(new TestingPrefService());
    Init(pref_service_.get());
  }

  scoped_ptr<TestingPrefService> pref_service_;
};

TEST_F(PrefProxyConfigServiceTest, BaseConfiguration) {
  net::ProxyConfig actual_config;
  EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID,
            proxy_config_service_->GetLatestProxyConfig(&actual_config));
  EXPECT_EQ(GURL(kFixedPacUrl), actual_config.pac_url());
}

TEST_F(PrefProxyConfigServiceTest, DynamicPrefOverrides) {
  pref_service_->SetManagedPref(
      prefs::kProxy,
      ProxyConfigDictionary::CreateFixedServers("http://example.com:3128", ""));
  loop_.RunAllPending();

  net::ProxyConfig actual_config;
  EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID,
            proxy_config_service_->GetLatestProxyConfig(&actual_config));
  EXPECT_FALSE(actual_config.auto_detect());
  EXPECT_EQ(net::ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY,
            actual_config.proxy_rules().type);
  EXPECT_EQ(actual_config.proxy_rules().single_proxy,
            net::ProxyServer::FromURI("http://example.com:3128",
                                      net::ProxyServer::SCHEME_HTTP));

  pref_service_->SetManagedPref(prefs::kProxy,
                                ProxyConfigDictionary::CreateAutoDetect());
  loop_.RunAllPending();

  EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID,
            proxy_config_service_->GetLatestProxyConfig(&actual_config));
  EXPECT_TRUE(actual_config.auto_detect());
}

// Compares proxy configurations, but allows different identifiers.
MATCHER_P(ProxyConfigMatches, config, "") {
  net::ProxyConfig reference(config);
  reference.set_id(arg.id());
  return reference.Equals(arg);
}

TEST_F(PrefProxyConfigServiceTest, Observers) {
  const net::ProxyConfigService::ConfigAvailability CONFIG_VALID =
      net::ProxyConfigService::CONFIG_VALID;
  MockObserver observer;
  proxy_config_service_->AddObserver(&observer);

  // Firing the observers in the delegate should trigger a notification.
  net::ProxyConfig config2;
  config2.set_auto_detect(true);
  EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(config2),
                                             CONFIG_VALID)).Times(1);
  delegate_service_->SetProxyConfig(config2, CONFIG_VALID);
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);

  // Override configuration, this should trigger a notification.
  net::ProxyConfig pref_config;
  pref_config.set_pac_url(GURL(kFixedPacUrl));

  EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(pref_config),
                                             CONFIG_VALID)).Times(1);
  pref_service_->SetManagedPref(
      prefs::kProxy,
      ProxyConfigDictionary::CreatePacScript(kFixedPacUrl));
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);

  // Since there are pref overrides, delegate changes should be ignored.
  net::ProxyConfig config3;
  config3.proxy_rules().ParseFromString("http=config3:80");
  EXPECT_CALL(observer, OnProxyConfigChanged(_, _)).Times(0);
  fixed_config_.set_auto_detect(true);
  delegate_service_->SetProxyConfig(config3, CONFIG_VALID);
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);

  // Clear the override should switch back to the fixed configuration.
  EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(config3),
                                             CONFIG_VALID)).Times(1);
  pref_service_->RemoveManagedPref(prefs::kProxy);
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);

  // Delegate service notifications should show up again.
  net::ProxyConfig config4;
  config4.proxy_rules().ParseFromString("socks:config4");
  EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(config4),
                                             CONFIG_VALID)).Times(1);
  delegate_service_->SetProxyConfig(config4, CONFIG_VALID);
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);

  proxy_config_service_->RemoveObserver(&observer);
}

TEST_F(PrefProxyConfigServiceTest, Fallback) {
  const net::ProxyConfigService::ConfigAvailability CONFIG_VALID =
      net::ProxyConfigService::CONFIG_VALID;
  MockObserver observer;
  net::ProxyConfig actual_config;
  delegate_service_->SetProxyConfig(net::ProxyConfig::CreateDirect(),
                                    net::ProxyConfigService::CONFIG_UNSET);
  proxy_config_service_->AddObserver(&observer);

  // Prepare test data.
  net::ProxyConfig recommended_config = net::ProxyConfig::CreateAutoDetect();
  net::ProxyConfig user_config =
      net::ProxyConfig::CreateFromCustomPacURL(GURL(kFixedPacUrl));

  // Set a recommended pref.
  EXPECT_CALL(observer,
              OnProxyConfigChanged(ProxyConfigMatches(recommended_config),
                                   CONFIG_VALID)).Times(1);
  pref_service_->SetRecommendedPref(
      prefs::kProxy,
      ProxyConfigDictionary::CreateAutoDetect());
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);
  EXPECT_EQ(CONFIG_VALID,
            proxy_config_service_->GetLatestProxyConfig(&actual_config));
  EXPECT_THAT(actual_config, ProxyConfigMatches(recommended_config));

  // Override in user prefs.
  EXPECT_CALL(observer,
              OnProxyConfigChanged(ProxyConfigMatches(user_config),
                                   CONFIG_VALID)).Times(1);
  pref_service_->SetManagedPref(
      prefs::kProxy,
      ProxyConfigDictionary::CreatePacScript(kFixedPacUrl));
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);
  EXPECT_EQ(CONFIG_VALID,
            proxy_config_service_->GetLatestProxyConfig(&actual_config));
  EXPECT_THAT(actual_config, ProxyConfigMatches(user_config));

  // Go back to recommended pref.
  EXPECT_CALL(observer,
              OnProxyConfigChanged(ProxyConfigMatches(recommended_config),
                                   CONFIG_VALID)).Times(1);
  pref_service_->RemoveManagedPref(prefs::kProxy);
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);
  EXPECT_EQ(CONFIG_VALID,
            proxy_config_service_->GetLatestProxyConfig(&actual_config));
  EXPECT_THAT(actual_config, ProxyConfigMatches(recommended_config));

  proxy_config_service_->RemoveObserver(&observer);
}

// Test parameter object for testing command line proxy configuration.
struct CommandLineTestParams {
  // Explicit assignment operator, so testing::TestWithParam works with MSVC.
  CommandLineTestParams& operator=(const CommandLineTestParams& other) {
    description = other.description;
    for (unsigned int i = 0; i < arraysize(switches); i++)
      switches[i] = other.switches[i];
    is_null = other.is_null;
    auto_detect = other.auto_detect;
    pac_url = other.pac_url;
    proxy_rules = other.proxy_rules;
    return *this;
  }

  // Short description to identify the test.
  const char* description;

  // The command line to build a ProxyConfig from.
  struct SwitchValue {
    const char* name;
    const char* value;
  } switches[2];

  // Expected outputs (fields of the ProxyConfig).
  bool is_null;
  bool auto_detect;
  GURL pac_url;
  net::ProxyRulesExpectation proxy_rules;
};

void PrintTo(const CommandLineTestParams& params, std::ostream* os) {
  *os << params.description;
}

class PrefProxyConfigServiceCommandLineTest
    : public PrefProxyConfigServiceTestBase<
          testing::TestWithParam<CommandLineTestParams> > {
 protected:
  PrefProxyConfigServiceCommandLineTest()
      : command_line_(CommandLine::NO_PROGRAM) {}

  virtual void SetUp() {
    for (size_t i = 0; i < arraysize(GetParam().switches); i++) {
      const char* name = GetParam().switches[i].name;
      const char* value = GetParam().switches[i].value;
      if (name && value)
        command_line_.AppendSwitchASCII(name, value);
      else if (name)
        command_line_.AppendSwitch(name);
    }
    pref_service_.reset(
        PrefServiceMockBuilder().WithCommandLine(&command_line_).Create());
    Init(pref_service_.get());
  }

 private:
  CommandLine command_line_;
  scoped_ptr<PrefService> pref_service_;
};

TEST_P(PrefProxyConfigServiceCommandLineTest, CommandLine) {
  net::ProxyConfig config;
  EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID,
            proxy_config_service_->GetLatestProxyConfig(&config));

  if (GetParam().is_null) {
    EXPECT_EQ(GURL(kFixedPacUrl), config.pac_url());
  } else {
    EXPECT_NE(GURL(kFixedPacUrl), config.pac_url());
    EXPECT_EQ(GetParam().auto_detect, config.auto_detect());
    EXPECT_EQ(GetParam().pac_url, config.pac_url());
    EXPECT_TRUE(GetParam().proxy_rules.Matches(config.proxy_rules()));
  }
}

static const CommandLineTestParams kCommandLineTestParams[] = {
  {
    "Empty command line",
    // Input
    { },
    // Expected result
    true,                                               // is_null
    false,                                              // auto_detect
    GURL(),                                             // pac_url
    net::ProxyRulesExpectation::Empty(),
  },
  {
    "No proxy",
    // Input
    {
      { switches::kNoProxyServer, NULL },
    },
    // Expected result
    false,                                              // is_null
    false,                                              // auto_detect
    GURL(),                                             // pac_url
    net::ProxyRulesExpectation::Empty(),
  },
  {
    "No proxy with extra parameters.",
    // Input
    {
      { switches::kNoProxyServer, NULL },
      { switches::kProxyServer, "http://proxy:8888" },
    },
    // Expected result
    false,                                              // is_null
    false,                                              // auto_detect
    GURL(),                                             // pac_url
    net::ProxyRulesExpectation::Empty(),
  },
  {
    "Single proxy.",
    // Input
    {
      { switches::kProxyServer, "http://proxy:8888" },
    },
    // Expected result
    false,                                              // is_null
    false,                                              // auto_detect
    GURL(),                                             // pac_url
    net::ProxyRulesExpectation::Single(
        "proxy:8888",  // single proxy
        ""),           // bypass rules
  },
  {
    "Per scheme proxy.",
    // Input
    {
      { switches::kProxyServer, "http=httpproxy:8888;ftp=ftpproxy:8889" },
    },
    // Expected result
    false,                                              // is_null
    false,                                              // auto_detect
    GURL(),                                             // pac_url
    net::ProxyRulesExpectation::PerScheme(
        "httpproxy:8888",  // http
        "",                // https
        "ftpproxy:8889",   // ftp
        ""),               // bypass rules
  },
  {
    "Per scheme proxy with bypass URLs.",
    // Input
    {
      { switches::kProxyServer, "http=httpproxy:8888;ftp=ftpproxy:8889" },
      { switches::kProxyBypassList,
        ".google.com, foo.com:99, 1.2.3.4:22, 127.0.0.1/8" },
    },
    // Expected result
    false,                                              // is_null
    false,                                              // auto_detect
    GURL(),                                             // pac_url
    net::ProxyRulesExpectation::PerScheme(
        "httpproxy:8888",  // http
        "",                // https
        "ftpproxy:8889",   // ftp
        "*.google.com,foo.com:99,1.2.3.4:22,127.0.0.1/8"),
  },
  {
    "Pac URL",
    // Input
    {
      { switches::kProxyPacUrl, "http://wpad/wpad.dat" },
    },
    // Expected result
    false,                                              // is_null
    false,                                              // auto_detect
    GURL("http://wpad/wpad.dat"),                       // pac_url
    net::ProxyRulesExpectation::Empty(),
  },
  {
    "Autodetect",
    // Input
    {
      { switches::kProxyAutoDetect, NULL },
    },
    // Expected result
    false,                                              // is_null
    true,                                               // auto_detect
    GURL(),                                             // pac_url
    net::ProxyRulesExpectation::Empty(),
  },
};

INSTANTIATE_TEST_CASE_P(
    PrefProxyConfigServiceCommandLineTestInstance,
    PrefProxyConfigServiceCommandLineTest,
    testing::ValuesIn(kCommandLineTestParams));

}  // namespace
<commit_msg>Replace gmock's EXPECT_THAT by an explicit check when comparing proxy config in PrefProxyConfigServiceTest.Fallback. This should avoid having gtest print the objects, which results in uninitialized memory accesses.<commit_after>// Copyright (c) 2011 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 "chrome/browser/net/pref_proxy_config_service.h"

#include "base/command_line.h"
#include "base/file_path.h"
#include "chrome/browser/net/chrome_url_request_context.h"
#include "chrome/browser/prefs/pref_service_mock_builder.h"
#include "chrome/browser/prefs/proxy_config_dictionary.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/testing_pref_service.h"
#include "net/proxy/proxy_config_service_common_unittest.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using testing::_;
using testing::Mock;

namespace {

const char kFixedPacUrl[] = "http://chromium.org/fixed_pac_url";

// Testing proxy config service that allows us to fire notifications at will.
class TestProxyConfigService : public net::ProxyConfigService {
 public:
  TestProxyConfigService(const net::ProxyConfig& config,
                         ConfigAvailability availability)
      : config_(config),
        availability_(availability) {}

  void SetProxyConfig(const net::ProxyConfig config,
                      ConfigAvailability availability) {
    config_ = config;
    availability_ = availability;
    FOR_EACH_OBSERVER(net::ProxyConfigService::Observer, observers_,
                      OnProxyConfigChanged(config, availability));
  }

 private:
  virtual void AddObserver(net::ProxyConfigService::Observer* observer) {
    observers_.AddObserver(observer);
  }

  virtual void RemoveObserver(net::ProxyConfigService::Observer* observer) {
    observers_.RemoveObserver(observer);
  }

  virtual net::ProxyConfigService::ConfigAvailability GetLatestProxyConfig(
      net::ProxyConfig* config) {
    *config = config_;
    return availability_;
  }

  net::ProxyConfig config_;
  ConfigAvailability availability_;
  ObserverList<net::ProxyConfigService::Observer, true> observers_;
};

// A mock observer for capturing callbacks.
class MockObserver : public net::ProxyConfigService::Observer {
 public:
  MOCK_METHOD2(OnProxyConfigChanged,
               void(const net::ProxyConfig&,
                    net::ProxyConfigService::ConfigAvailability));
};

template<typename TESTBASE>
class PrefProxyConfigServiceTestBase : public TESTBASE {
 protected:
  PrefProxyConfigServiceTestBase()
      : ui_thread_(BrowserThread::UI, &loop_),
        io_thread_(BrowserThread::IO, &loop_) {}

  virtual void Init(PrefService* pref_service) {
    ASSERT_TRUE(pref_service);
    PrefProxyConfigService::RegisterPrefs(pref_service);
    fixed_config_.set_pac_url(GURL(kFixedPacUrl));
    delegate_service_ =
        new TestProxyConfigService(fixed_config_,
                                   net::ProxyConfigService::CONFIG_VALID);
    proxy_config_tracker_ = new PrefProxyConfigTracker(pref_service);
    proxy_config_service_.reset(
        new PrefProxyConfigService(proxy_config_tracker_.get(),
                                   delegate_service_));
  }

  virtual void TearDown() {
    proxy_config_tracker_->DetachFromPrefService();
    loop_.RunAllPending();
    proxy_config_service_.reset();
  }

  MessageLoop loop_;
  TestProxyConfigService* delegate_service_; // weak
  scoped_ptr<PrefProxyConfigService> proxy_config_service_;
  net::ProxyConfig fixed_config_;

 private:
  scoped_refptr<PrefProxyConfigTracker> proxy_config_tracker_;
  BrowserThread ui_thread_;
  BrowserThread io_thread_;
};

class PrefProxyConfigServiceTest
    : public PrefProxyConfigServiceTestBase<testing::Test> {
 protected:
  virtual void SetUp() {
    pref_service_.reset(new TestingPrefService());
    Init(pref_service_.get());
  }

  scoped_ptr<TestingPrefService> pref_service_;
};

TEST_F(PrefProxyConfigServiceTest, BaseConfiguration) {
  net::ProxyConfig actual_config;
  EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID,
            proxy_config_service_->GetLatestProxyConfig(&actual_config));
  EXPECT_EQ(GURL(kFixedPacUrl), actual_config.pac_url());
}

TEST_F(PrefProxyConfigServiceTest, DynamicPrefOverrides) {
  pref_service_->SetManagedPref(
      prefs::kProxy,
      ProxyConfigDictionary::CreateFixedServers("http://example.com:3128", ""));
  loop_.RunAllPending();

  net::ProxyConfig actual_config;
  EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID,
            proxy_config_service_->GetLatestProxyConfig(&actual_config));
  EXPECT_FALSE(actual_config.auto_detect());
  EXPECT_EQ(net::ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY,
            actual_config.proxy_rules().type);
  EXPECT_EQ(actual_config.proxy_rules().single_proxy,
            net::ProxyServer::FromURI("http://example.com:3128",
                                      net::ProxyServer::SCHEME_HTTP));

  pref_service_->SetManagedPref(prefs::kProxy,
                                ProxyConfigDictionary::CreateAutoDetect());
  loop_.RunAllPending();

  EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID,
            proxy_config_service_->GetLatestProxyConfig(&actual_config));
  EXPECT_TRUE(actual_config.auto_detect());
}

// Compares proxy configurations, but allows different identifiers.
MATCHER_P(ProxyConfigMatches, config, "") {
  net::ProxyConfig reference(config);
  reference.set_id(arg.id());
  return reference.Equals(arg);
}

TEST_F(PrefProxyConfigServiceTest, Observers) {
  const net::ProxyConfigService::ConfigAvailability CONFIG_VALID =
      net::ProxyConfigService::CONFIG_VALID;
  MockObserver observer;
  proxy_config_service_->AddObserver(&observer);

  // Firing the observers in the delegate should trigger a notification.
  net::ProxyConfig config2;
  config2.set_auto_detect(true);
  EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(config2),
                                             CONFIG_VALID)).Times(1);
  delegate_service_->SetProxyConfig(config2, CONFIG_VALID);
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);

  // Override configuration, this should trigger a notification.
  net::ProxyConfig pref_config;
  pref_config.set_pac_url(GURL(kFixedPacUrl));

  EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(pref_config),
                                             CONFIG_VALID)).Times(1);
  pref_service_->SetManagedPref(
      prefs::kProxy,
      ProxyConfigDictionary::CreatePacScript(kFixedPacUrl));
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);

  // Since there are pref overrides, delegate changes should be ignored.
  net::ProxyConfig config3;
  config3.proxy_rules().ParseFromString("http=config3:80");
  EXPECT_CALL(observer, OnProxyConfigChanged(_, _)).Times(0);
  fixed_config_.set_auto_detect(true);
  delegate_service_->SetProxyConfig(config3, CONFIG_VALID);
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);

  // Clear the override should switch back to the fixed configuration.
  EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(config3),
                                             CONFIG_VALID)).Times(1);
  pref_service_->RemoveManagedPref(prefs::kProxy);
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);

  // Delegate service notifications should show up again.
  net::ProxyConfig config4;
  config4.proxy_rules().ParseFromString("socks:config4");
  EXPECT_CALL(observer, OnProxyConfigChanged(ProxyConfigMatches(config4),
                                             CONFIG_VALID)).Times(1);
  delegate_service_->SetProxyConfig(config4, CONFIG_VALID);
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);

  proxy_config_service_->RemoveObserver(&observer);
}

TEST_F(PrefProxyConfigServiceTest, Fallback) {
  const net::ProxyConfigService::ConfigAvailability CONFIG_VALID =
      net::ProxyConfigService::CONFIG_VALID;
  MockObserver observer;
  net::ProxyConfig actual_config;
  delegate_service_->SetProxyConfig(net::ProxyConfig::CreateDirect(),
                                    net::ProxyConfigService::CONFIG_UNSET);
  proxy_config_service_->AddObserver(&observer);

  // Prepare test data.
  net::ProxyConfig recommended_config = net::ProxyConfig::CreateAutoDetect();
  net::ProxyConfig user_config =
      net::ProxyConfig::CreateFromCustomPacURL(GURL(kFixedPacUrl));

  // Set a recommended pref.
  EXPECT_CALL(observer,
              OnProxyConfigChanged(ProxyConfigMatches(recommended_config),
                                   CONFIG_VALID)).Times(1);
  pref_service_->SetRecommendedPref(
      prefs::kProxy,
      ProxyConfigDictionary::CreateAutoDetect());
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);
  EXPECT_EQ(CONFIG_VALID,
            proxy_config_service_->GetLatestProxyConfig(&actual_config));
  EXPECT_TRUE(actual_config.Equals(recommended_config));

  // Override in user prefs.
  EXPECT_CALL(observer,
              OnProxyConfigChanged(ProxyConfigMatches(user_config),
                                   CONFIG_VALID)).Times(1);
  pref_service_->SetManagedPref(
      prefs::kProxy,
      ProxyConfigDictionary::CreatePacScript(kFixedPacUrl));
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);
  EXPECT_EQ(CONFIG_VALID,
            proxy_config_service_->GetLatestProxyConfig(&actual_config));
  EXPECT_TRUE(actual_config.Equals(user_config));

  // Go back to recommended pref.
  EXPECT_CALL(observer,
              OnProxyConfigChanged(ProxyConfigMatches(recommended_config),
                                   CONFIG_VALID)).Times(1);
  pref_service_->RemoveManagedPref(prefs::kProxy);
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);
  EXPECT_EQ(CONFIG_VALID,
            proxy_config_service_->GetLatestProxyConfig(&actual_config));
  EXPECT_TRUE(actual_config.Equals(recommended_config));

  proxy_config_service_->RemoveObserver(&observer);
}

// Test parameter object for testing command line proxy configuration.
struct CommandLineTestParams {
  // Explicit assignment operator, so testing::TestWithParam works with MSVC.
  CommandLineTestParams& operator=(const CommandLineTestParams& other) {
    description = other.description;
    for (unsigned int i = 0; i < arraysize(switches); i++)
      switches[i] = other.switches[i];
    is_null = other.is_null;
    auto_detect = other.auto_detect;
    pac_url = other.pac_url;
    proxy_rules = other.proxy_rules;
    return *this;
  }

  // Short description to identify the test.
  const char* description;

  // The command line to build a ProxyConfig from.
  struct SwitchValue {
    const char* name;
    const char* value;
  } switches[2];

  // Expected outputs (fields of the ProxyConfig).
  bool is_null;
  bool auto_detect;
  GURL pac_url;
  net::ProxyRulesExpectation proxy_rules;
};

void PrintTo(const CommandLineTestParams& params, std::ostream* os) {
  *os << params.description;
}

class PrefProxyConfigServiceCommandLineTest
    : public PrefProxyConfigServiceTestBase<
          testing::TestWithParam<CommandLineTestParams> > {
 protected:
  PrefProxyConfigServiceCommandLineTest()
      : command_line_(CommandLine::NO_PROGRAM) {}

  virtual void SetUp() {
    for (size_t i = 0; i < arraysize(GetParam().switches); i++) {
      const char* name = GetParam().switches[i].name;
      const char* value = GetParam().switches[i].value;
      if (name && value)
        command_line_.AppendSwitchASCII(name, value);
      else if (name)
        command_line_.AppendSwitch(name);
    }
    pref_service_.reset(
        PrefServiceMockBuilder().WithCommandLine(&command_line_).Create());
    Init(pref_service_.get());
  }

 private:
  CommandLine command_line_;
  scoped_ptr<PrefService> pref_service_;
};

TEST_P(PrefProxyConfigServiceCommandLineTest, CommandLine) {
  net::ProxyConfig config;
  EXPECT_EQ(net::ProxyConfigService::CONFIG_VALID,
            proxy_config_service_->GetLatestProxyConfig(&config));

  if (GetParam().is_null) {
    EXPECT_EQ(GURL(kFixedPacUrl), config.pac_url());
  } else {
    EXPECT_NE(GURL(kFixedPacUrl), config.pac_url());
    EXPECT_EQ(GetParam().auto_detect, config.auto_detect());
    EXPECT_EQ(GetParam().pac_url, config.pac_url());
    EXPECT_TRUE(GetParam().proxy_rules.Matches(config.proxy_rules()));
  }
}

static const CommandLineTestParams kCommandLineTestParams[] = {
  {
    "Empty command line",
    // Input
    { },
    // Expected result
    true,                                               // is_null
    false,                                              // auto_detect
    GURL(),                                             // pac_url
    net::ProxyRulesExpectation::Empty(),
  },
  {
    "No proxy",
    // Input
    {
      { switches::kNoProxyServer, NULL },
    },
    // Expected result
    false,                                              // is_null
    false,                                              // auto_detect
    GURL(),                                             // pac_url
    net::ProxyRulesExpectation::Empty(),
  },
  {
    "No proxy with extra parameters.",
    // Input
    {
      { switches::kNoProxyServer, NULL },
      { switches::kProxyServer, "http://proxy:8888" },
    },
    // Expected result
    false,                                              // is_null
    false,                                              // auto_detect
    GURL(),                                             // pac_url
    net::ProxyRulesExpectation::Empty(),
  },
  {
    "Single proxy.",
    // Input
    {
      { switches::kProxyServer, "http://proxy:8888" },
    },
    // Expected result
    false,                                              // is_null
    false,                                              // auto_detect
    GURL(),                                             // pac_url
    net::ProxyRulesExpectation::Single(
        "proxy:8888",  // single proxy
        ""),           // bypass rules
  },
  {
    "Per scheme proxy.",
    // Input
    {
      { switches::kProxyServer, "http=httpproxy:8888;ftp=ftpproxy:8889" },
    },
    // Expected result
    false,                                              // is_null
    false,                                              // auto_detect
    GURL(),                                             // pac_url
    net::ProxyRulesExpectation::PerScheme(
        "httpproxy:8888",  // http
        "",                // https
        "ftpproxy:8889",   // ftp
        ""),               // bypass rules
  },
  {
    "Per scheme proxy with bypass URLs.",
    // Input
    {
      { switches::kProxyServer, "http=httpproxy:8888;ftp=ftpproxy:8889" },
      { switches::kProxyBypassList,
        ".google.com, foo.com:99, 1.2.3.4:22, 127.0.0.1/8" },
    },
    // Expected result
    false,                                              // is_null
    false,                                              // auto_detect
    GURL(),                                             // pac_url
    net::ProxyRulesExpectation::PerScheme(
        "httpproxy:8888",  // http
        "",                // https
        "ftpproxy:8889",   // ftp
        "*.google.com,foo.com:99,1.2.3.4:22,127.0.0.1/8"),
  },
  {
    "Pac URL",
    // Input
    {
      { switches::kProxyPacUrl, "http://wpad/wpad.dat" },
    },
    // Expected result
    false,                                              // is_null
    false,                                              // auto_detect
    GURL("http://wpad/wpad.dat"),                       // pac_url
    net::ProxyRulesExpectation::Empty(),
  },
  {
    "Autodetect",
    // Input
    {
      { switches::kProxyAutoDetect, NULL },
    },
    // Expected result
    false,                                              // is_null
    true,                                               // auto_detect
    GURL(),                                             // pac_url
    net::ProxyRulesExpectation::Empty(),
  },
};

INSTANTIATE_TEST_CASE_P(
    PrefProxyConfigServiceCommandLineTestInstance,
    PrefProxyConfigServiceCommandLineTest,
    testing::ValuesIn(kCommandLineTestParams));

}  // namespace
<|endoftext|>


<commit_before>/*
 *  Copyright 2011 The Regents of the University of California
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
#include <cusp/array1d.h>
#include <cusp/blas.h>
#include <cusp/multiply.h>
#include <cusp/monitor.h>
#include <cusp/linear_operator.h>

namespace blas = cusp::blas;
namespace cusp
{
  namespace krylov
  {
    template <typename ValueType>
    void ApplyPlaneRotation(ValueType& dx,
			    ValueType& dy,
			    ValueType& cs,
			    ValueType& sn)
    {
      ValueType temp = cs * dx + sn *dy;
      dy = -sn*dx+cs*dy;
      dx = temp;
    }

    template <typename ValueType>
    void GeneratePlaneRotation(ValueType& dx,
			       ValueType& dy,
			       ValueType& cs,
			       ValueType& sn)
    {
      if(dy == 0.0){
	cs = 1.0;
	sn = 0.0;
      }else if (std::abs(dy) > std::abs (dx)) {
	ValueType tmp = dx / dy;
	sn = 1.0 / sqrt(ValueType(1.0) + tmp*tmp);
	cs = tmp*sn;
      }else {
	ValueType tmp = dy / dx;
	cs = 1.0 / sqrt(ValueType(1.0) + tmp*tmp);
	sn = tmp*cs;
      }
    }

    template <class LinearOperator,typename ValueType>
    void PlaneRotation(LinearOperator& H,
		       ValueType& cs,
		       ValueType& sn,
		       ValueType& s,
		       int i)
    {
      for (int k = 0; k < i; k++){
	ApplyPlaneRotation(H(k,i), H(k+1,i), cs[k], sn[k]);
      }
      GeneratePlaneRotation(H(i,i), H(i+1,i), cs[i], sn[i]);
      ApplyPlaneRotation(H(i,i), H(i+1,i), cs[i], sn[i]);
      ApplyPlaneRotation(s[i], s[i+1], cs[i], sn[i]);
    }

    template <class LinearOperator,
	      class Vector>
    void gmres(LinearOperator& A,
	       Vector& x,
	       Vector& b,
	       const size_t restart)
    {
      typedef typename LinearOperator::value_type   ValueType;
      cusp::default_monitor<ValueType> monitor(b);
      cusp::krylov::gmres(A, x, b, restart, monitor);
    }

    template <class LinearOperator,
	      class Vector,
	      class Monitor>
    void gmres(LinearOperator& A,
	       Vector& x,
	       Vector& b,
	       const size_t restart,
	       Monitor& monitor)
    {
      typedef typename LinearOperator::value_type   ValueType;
      typedef typename LinearOperator::memory_space MemorySpace;
      cusp::identity_operator<ValueType,MemorySpace> M(A.num_rows, A.num_cols);
      cusp::krylov::gmres(A, x, b, restart, monitor, M);
    }

    template <class LinearOperator,
	      class Vector,
	      class Monitor,
	      class Preconditioner>
    void gmres(LinearOperator& A,
	       Vector& x,
	       Vector& b,
	       const size_t restart,
	       Monitor& monitor,
	       Preconditioner& M)
    {
      typedef typename LinearOperator::value_type   ValueType;
      typedef typename LinearOperator::memory_space MemorySpace;
      assert(A.num_rows == A.num_cols);        // sanity check
      const size_t N = A.num_rows;
      const int R = restart;
      int i, j, k;
      ValueType beta, resid0;
      cusp::array1d<ValueType,cusp::host_memory> rel_resid(1);
      //allocate workspace
      cusp::array1d<ValueType,MemorySpace> w(N);
      cusp::array1d<ValueType,MemorySpace> V0(N); //Arnoldi matrix pos 0
      cusp::array2d<ValueType,MemorySpace,cusp::column_major> V(N,R+1,ValueType(0.0)); //Arnoldi matrix
      //duplicate copy of s on GPU
      cusp::array1d<ValueType,MemorySpace> sDev(R+1);
      //HOST WORKSPACE
      cusp::array2d<ValueType,cusp::host_memory,cusp::column_major> H(R+1, R); //Hessenberg matrix
      cusp::array1d<ValueType,cusp::host_memory> s(R+1);
      cusp::array1d<ValueType,cusp::host_memory> cs(R);
      cusp::array1d<ValueType,cusp::host_memory> sn(R);
      ValueType b_norm = blas::nrm2(b);

      do{
	// compute initial residual and its norm //
	cusp::multiply(A, x, w);                     // V(0) = A*x        //
	blas::axpy(b,w,ValueType(-1));               // V(0) = V(0) - b   //
	cusp::multiply(M,w,w);                       // V(0) = M*V(0)     //
	beta = blas::nrm2(w);                        // beta = norm(V(0)) //
	blas::scal(w, ValueType(-1.0/beta));         // V(0) = -V(0)/beta //
	blas::copy(w,V.column(0));
	// save very first residual norm //
	if (monitor.iteration_count()== 0){
	  //resid0 = beta;
	  cusp::multiply(M,b,V0);
	  resid0 = blas::nrm2(V0)/b_norm;
	}
	//s = 0 //
	blas::fill(s,ValueType(0.0));
	s[0] = beta;
	i = -1;

	do{
	  ++i;
	  ++monitor;

	  //apply preconditioner
	  //can't pass in ref to column in V so need to use copy (w)
	  cusp::multiply(A,w,V0);
	  //V(i+1) = A*w = M*A*V(i)    //
	  cusp::multiply(M,V0,w);

	  for (k = 0; k <= i; k++){
	    //  H(k,i) = <V(i+1),V(k)>    //
	    H(k, i) = blas::dotc(w, V.column(k));
	    // V(i+1) -= H(k, i) * V(k)  //
	    blas::axpy(V.column(k),w,-H(k,i));
	  }

	  H(i+1,i) = blas::nrm2(w);
	  // V(i+1) = V(i+1) / H(i+1, i) //
	  blas::scal(w,ValueType(1.0/H(i+1,i)));
	  blas::copy(w,V.column(i+1));

	  PlaneRotation(H,cs,sn,s,i);

	  rel_resid[0] = std::abs(s[i+1]) / resid0 + monitor.absolute_tolerance();

	  //check convergence condition
	  //if (rel_resid < monitor.relative_tolerance())
	  if (monitor.finished(rel_resid)){
	    break;
	  }
	}while (i+1 < R && monitor.iteration_count()+1 <= monitor.iteration_limit());

	// solve upper triangular system in place //
	for (j = i; j >= 0; j--){
	  s[j] /= H(j,j);
	  //S(0:j) = s(0:j) - s[j] H(0:j,j)
	  typename cusp::array2d< ValueType, cusp::host_memory, cusp::column_major >::column_view H_j = H.column(j);
	  blas::axpy(H_j,s,-s[j]);
	  /*
	    for (k = j-1; k >= 0; k--)
	    s[k] -= H(k,j) * s[j];
	  */
	}

	// update the solution //

	//copy s to gpu
	blas::copy(s,sDev);
	// x= V(1:N,0:i)*s(0:i)+x //
	for (j = 0; j <= i; j++){
	  // x = x + s[j] * V(j) //
	  blas::axpy(V.column(j),x,s[j]);
	}
      } while (rel_resid[0] >= monitor.tolerance() &&
	       monitor.iteration_count()+1 <= monitor.iteration_limit());
    }
  } // end namespace krylov
} // end namespace cusp
<commit_msg>Fix GMRES problem caused by fix to issue #62. Patch thanks to Joe Gordon.<commit_after>/*
 *  Copyright 2011 The Regents of the University of California
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
#include <cusp/array1d.h>
#include <cusp/blas.h>
#include <cusp/multiply.h>
#include <cusp/monitor.h>
#include <cusp/linear_operator.h>

namespace blas = cusp::blas;
namespace cusp
{
  namespace krylov
  {
    template <typename ValueType>
    void ApplyPlaneRotation(ValueType& dx,
			    ValueType& dy,
			    ValueType& cs,
			    ValueType& sn)
    {
      ValueType temp = cs * dx + sn *dy;
      dy = -sn*dx+cs*dy;
      dx = temp;
    }

    template <typename ValueType>
    void GeneratePlaneRotation(ValueType& dx,
			       ValueType& dy,
			       ValueType& cs,
			       ValueType& sn)
    {
      if(dy == 0.0){
	cs = 1.0;
	sn = 0.0;
      }else if (std::abs(dy) > std::abs (dx)) {
	ValueType tmp = dx / dy;
	sn = 1.0 / sqrt(ValueType(1.0) + tmp*tmp);
	cs = tmp*sn;
      }else {
	ValueType tmp = dy / dx;
	cs = 1.0 / sqrt(ValueType(1.0) + tmp*tmp);
	sn = tmp*cs;
      }
    }

    template <class LinearOperator,typename ValueType>
    void PlaneRotation(LinearOperator& H,
		       ValueType& cs,
		       ValueType& sn,
		       ValueType& s,
		       int i)
    {
      for (int k = 0; k < i; k++){
	ApplyPlaneRotation(H(k,i), H(k+1,i), cs[k], sn[k]);
      }
      GeneratePlaneRotation(H(i,i), H(i+1,i), cs[i], sn[i]);
      ApplyPlaneRotation(H(i,i), H(i+1,i), cs[i], sn[i]);
      ApplyPlaneRotation(s[i], s[i+1], cs[i], sn[i]);
    }

    template <class LinearOperator,
	      class Vector>
    void gmres(LinearOperator& A,
	       Vector& x,
	       Vector& b,
	       const size_t restart)
    {
      typedef typename LinearOperator::value_type   ValueType;
      cusp::default_monitor<ValueType> monitor(b);
      cusp::krylov::gmres(A, x, b, restart, monitor);
    }

    template <class LinearOperator,
	      class Vector,
	      class Monitor>
    void gmres(LinearOperator& A,
	       Vector& x,
	       Vector& b,
	       const size_t restart,
	       Monitor& monitor)
    {
      typedef typename LinearOperator::value_type   ValueType;
      typedef typename LinearOperator::memory_space MemorySpace;
      cusp::identity_operator<ValueType,MemorySpace> M(A.num_rows, A.num_cols);
      cusp::krylov::gmres(A, x, b, restart, monitor, M);
    }

    template <class LinearOperator,
	      class Vector,
	      class Monitor,
	      class Preconditioner>
    void gmres(LinearOperator& A,
	       Vector& x,
	       Vector& b,
	       const size_t restart,
	       Monitor& monitor,
	       Preconditioner& M)
    {
      typedef typename LinearOperator::value_type   ValueType;
      typedef typename LinearOperator::memory_space MemorySpace;
      assert(A.num_rows == A.num_cols);        // sanity check
      const size_t N = A.num_rows;
      const int R = restart;
      int i, j, k;
      ValueType beta, resid0;
      cusp::array1d<ValueType,cusp::host_memory> rel_resid(1);
      //allocate workspace
      cusp::array1d<ValueType,MemorySpace> w(N);
      cusp::array1d<ValueType,MemorySpace> V0(N); //Arnoldi matrix pos 0
      cusp::array2d<ValueType,MemorySpace,cusp::column_major> V(N,R+1,ValueType(0.0)); //Arnoldi matrix
      //duplicate copy of s on GPU
      cusp::array1d<ValueType,MemorySpace> sDev(R+1);
      //HOST WORKSPACE
      cusp::array2d<ValueType,cusp::host_memory,cusp::column_major> H(R+1, R); //Hessenberg matrix
      cusp::array1d<ValueType,cusp::host_memory> s(R+1);
      cusp::array1d<ValueType,cusp::host_memory> cs(R);
      cusp::array1d<ValueType,cusp::host_memory> sn(R);
      ValueType b_norm = blas::nrm2(b);

      do{
	// compute initial residual and its norm //
	cusp::multiply(A, x, w);                     // V(0) = A*x        //
	blas::axpy(b,w,ValueType(-1));               // V(0) = V(0) - b   //
	cusp::multiply(M,w,w);                       // V(0) = M*V(0)     //
	beta = blas::nrm2(w);                        // beta = norm(V(0)) //
	blas::scal(w, ValueType(-1.0/beta));         // V(0) = -V(0)/beta //
	blas::copy(w,V.column(0));
	// save very first residual norm //
	if (monitor.iteration_count()== 0){
	  //resid0 = beta;
	  cusp::multiply(M,b,V0);
	  resid0 = blas::nrm2(V0)/b_norm;
	}
	//s = 0 //
	blas::fill(s,ValueType(0.0));
	s[0] = beta;
	i = -1;

	do{
	  ++i;
	  ++monitor;

	  //apply preconditioner
	  //can't pass in ref to column in V so need to use copy (w)
	  cusp::multiply(A,w,V0);
	  //V(i+1) = A*w = M*A*V(i)    //
	  cusp::multiply(M,V0,w);

	  for (k = 0; k <= i; k++){
	    //  H(k,i) = <V(i+1),V(k)>    //
	    H(k, i) = blas::dotc(w, V.column(k));
	    // V(i+1) -= H(k, i) * V(k)  //
	    blas::axpy(V.column(k),w,-H(k,i));
	  }

	  H(i+1,i) = blas::nrm2(w);
	  // V(i+1) = V(i+1) / H(i+1, i) //
	  blas::scal(w,ValueType(1.0/H(i+1,i)));
	  blas::copy(w,V.column(i+1));

	  PlaneRotation(H,cs,sn,s,i);

	  rel_resid[0] = std::abs(s[i+1]) / resid0 + monitor.absolute_tolerance();

	  //check convergence condition
	  //if (rel_resid < monitor.relative_tolerance())
	  if (monitor.finished(rel_resid)){
	    break;
	  }
	}while (i+1 < R && monitor.iteration_count()+1 <= monitor.iteration_limit());

	// solve upper triangular system in place //
	for (j = i; j >= 0; j--){
	  s[j] /= H(j,j);
	  //S(0:j) = s(0:j) - s[j] H(0:j,j)
	  for (k = j-1; k >= 0; k--){
	    s[k] -= H(k,j) * s[j];
	  }
	}

	// update the solution //

	//copy s to gpu
	blas::copy(s,sDev);
	// x= V(1:N,0:i)*s(0:i)+x //
	for (j = 0; j <= i; j++){
	  // x = x + s[j] * V(j) //
	  blas::axpy(V.column(j),x,s[j]);
	}
      } while (rel_resid[0] >= monitor.tolerance() &&
	       monitor.iteration_count()+1 <= monitor.iteration_limit());
    }
  } // end namespace krylov
} // end namespace cusp
<|endoftext|>


<commit_before><commit_msg>Allow cookies and other storage data in extensions even when the user chose to block them on websites.<commit_after><|endoftext|>