<commit_before>/* $Id$ */
# ifndef CPPAD_EXP_2_INCLUDED
# define CPPAD_EXP_2_INCLUDED

/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-07 Bradley M. Bell

CppAD is distributed under multiple licenses. This distribution is under
the terms of the
                    Common Public License Version 1.0.

A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*
$begin exp_2$$
$spell
	cppad-%yyyymmdd%
	hpp
	Apx
	cpp
	const
	exp
	bool
$$

$section Second Order Exponential Approximation$$

$index exp_2$$
$index example, algorithm$$
$index algorithm, example$$
$index exp, example$$

$head Syntax$$
$codei%# include "exp_2.hpp"%$$
$pre
$$
$icode%y% = exp_2(%x%)%$$

$head Purpose$$
This is a simple example algorithm that is used to demonstrate
Algorithmic Differentiation
(see $cref exp_eps$$ for a more complex example).

$head Mathematical Form$$
The exponential function can be defined by
$latex \[
	\exp (x) = 1 + x^1 / 1 ! + x^2 / 2 ! + \cdots
\] $$
The second order approximation for the exponential function is
$latex \[
{\rm exp\_2} (x) =  1 + x + x^2 / 2
\] $$

$head include$$
The include command in the syntax is relative to
$codei%
	cppad-%yyyymmdd%/introduction/exp_apx
%$$
where $codei%cppad-%yyyymmdd%$$ is the distribution directory
created during the beginning steps of the
$cref%installation%Install%$$ of CppAD.

$head x$$
The argument $icode x$$ has prototype
$codei%
	const %Type% &%x%
%$$
(see $icode Type$$ below).
It specifies the point at which to evaluate the
approximation for the second order exponential approximation.

$head y$$
The result $icode y$$ has prototype
$codei%
	%Type% %y%
%$$
It is the value of the exponential function
approximation defined above.

$head Type$$
If $icode u$$ and $italic v$$ are $italic Type$$ objects and $italic i$$
is an $code int$$:

$table
$bold Operation$$  $cnext $bold Result Type$$ $cnext $bold Description$$
$rnext
$icode%Type%(%i%)%$$
	$cnext $icode Type$$
	$cnext object with value equal to $icode i$$
$rnext
$icode%u% = %v%$$
	$cnext $icode Type$$
	$cnext new $icode u$$ (and result) is value of $italic v$$
$rnext
$icode%u% * %v%$$
	$cnext $icode Type$$
	$cnext result is value of $latex u * v$$
$rnext
$icode%u% / %v%$$
	$cnext $icode Type$$
	$cnext result is value of $latex u / v$$
$rnext
$icode%u% + %v%$$
	$cnext $icode Type$$
	$cnext result is value of $latex u + v$$
$tend

$childtable%
	introduction/exp_apx/exp_2.omh%
	introduction/exp_apx/exp_2_cppad.cpp
%$$

$head Implementation$$
The file $cref/exp_2.hpp/$$
contains a C++ implementation of this function.

$head Test$$
The file $cref/exp_2.cpp/$$
contains a test of this implementation.
It returns true for success and false for failure.

$head Exercises$$
$list number$$
Suppose that we make the call
$codep
	double x = .1;
	double y = exp_2(x);
$$
What is the value assigned to
$code v1$$, $code v2$$, ... ,$code v5$$ in $cref/exp_2.hpp/$$ ?
$lnext
Extend the routine $code exp_2.hpp$$ to
a routine $code exp_3.hpp$$ that computes
$latex \[
	1 + x^2 / 2 ! + x^3 / 3 !
\] $$
Do this in a way that only assigns one value to each variable
(as $code exp_2$$ does).
$lnext
Suppose that we make the call
$codep
	double x = .5;
	double y = exp_3(x);
$$
using $code exp_3$$ created in the previous problem.
What is the value assigned to the new variables in $code exp_3$$
(variables that are in $code exp_3$$ and not in $code exp_2$$) ?
$lend

$end
------------------------------------------------------------------------------
*/
// BEGIN PROGRAM
template <class Type>
Type exp_2(const Type &x)
{       Type v1  = x;                // v1 = x
        Type v2  = Type(1) + v1;     // v2 = 1 + x
        Type v3  = v1 * v1;          // v3 = x^2
        Type v4  = v3 / Type(2);     // v4 = x^2 / 2
        Type v5  = v2 + v4;          // v5 = 1 + x + x^2 / 2
        return v5;                   // exp_2(x) = 1 + x + x^2 / 2
}
// END PROGRAM

# endif
<commit_msg>fix specifications for templated Type<commit_after>/* $Id$ */
# ifndef CPPAD_EXP_2_INCLUDED
# define CPPAD_EXP_2_INCLUDED

/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-07 Bradley M. Bell

CppAD is distributed under multiple licenses. This distribution is under
the terms of the
                    Common Public License Version 1.0.

A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*
$begin exp_2$$
$spell
	cppad-%yyyymmdd%
	hpp
	Apx
	cpp
	const
	exp
	bool
$$

$section Second Order Exponential Approximation$$

$index exp_2$$
$index example, algorithm$$
$index algorithm, example$$
$index exp, example$$

$head Syntax$$
$codei%# include "exp_2.hpp"%$$
$pre
$$
$icode%y% = exp_2(%x%)%$$

$head Purpose$$
This is a simple example algorithm that is used to demonstrate
Algorithmic Differentiation
(see $cref exp_eps$$ for a more complex example).

$head Mathematical Form$$
The exponential function can be defined by
$latex \[
	\exp (x) = 1 + x^1 / 1 ! + x^2 / 2 ! + \cdots
\] $$
The second order approximation for the exponential function is
$latex \[
{\rm exp\_2} (x) =  1 + x + x^2 / 2
\] $$

$head include$$
The include command in the syntax is relative to
$codei%
	cppad-%yyyymmdd%/introduction/exp_apx
%$$
where $codei%cppad-%yyyymmdd%$$ is the distribution directory
created during the beginning steps of the
$cref%installation%Install%$$ of CppAD.

$head x$$
The argument $icode x$$ has prototype
$codei%
	const %Type% &%x%
%$$
(see $icode Type$$ below).
It specifies the point at which to evaluate the
approximation for the second order exponential approximation.

$head y$$
The result $icode y$$ has prototype
$codei%
	%Type% %y%
%$$
It is the value of the exponential function
approximation defined above.

$head Type$$
If $icode u$$ and $italic v$$ are $italic Type$$ objects and $italic i$$
is an $code int$$:

$table
$bold Operation$$  $cnext $bold Result Type$$ $cnext $bold Description$$
$rnext
$icode%Type%(%i%)%$$
	$cnext $icode Type$$
	$cnext construct object with value equal to $icode i$$
$rnext
$icode%Type u %=% v%$$
	$cnext $icode Type$$
	$cnext construct $icode u$$ with value equal to $icode v$$
$rnext
$icode%u% * %v%$$
	$cnext $icode Type$$
	$cnext result is value of $latex u * v$$
$rnext
$icode%u% / %v%$$
	$cnext $icode Type$$
	$cnext result is value of $latex u / v$$
$rnext
$icode%u% + %v%$$
	$cnext $icode Type$$
	$cnext result is value of $latex u + v$$
$tend

$childtable%
	introduction/exp_apx/exp_2.omh%
	introduction/exp_apx/exp_2_cppad.cpp
%$$

$head Implementation$$
The file $cref/exp_2.hpp/$$
contains a C++ implementation of this function.

$head Test$$
The file $cref/exp_2.cpp/$$
contains a test of this implementation.
It returns true for success and false for failure.

$head Exercises$$
$list number$$
Suppose that we make the call
$codep
	double x = .1;
	double y = exp_2(x);
$$
What is the value assigned to
$code v1$$, $code v2$$, ... ,$code v5$$ in $cref/exp_2.hpp/$$ ?
$lnext
Extend the routine $code exp_2.hpp$$ to
a routine $code exp_3.hpp$$ that computes
$latex \[
	1 + x^2 / 2 ! + x^3 / 3 !
\] $$
Do this in a way that only assigns one value to each variable
(as $code exp_2$$ does).
$lnext
Suppose that we make the call
$codep
	double x = .5;
	double y = exp_3(x);
$$
using $code exp_3$$ created in the previous problem.
What is the value assigned to the new variables in $code exp_3$$
(variables that are in $code exp_3$$ and not in $code exp_2$$) ?
$lend

$end
------------------------------------------------------------------------------
*/
// BEGIN PROGRAM
template <class Type>
Type exp_2(const Type &x)
{       Type v1  = x;                // v1 = x
        Type v2  = Type(1) + v1;     // v2 = 1 + x
        Type v3  = v1 * v1;          // v3 = x^2
        Type v4  = v3 / Type(2);     // v4 = x^2 / 2
        Type v5  = v2 + v4;          // v5 = 1 + x + x^2 / 2
        return v5;                   // exp_2(x) = 1 + x + x^2 / 2
}
// END PROGRAM

# endif
<|endoftext|>


<commit_before>// @(#)root/io:$Id$
// Author: Jakob Blomer

/*************************************************************************
 * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifndef ROOT_RRawFileWin
#define ROOT_RRawFileWin

#include <ROOT/RRawFile.hxx>
#include <ROOT/RStringView.hxx>

#include <cstddef>
#include <cstdint>
#include <cstdio>

namespace ROOT {
namespace Detail {

/**
 * \class RRawFileWin RRawFileWin.hxx
 * \ingroup IO
 *
 * The RRawFileWin class uses portable C I/O calls to read from a drive. The standard C I/O buffering is turned off
 * for the buffering of RRawFile base class.
 */
class RRawFileWin : public RRawFile {
private:
   FILE *fFilePtr;
   void Seek(long offset, int whence);

protected:
   void DoOpen() final;
   size_t DoReadAt(void *buffer, size_t nbytes, std::uint64_t offset) final;
   std::uint64_t DoGetSize() final;

public:
   RRawFileWin(std::string_view url, RRawFile::ROptions options);
   ~RRawFileWin();
};

} // namespace Detail
} // namespace ROOT

#endif
<commit_msg>[io] fix RRawFile header on Windows<commit_after>// @(#)root/io:$Id$
// Author: Jakob Blomer

/*************************************************************************
 * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifndef ROOT_RRawFileWin
#define ROOT_RRawFileWin

#include <ROOT/RRawFile.hxx>
#include <ROOT/RStringView.hxx>

#include <cstddef>
#include <cstdint>
#include <cstdio>

namespace ROOT {
namespace Experimental {
namespace Detail {

/**
 * \class RRawFileWin RRawFileWin.hxx
 * \ingroup IO
 *
 * The RRawFileWin class uses portable C I/O calls to read from a drive. The standard C I/O buffering is turned off
 * for the buffering of RRawFile base class.
 */
class RRawFileWin : public RRawFile {
private:
   FILE *fFilePtr;
   void Seek(long offset, int whence);

protected:
   void DoOpen() final;
   size_t DoReadAt(void *buffer, size_t nbytes, std::uint64_t offset) final;
   std::uint64_t DoGetSize() final;

public:
   RRawFileWin(std::string_view url, RRawFile::ROptions options);
   ~RRawFileWin();
};

} // namespace Detail
} // namespace Experimental
} // namespace ROOT

#endif
<|endoftext|>


<commit_before>#pragma once

#include <limits>
#include <algorithm>
#include <vector>
#include <map>
#include <functional>

using std::max;
using std::make_pair;
using std::min;
using std::abs;
using std::hypot;
using std::vector;
using std::map;
using std::function;

namespace search
{
    //
    //  Lifelong planning
    //
    namespace lp
    {
        constexpr auto infinity()
        {
            return std::numeric_limits<int>::max();
        }
        constexpr auto cost()
        {
            return 1;
        }

        struct Coordinate
        {
            int x, y;

            friend auto operator== (Coordinate l, Coordinate r)
            {
                return l.x == r.x && l.y == r.y;
            }
            friend auto operator!= (Coordinate l, Coordinate r)
            {
                return !(l == r);
            }

            auto neighbours() const
            {
                struct Directions : public map< char, function< Coordinate(Coordinate) >>
                {
                    Directions()
                    {
                        (*this)['1'] = [](Coordinate c) { return Coordinate{ c.x - 1, c.y - 1 }; };
                        (*this)['2'] = [](Coordinate c) { return Coordinate{ c.x - 0, c.y - 1 }; };
                        (*this)['3'] = [](Coordinate c) { return Coordinate{ c.x + 1, c.y - 1 }; };
                        (*this)['4'] = [](Coordinate c) { return Coordinate{ c.x - 1, c.y - 0 }; };
                        (*this)['5'] = [](Coordinate c) { return Coordinate{ c.x + 1, c.y + 0 }; };
                        (*this)['6'] = [](Coordinate c) { return Coordinate{ c.x - 1, c.y + 1 }; };
                        (*this)['7'] = [](Coordinate c) { return Coordinate{ c.x - 0, c.y + 1 }; };
                        (*this)['8'] = [](Coordinate c) { return Coordinate{ c.x + 1, c.y + 1 }; };
                    }
                } static const directions;

                vector<Coordinate> result;
                for (auto n = '1'; n != '9'; ++n)
                    result.push_back(directions.at(n)(*this));
                return result;
            }
        };

        struct LpState
        {
            struct Key
            {
                const int first, second;

                friend auto operator== (Key l, Key r)
                {
                    return l.first == r.first && l.second == r.second;
                }
                friend auto operator < (Key l, Key r)
                {
                    return (l.first < r.first) || (l.first == r.first && l.second < r.second);
                }
            };

            friend auto operator==(LpState const& l, LpState const& r)
            {
                return l.coordinate == r.coordinate && l.g == r.g && l.r == r.r;
            }

            Coordinate coordinate;
            int g, r;

            template<typename Hfunc>
            auto key(Hfunc h) const
            {
                return Key{ min(g, r + h(coordinate)), min(g, r) };
            }
        };

        struct LpManhattanDistance
        {
            const Coordinate goal;
            auto operator()(Coordinate c) const
            {
                return max(abs(goal.x - c.x), abs(goal.y - c.y));
            }
        };

        struct LpEuclideanDistance
        {
            const Coordinate goal;
            auto operator()(Coordinate c) const
            {
                auto result = hypot(abs(goal.x - c.x), abs(goal.y - c.y));
                return static_cast<int>(round(result));
            }
        };

        class Matrix
        {
        public:
            Matrix(unsigned height, unsigned width)
                : _data{ height, vector<LpState>(width)}
            {   }

            auto at(Coordinate c) -> LpState&
            {
                return{ _data[c.y][c.x] };
            }

            auto at(Coordinate c) const -> LpState const&
            {
                return{ _data[c.y][c.x] };
            }

        private:
            vector<vector<LpState>> _data;
        };
    }
}<commit_msg>add LpLess for ording in priority queue.<commit_after>#pragma once

#include <limits>
#include <algorithm>
#include <vector>
#include <map>
#include <functional>

using std::max;
using std::make_pair;
using std::min;
using std::abs;
using std::hypot;
using std::vector;
using std::map;
using std::function;

namespace search
{
    //
    //  Lifelong planning
    //
    namespace lp
    {
        constexpr auto infinity()
        {
            return std::numeric_limits<int>::max();
        }
        constexpr auto cost()
        {
            return 1;
        }

        struct Coordinate
        {
            int x, y;

            friend auto operator== (Coordinate l, Coordinate r)
            {
                return l.x == r.x && l.y == r.y;
            }
            friend auto operator!= (Coordinate l, Coordinate r)
            {
                return !(l == r);
            }

            auto neighbours() const
            {
                struct Directions : public map< char, function< Coordinate(Coordinate) >>
                {
                    Directions()
                    {
                        (*this)['1'] = [](Coordinate c) { return Coordinate{ c.x - 1, c.y - 1 }; };
                        (*this)['2'] = [](Coordinate c) { return Coordinate{ c.x - 0, c.y - 1 }; };
                        (*this)['3'] = [](Coordinate c) { return Coordinate{ c.x + 1, c.y - 1 }; };
                        (*this)['4'] = [](Coordinate c) { return Coordinate{ c.x - 1, c.y - 0 }; };
                        (*this)['5'] = [](Coordinate c) { return Coordinate{ c.x + 1, c.y + 0 }; };
                        (*this)['6'] = [](Coordinate c) { return Coordinate{ c.x - 1, c.y + 1 }; };
                        (*this)['7'] = [](Coordinate c) { return Coordinate{ c.x - 0, c.y + 1 }; };
                        (*this)['8'] = [](Coordinate c) { return Coordinate{ c.x + 1, c.y + 1 }; };
                    }
                } static const directions;

                vector<Coordinate> result;
                for (auto n = '1'; n != '9'; ++n)
                    result.push_back(directions.at(n)(*this));
                return result;
            }
        };

        struct LpState
        {
            struct Key
            {
                const int first, second;

                friend auto operator== (Key l, Key r)
                {
                    return l.first == r.first && l.second == r.second;
                }
                friend auto operator < (Key l, Key r)
                {
                    return (l.first < r.first) || (l.first == r.first && l.second < r.second);
                }
            };

            friend auto operator==(LpState const& l, LpState const& r)
            {
                return l.coordinate == r.coordinate && l.g == r.g && l.r == r.r;
            }

            Coordinate coordinate;
            int g, r;

            template<typename Hfunc>
            auto key(Hfunc h) const
            {
                return Key{ min(g, r + h(coordinate)), min(g, r) };
            }
        };

        template<typename Hfunc>
        struct LpLess
        {
            LpLess() = delete;
            LpLess(Coordinate goal): _goal(goal){   }

            auto operator()(LpState const& l, LpState const& r) const
            {
                return l.key(Hfunc{ _goal }) < r.key(Hfunc{ _goal });
            }

        private:
            Coordinate _goal;
        };

        struct LpManhattanDistance
        {
            const Coordinate goal;
            auto operator()(Coordinate c) const
            {
                return max(abs(goal.x - c.x), abs(goal.y - c.y));
            }
        };

        struct LpEuclideanDistance
        {
            const Coordinate goal;
            auto operator()(Coordinate c) const
            {
                auto result = hypot(abs(goal.x - c.x), abs(goal.y - c.y));
                return static_cast<int>(round(result));
            }
        };

        class Matrix
        {
        public:
            Matrix(unsigned height, unsigned width)
                : _data{ height, vector<LpState>(width)}
            {   }

            auto at(Coordinate c) -> LpState&
            {
                return{ _data[c.y][c.x] };
            }

            auto at(Coordinate c) const -> LpState const&
            {
                return{ _data[c.y][c.x] };
            }

        private:
            vector<vector<LpState>> _data;
        };
    }
}<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (c) 2015 Mark Charlebois. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 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.
 *
 ****************************************************************************/

/**
 * @file simulator.cpp
 * A device simulator
 */

#include <px4_log.h>
#include <px4_tasks.h>
#include <px4_time.h>
#include <pthread.h>
#include <poll.h>
#include <systemlib/err.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <drivers/drv_led.h>

#include "simulator.h"

using namespace simulator;

static px4_task_t g_sim_task = -1;

Simulator *Simulator::_instance = NULL;

Simulator *Simulator::getInstance()
{
	return _instance;
}

bool Simulator::getMPUReport(uint8_t *buf, int len)
{
	return _mpu.copyData(buf, len);
}

bool Simulator::getRawAccelReport(uint8_t *buf, int len)
{
	return _accel.copyData(buf, len);
}

bool Simulator::getMagReport(uint8_t *buf, int len)
{
	return _mag.copyData(buf, len);
}

bool Simulator::getBaroSample(uint8_t *buf, int len)
{
	return _baro.copyData(buf, len);
}

bool Simulator::getGPSSample(uint8_t *buf, int len)
{
	return _gps.copyData(buf, len);
}

bool Simulator::getAirspeedSample(uint8_t *buf, int len)
{
	return _airspeed.copyData(buf, len);
}

void Simulator::write_MPU_data(void *buf)
{
	_mpu.writeData(buf);
}

void Simulator::write_accel_data(void *buf)
{
	_accel.writeData(buf);
}

void Simulator::write_mag_data(void *buf)
{
	_mag.writeData(buf);
}

void Simulator::write_baro_data(void *buf)
{
	_baro.writeData(buf);
}

void Simulator::write_gps_data(void *buf)
{
	_gps.writeData(buf);
}

void Simulator::write_airspeed_data(void *buf)
{
	_airspeed.writeData(buf);
}

int Simulator::start(int argc, char *argv[])
{
	int ret = 0;
	int udp_port = 0;
	_instance = new Simulator();

	if (_instance) {
		drv_led_start();

		if (argc == 5 && strcmp(argv[3], "-u") == 0)
			udp_port = atoi(argv[4]);

		if (argv[2][1] == 's') {
			_instance->initializeSensorData();
#ifndef __PX4_QURT
			// Update sensor data
			_instance->pollForMAVLinkMessages(false,udp_port);
#endif

		} else if (argv[2][1] == 'p') {
			// Update sensor data
			_instance->pollForMAVLinkMessages(true,udp_port);

		} else {
			_instance->initializeSensorData();
			_instance->_initialized = true;
		}

	} else {
		PX4_WARN("Simulator creation failed");
		ret = 1;
	}

	return ret;
}

static void usage()
{
	PX4_WARN("Usage: simulator {start -[spt] [-u udp_port] |stop}");
	PX4_WARN("Simulate raw sensors:     simulator start -s");
	PX4_WARN("Publish sensors combined: simulator start -p");
	PX4_WARN("Dummy unit test data:     simulator start -t");
}

__BEGIN_DECLS
extern int simulator_main(int argc, char *argv[]);
__END_DECLS

extern "C" {

	int simulator_main(int argc, char *argv[])
	{
		int ret = 0;

		if (argc > 2 && strcmp(argv[1], "start") == 0) {
			if (strcmp(argv[2], "-s") == 0 ||
			    strcmp(argv[2], "-p") == 0 ||
			    strcmp(argv[2], "-t") == 0) {

				if (g_sim_task >= 0) {
					warnx("Simulator already started");
					return 0;
				}

				// enable lockstep support
				px4_enable_sim_lockstep();

				g_sim_task = px4_task_spawn_cmd("simulator",
								SCHED_DEFAULT,
								SCHED_PRIORITY_MAX,
								1500,
								Simulator::start,
								argv);

				// now wait for the command to complete
				while (true) {
					if (Simulator::getInstance() && Simulator::getInstance()->isInitialized()) {
						break;

					} else {
						usleep(100000);
					}
				}

			} else {
				usage();
				ret = -EINVAL;
			}

		} else if (argc == 2 && strcmp(argv[1], "stop") == 0) {
			if (g_sim_task < 0) {
				PX4_WARN("Simulator not running");

			} else {
				px4_task_delete(g_sim_task);
				g_sim_task = -1;
			}

		} else {
			usage();
			ret = -EINVAL;
		}

		return ret;
	}

}
<commit_msg>fix code style for Travis<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2015 Mark Charlebois. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 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.
 *
 ****************************************************************************/

/**
 * @file simulator.cpp
 * A device simulator
 */

#include <px4_log.h>
#include <px4_tasks.h>
#include <px4_time.h>
#include <pthread.h>
#include <poll.h>
#include <systemlib/err.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <drivers/drv_led.h>

#include "simulator.h"

using namespace simulator;

static px4_task_t g_sim_task = -1;

Simulator *Simulator::_instance = NULL;

Simulator *Simulator::getInstance()
{
	return _instance;
}

bool Simulator::getMPUReport(uint8_t *buf, int len)
{
	return _mpu.copyData(buf, len);
}

bool Simulator::getRawAccelReport(uint8_t *buf, int len)
{
	return _accel.copyData(buf, len);
}

bool Simulator::getMagReport(uint8_t *buf, int len)
{
	return _mag.copyData(buf, len);
}

bool Simulator::getBaroSample(uint8_t *buf, int len)
{
	return _baro.copyData(buf, len);
}

bool Simulator::getGPSSample(uint8_t *buf, int len)
{
	return _gps.copyData(buf, len);
}

bool Simulator::getAirspeedSample(uint8_t *buf, int len)
{
	return _airspeed.copyData(buf, len);
}

void Simulator::write_MPU_data(void *buf)
{
	_mpu.writeData(buf);
}

void Simulator::write_accel_data(void *buf)
{
	_accel.writeData(buf);
}

void Simulator::write_mag_data(void *buf)
{
	_mag.writeData(buf);
}

void Simulator::write_baro_data(void *buf)
{
	_baro.writeData(buf);
}

void Simulator::write_gps_data(void *buf)
{
	_gps.writeData(buf);
}

void Simulator::write_airspeed_data(void *buf)
{
	_airspeed.writeData(buf);
}

int Simulator::start(int argc, char *argv[])
{
	int ret = 0;
	int udp_port = 0;
	_instance = new Simulator();

	if (_instance) {
		drv_led_start();

		if (argc == 5 && strcmp(argv[3], "-u") == 0) {
			udp_port = atoi(argv[4]);
		}

		if (argv[2][1] == 's') {
			_instance->initializeSensorData();
#ifndef __PX4_QURT
			// Update sensor data
			_instance->pollForMAVLinkMessages(false, udp_port);
#endif

		} else if (argv[2][1] == 'p') {
			// Update sensor data
			_instance->pollForMAVLinkMessages(true, udp_port);

		} else {
			_instance->initializeSensorData();
			_instance->_initialized = true;
		}

	} else {
		PX4_WARN("Simulator creation failed");
		ret = 1;
	}

	return ret;
}

static void usage()
{
	PX4_WARN("Usage: simulator {start -[spt] [-u udp_port] |stop}");
	PX4_WARN("Simulate raw sensors:     simulator start -s");
	PX4_WARN("Publish sensors combined: simulator start -p");
	PX4_WARN("Dummy unit test data:     simulator start -t");
}

__BEGIN_DECLS
extern int simulator_main(int argc, char *argv[]);
__END_DECLS

extern "C" {

	int simulator_main(int argc, char *argv[])
	{
		int ret = 0;

		if (argc > 2 && strcmp(argv[1], "start") == 0) {
			if (strcmp(argv[2], "-s") == 0 ||
			    strcmp(argv[2], "-p") == 0 ||
			    strcmp(argv[2], "-t") == 0) {

				if (g_sim_task >= 0) {
					warnx("Simulator already started");
					return 0;
				}

				// enable lockstep support
				px4_enable_sim_lockstep();

				g_sim_task = px4_task_spawn_cmd("simulator",
								SCHED_DEFAULT,
								SCHED_PRIORITY_MAX,
								1500,
								Simulator::start,
								argv);

				// now wait for the command to complete
				while (true) {
					if (Simulator::getInstance() && Simulator::getInstance()->isInitialized()) {
						break;

					} else {
						usleep(100000);
					}
				}

			} else {
				usage();
				ret = -EINVAL;
			}

		} else if (argc == 2 && strcmp(argv[1], "stop") == 0) {
			if (g_sim_task < 0) {
				PX4_WARN("Simulator not running");

			} else {
				px4_task_delete(g_sim_task);
				g_sim_task = -1;
			}

		} else {
			usage();
			ret = -EINVAL;
		}

		return ret;
	}

}
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>

#include <vespa/eval/eval/value_type.h>
#include <vespa/searchlib/fef/feature_type.h>
#include <vespa/searchlib/fef/featurenameparser.h>
#include <vespa/searchlib/features/rankingexpressionfeature.h>
#include <vespa/searchlib/fef/test/dummy_dependency_handler.h>
#include <vespa/searchlib/fef/test/indexenvironment.h>

using namespace search::features;
using namespace search::features::rankingexpression;
using namespace search::fef::test;
using namespace search::fef;
using namespace vespalib::eval;

using TypeMap = std::map<vespalib::string,vespalib::string>;

struct DummyExpression : IntrinsicExpression {
    FeatureType type;
    DummyExpression(const FeatureType &type_in) : type(type_in) {}
    FeatureType result_type() const override { return type; }
    FeatureExecutor &create_executor(const QueryEnv &, vespalib::Stash &) const override {
        abort();
    }
};

struct DummyReplacer : ExpressionReplacer {
    vespalib::string trigger;
    FeatureType type;
    DummyReplacer(const vespalib::string trigger_in, const FeatureType &type_in)
        : trigger(trigger_in),
          type(type_in)
    {}
    IntrinsicExpression::UP maybe_replace(const vespalib::eval::Function &function,
                                          const search::fef::IIndexEnvironment &) const override
    {
        for (size_t i = 0; i < function.num_params(); ++i) {
            if (function.param_name(i) == trigger) {
                return std::make_unique<DummyExpression>(type);
            }
        }
        return IntrinsicExpression::UP(nullptr);
    }
};

ExpressionReplacer::SP make_replacer() {
    auto replacer = std::make_shared<ListExpressionReplacer>();
    replacer->add(std::make_unique<NullExpressionReplacer>());
    replacer->add(std::make_unique<DummyReplacer>("foo", FeatureType::number()));
    replacer->add(std::make_unique<DummyReplacer>("bar", FeatureType::object(ValueType::from_spec("tensor(x[])"))));
    return replacer;
}

struct SetupResult {
    IndexEnvironment index_env;
    RankingExpressionBlueprint rank;
    DummyDependencyHandler deps;
    bool setup_ok;
    SetupResult(const TypeMap &object_inputs, const vespalib::string &expression);
    ~SetupResult();
};

SetupResult::SetupResult(const TypeMap &object_inputs,
                         const vespalib::string &expression)
    : index_env(), rank(make_replacer()), deps(rank), setup_ok(false)
{
    rank.setName("self");
    index_env.getProperties().add("self.rankingScript", expression);
    for (const auto &input: object_inputs) {
        deps.define_object_input(input.first, ValueType::from_spec(input.second));
    }
    setup_ok = rank.setup(index_env, {});
    EXPECT_TRUE(!deps.accept_type_mismatch);
}
SetupResult::~SetupResult() {}

void verify_output_type(const TypeMap &object_inputs,
                        const vespalib::string &expression, const FeatureType &expect)
{
    SetupResult result(object_inputs, expression);
    EXPECT_TRUE(result.setup_ok);
    EXPECT_EQUAL(1u, result.deps.output.size());
    ASSERT_EQUAL(1u, result.deps.output_type.size());
    if (expect.is_object()) {
        EXPECT_EQUAL(expect.type(), result.deps.output_type[0].type());
    } else {
        EXPECT_TRUE(!result.deps.output_type[0].is_object());
    }
}

void verify_setup_fail(const TypeMap &object_inputs,
                       const vespalib::string &expression)
{
    SetupResult result(object_inputs, expression);
    EXPECT_TRUE(!result.setup_ok);
    EXPECT_EQUAL(0u, result.deps.output.size());
}

void verify_input_count(const vespalib::string &expression, size_t expect) {
    SetupResult result({}, expression);
    EXPECT_TRUE(result.setup_ok);
    EXPECT_EQUAL(result.deps.input.size(), expect);
}

TEST("require that expression with only number inputs produce number output (compiled)") {
    TEST_DO(verify_output_type({}, "a*b", FeatureType::number()));
}

TEST("require that expression with object input produces object output (interpreted)") {
    TEST_DO(verify_output_type({{"b", "double"}}, "a*b", FeatureType::object(ValueType::double_type())));
}

TEST("require that ranking expression can resolve to concrete complex type") {
    TEST_DO(verify_output_type({{"a", "tensor(x{},y{})"}, {"b", "tensor(y{},z{})"}}, "a*b",
                               FeatureType::object(ValueType::from_spec("tensor(x{},y{},z{})"))));
}

TEST("require that ranking expression can resolve to abstract complex type") {
    TEST_DO(verify_output_type({{"a", "tensor"}}, "a*b", FeatureType::object(ValueType::from_spec("tensor"))));
}

TEST("require that ranking expression can resolve to 'any' type") {
    TEST_DO(verify_output_type({{"a", "tensor(x{},y{})"}, {"b", "tensor"}}, "a*b",
                               FeatureType::object(ValueType::from_spec("any"))));
}

TEST("require that setup fails for incompatible types") {
    TEST_DO(verify_setup_fail({{"a", "tensor(x{},y{})"}, {"b", "tensor(y[10],z{})"}}, "a*b"));
}

TEST("require that replaced expressions have no inputs") {
    TEST_DO(verify_input_count("a*b*c", 3u));
    TEST_DO(verify_input_count("foo*b*c", 0u));
    TEST_DO(verify_input_count("a*b*bar", 0u));
    TEST_DO(verify_input_count("foo*b*bar", 0u));
}

TEST("require that replaced expressions override result type") {
    TEST_DO(verify_output_type({{"b", "tensor(z{})"}}, "a*b*c",
                               FeatureType::object(ValueType::from_spec("tensor(z{})"))));
    TEST_DO(verify_output_type({{"b", "tensor(z{})"}}, "foo*b*c",
                               FeatureType::number()));
    TEST_DO(verify_output_type({{"b", "tensor(z{})"}}, "a*b*bar",
                               FeatureType::object(ValueType::from_spec("tensor(x[])"))));
    TEST_DO(verify_output_type({{"b", "tensor(z{})"}}, "foo*b*bar",
                               FeatureType::number()));
}

TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>test that appropriate executor is created<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>

#include <vespa/eval/eval/value_type.h>
#include <vespa/searchlib/fef/feature_type.h>
#include <vespa/searchlib/fef/featurenameparser.h>
#include <vespa/searchlib/features/rankingexpressionfeature.h>
#include <vespa/searchlib/fef/test/dummy_dependency_handler.h>
#include <vespa/searchlib/fef/test/indexenvironment.h>
#include <vespa/searchlib/fef/test/queryenvironment.h>

using namespace search::features;
using namespace search::features::rankingexpression;
using namespace search::fef::test;
using namespace search::fef;
using namespace vespalib::eval;

using TypeMap = std::map<vespalib::string,vespalib::string>;

struct DummyExecutor : FeatureExecutor {
    void execute(uint32_t) override {}
};

struct DummyExpression : IntrinsicExpression {
    FeatureType type;
    DummyExpression(const FeatureType &type_in) : type(type_in) {}
    FeatureType result_type() const override { return type; }
    FeatureExecutor &create_executor(const QueryEnv &, vespalib::Stash &stash) const override {
        return stash.create<DummyExecutor>();
    }
};

struct DummyReplacer : ExpressionReplacer {
    vespalib::string trigger;
    FeatureType type;
    DummyReplacer(const vespalib::string trigger_in, const FeatureType &type_in)
        : trigger(trigger_in),
          type(type_in)
    {}
    IntrinsicExpression::UP maybe_replace(const vespalib::eval::Function &function,
                                          const search::fef::IIndexEnvironment &) const override
    {
        for (size_t i = 0; i < function.num_params(); ++i) {
            if (function.param_name(i) == trigger) {
                return std::make_unique<DummyExpression>(type);
            }
        }
        return IntrinsicExpression::UP(nullptr);
    }
};

ExpressionReplacer::SP make_replacer() {
    auto replacer = std::make_shared<ListExpressionReplacer>();
    replacer->add(std::make_unique<NullExpressionReplacer>());
    replacer->add(std::make_unique<DummyReplacer>("foo", FeatureType::number()));
    replacer->add(std::make_unique<DummyReplacer>("bar", FeatureType::object(ValueType::from_spec("tensor(x[])"))));
    return replacer;
}

struct SetupResult {
    vespalib::Stash stash;
    IndexEnvironment index_env;
    QueryEnvironment query_env;
    RankingExpressionBlueprint rank;
    DummyDependencyHandler deps;
    bool setup_ok;
    SetupResult(const TypeMap &object_inputs, const vespalib::string &expression);
    ~SetupResult();
};

SetupResult::SetupResult(const TypeMap &object_inputs,
                         const vespalib::string &expression)
    : stash(), index_env(), query_env(&index_env), rank(make_replacer()), deps(rank), setup_ok(false)
{
    rank.setName("self");
    index_env.getProperties().add("self.rankingScript", expression);
    for (const auto &input: object_inputs) {
        deps.define_object_input(input.first, ValueType::from_spec(input.second));
    }
    setup_ok = rank.setup(index_env, {});
    EXPECT_TRUE(!deps.accept_type_mismatch);
}
SetupResult::~SetupResult() {}

void verify_output_type(const TypeMap &object_inputs,
                        const vespalib::string &expression, const FeatureType &expect)
{
    SetupResult result(object_inputs, expression);
    EXPECT_TRUE(result.setup_ok);
    EXPECT_EQUAL(1u, result.deps.output.size());
    ASSERT_EQUAL(1u, result.deps.output_type.size());
    if (expect.is_object()) {
        EXPECT_EQUAL(expect.type(), result.deps.output_type[0].type());
    } else {
        EXPECT_TRUE(!result.deps.output_type[0].is_object());
    }
}

void verify_setup_fail(const TypeMap &object_inputs,
                       const vespalib::string &expression)
{
    SetupResult result(object_inputs, expression);
    EXPECT_TRUE(!result.setup_ok);
    EXPECT_EQUAL(0u, result.deps.output.size());
}

void verify_input_count(const vespalib::string &expression, size_t expect) {
    SetupResult result({}, expression);
    EXPECT_TRUE(result.setup_ok);
    EXPECT_EQUAL(result.deps.input.size(), expect);
}

TEST("require that expression with only number inputs produce number output (compiled)") {
    TEST_DO(verify_output_type({}, "a*b", FeatureType::number()));
}

TEST("require that expression with object input produces object output (interpreted)") {
    TEST_DO(verify_output_type({{"b", "double"}}, "a*b", FeatureType::object(ValueType::double_type())));
}

TEST("require that ranking expression can resolve to concrete complex type") {
    TEST_DO(verify_output_type({{"a", "tensor(x{},y{})"}, {"b", "tensor(y{},z{})"}}, "a*b",
                               FeatureType::object(ValueType::from_spec("tensor(x{},y{},z{})"))));
}

TEST("require that ranking expression can resolve to abstract complex type") {
    TEST_DO(verify_output_type({{"a", "tensor"}}, "a*b", FeatureType::object(ValueType::from_spec("tensor"))));
}

TEST("require that ranking expression can resolve to 'any' type") {
    TEST_DO(verify_output_type({{"a", "tensor(x{},y{})"}, {"b", "tensor"}}, "a*b",
                               FeatureType::object(ValueType::from_spec("any"))));
}

TEST("require that setup fails for incompatible types") {
    TEST_DO(verify_setup_fail({{"a", "tensor(x{},y{})"}, {"b", "tensor(y[10],z{})"}}, "a*b"));
}

TEST("require that replaced expressions have no inputs") {
    TEST_DO(verify_input_count("a*b*c", 3u));
    TEST_DO(verify_input_count("foo*b*c", 0u));
    TEST_DO(verify_input_count("a*b*bar", 0u));
    TEST_DO(verify_input_count("foo*b*bar", 0u));
}

TEST("require that replaced expressions override result type") {
    TEST_DO(verify_output_type({{"b", "tensor(z{})"}}, "a*b*c",
                               FeatureType::object(ValueType::from_spec("tensor(z{})"))));
    TEST_DO(verify_output_type({{"b", "tensor(z{})"}}, "foo*b*c",
                               FeatureType::number()));
    TEST_DO(verify_output_type({{"b", "tensor(z{})"}}, "a*b*bar",
                               FeatureType::object(ValueType::from_spec("tensor(x[])"))));
    TEST_DO(verify_output_type({{"b", "tensor(z{})"}}, "foo*b*bar",
                               FeatureType::number()));
}

TEST_F("require that replaced expressions create the appropriate executor", SetupResult({}, "foo")) {
    EXPECT_TRUE(f1.setup_ok);
    FeatureExecutor &executor = f1.rank.createExecutor(f1.query_env, f1.stash);
    EXPECT_TRUE(dynamic_cast<DummyExecutor*>(&executor) != nullptr);
}

TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|>


<commit_before>// Copyright (c) 2008 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 "net/proxy/proxy_script_fetcher.h"

#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/ref_counted.h"
#include "base/string_util.h"
#include "net/base/io_buffer.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request.h"

// TODO(eroman):
//   - Support auth-prompts.

namespace net {

namespace {

// The maximum size (in bytes) allowed for a PAC script. Responses exceeding
// this will fail with ERR_FILE_TOO_BIG.
int max_response_bytes = 1048576;  // 1 megabyte

// The maximum duration (in milliseconds) allowed for fetching the PAC script.
// Responses exceeding this will fail with ERR_TIMED_OUT.
int max_duration_ms = 300000;  // 5 minutes

// Returns true if |mime_type| is one of the known PAC mime type.
bool IsPacMimeType(const std::string& mime_type) {
  static const char * const kSupportedPacMimeTypes[] = {
    "application/x-ns-proxy-autoconfig",
    "application/x-javascript-config",
  };
  for (size_t i = 0; i < arraysize(kSupportedPacMimeTypes); ++i) {
    if (LowerCaseEqualsASCII(mime_type, kSupportedPacMimeTypes[i]))
      return true;
  }
  return false;
}

}  // namespace

class ProxyScriptFetcherImpl : public ProxyScriptFetcher,
                               public URLRequest::Delegate {
 public:
  // Creates a ProxyScriptFetcher that issues requests through
  // |url_request_context|. |url_request_context| must remain valid for the
  // lifetime of ProxyScriptFetcherImpl.
  explicit ProxyScriptFetcherImpl(URLRequestContext* url_request_context);

  virtual ~ProxyScriptFetcherImpl();

  // ProxyScriptFetcher methods:

  virtual void Fetch(const GURL& url, std::string* bytes,
                     CompletionCallback* callback);
  virtual void Cancel();

  // URLRequest::Delegate methods:

  virtual void OnAuthRequired(URLRequest* request,
                              AuthChallengeInfo* auth_info);
  virtual void OnSSLCertificateError(URLRequest* request, int cert_error,
                                     X509Certificate* cert);
  virtual void OnReceivedRedirect(URLRequest* request, const GURL& to_url);
  virtual void OnResponseStarted(URLRequest* request);
  virtual void OnReadCompleted(URLRequest* request, int num_bytes);
  virtual void OnResponseCompleted(URLRequest* request);

 private:
  // Read more bytes from the response.
  void ReadBody(URLRequest* request);

  // Called once the request has completed to notify the caller of
  // |response_code_| and |response_bytes_|.
  void FetchCompleted();

  // Clear out the state for the current request.
  void ResetCurRequestState();

  // Callback for time-out task of request with id |id|.
  void OnTimeout(int id);

  // Factory for creating the time-out task. This takes care of revoking
  // outstanding tasks when |this| is deleted.
  ScopedRunnableMethodFactory<ProxyScriptFetcherImpl> task_factory_;

  // The context used for making network requests.
  URLRequestContext* url_request_context_;

  // Buffer that URLRequest writes into.
  enum { kBufSize = 4096 };
  scoped_refptr<net::IOBuffer> buf_;

  // The next ID to use for |cur_request_| (monotonically increasing).
  int next_id_;

  // The current (in progress) request, or NULL.
  scoped_ptr<URLRequest> cur_request_;

  // State for current request (only valid when |cur_request_| is not NULL):

  // Unique ID for the current request.
  int cur_request_id_;

  // Callback to invoke on completion of the fetch.
  CompletionCallback* callback_;

  // Holds the error condition that was hit on the current request, or OK.
  int result_code_;

  // Holds the bytes read so far. Will not exceed |max_response_bytes|. This
  // buffer is owned by the owner of |callback|.
  std::string* result_bytes_;
};

ProxyScriptFetcherImpl::ProxyScriptFetcherImpl(
    URLRequestContext* url_request_context)
    : ALLOW_THIS_IN_INITIALIZER_LIST(task_factory_(this)),
      url_request_context_(url_request_context),
      buf_(new net::IOBuffer(kBufSize)),
      next_id_(0),
      cur_request_(NULL),
      cur_request_id_(0),
      callback_(NULL),
      result_code_(OK),
      result_bytes_(NULL) {
  DCHECK(url_request_context);
}

ProxyScriptFetcherImpl::~ProxyScriptFetcherImpl() {
  // The URLRequest's destructor will cancel the outstanding request, and
  // ensure that the delegate (this) is not called again.
}

void ProxyScriptFetcherImpl::Fetch(const GURL& url,
                                   std::string* bytes,
                                   CompletionCallback* callback) {
  // It is invalid to call Fetch() while a request is already in progress.
  DCHECK(!cur_request_.get());

  DCHECK(callback);
  DCHECK(bytes);

  cur_request_.reset(new URLRequest(url, this));
  cur_request_->set_context(url_request_context_);
  cur_request_->set_method("GET");

  // Make sure that the PAC script is downloaded using a direct connection,
  // to avoid circular dependencies (fetching is a part of proxy resolution).
  cur_request_->set_load_flags(LOAD_BYPASS_PROXY);

  // Save the caller's info for notification on completion.
  callback_ = callback;
  result_bytes_ = bytes;
  result_bytes_->clear();

  // Post a task to timeout this request if it takes too long.
  cur_request_id_ = ++next_id_;
  MessageLoop::current()->PostDelayedTask(FROM_HERE,
      task_factory_.NewRunnableMethod(&ProxyScriptFetcherImpl::OnTimeout,
                                      cur_request_id_),
      static_cast<int>(max_duration_ms));

  // Start the request.
  cur_request_->Start();
}

void ProxyScriptFetcherImpl::Cancel() {
  // ResetCurRequestState will free the URLRequest, which will cause
  // cancellation.
  ResetCurRequestState();
}

void ProxyScriptFetcherImpl::OnAuthRequired(URLRequest* request,
                                            AuthChallengeInfo* auth_info) {
  DCHECK(request == cur_request_.get());
  // TODO(eroman):
  LOG(WARNING) << "Auth required to fetch PAC script, aborting.";
  result_code_ = ERR_NOT_IMPLEMENTED;
  request->CancelAuth();
}

void ProxyScriptFetcherImpl::OnSSLCertificateError(URLRequest* request,
                                                   int cert_error,
                                                   X509Certificate* cert) {
  DCHECK(request == cur_request_.get());
  LOG(WARNING) << "SSL certificate error when fetching PAC script, aborting.";
  // Certificate errors are in same space as net errors.
  result_code_ = cert_error;
  request->Cancel();
}

void ProxyScriptFetcherImpl::OnReceivedRedirect(URLRequest* request,
                                                const GURL& to_url) {
  DCHECK(request == cur_request_.get());
  // OK, thanks for telling.
}

void ProxyScriptFetcherImpl::OnResponseStarted(URLRequest* request) {
  DCHECK(request == cur_request_.get());

  if (!request->status().is_success()) {
    OnResponseCompleted(request);
    return;
  }

  // Require HTTP responses to have a success status code.
  if (request->url().SchemeIs("http") || request->url().SchemeIs("https")) {
    // NOTE about status codes: We are like Firefox 3 in this respect.
    // {IE 7, Safari 3, Opera 9.5} do not care about the status code.
    if (request->GetResponseCode() != 200) {
      result_code_ = ERR_PAC_STATUS_NOT_OK;
      request->Cancel();
      return;
    }

    // NOTE about mime types: We do not enforce mime types on PAC files.
    // This is for compatibility with {IE 7, Firefox 3, Opera 9.5}. We will
    // however log mismatches to help with debugging.
    if (logging::GetMinLogLevel() <= logging::LOG_INFO) {
      std::string mime_type;
      cur_request_->GetMimeType(&mime_type);
      if (!!IsPacMimeType(mime_type)) {
        LOG(INFO) << "Fetched PAC script does not have a proper mime type: "
                  << mime_type;
      }
    }
  }

  ReadBody(request);
}

void ProxyScriptFetcherImpl::OnReadCompleted(URLRequest* request,
                                             int num_bytes) {
  DCHECK(request == cur_request_.get());
  if (num_bytes > 0) {
    // Enforce maximum size bound.
    if (num_bytes + result_bytes_->size() >
        static_cast<size_t>(max_response_bytes)) {
      result_code_ = ERR_FILE_TOO_BIG;
      request->Cancel();
      return;
    }
    result_bytes_->append(buf_->data(), num_bytes);
    ReadBody(request);
  } else {  // Error while reading, or EOF
    OnResponseCompleted(request);
  }
}

void ProxyScriptFetcherImpl::OnResponseCompleted(URLRequest* request) {
  DCHECK(request == cur_request_.get());

  // Use |result_code_| as the request's error if we have already set it to
  // something specific.
  if (result_code_ == OK && !request->status().is_success())
    result_code_ = request->status().os_error();

  FetchCompleted();
}

void ProxyScriptFetcherImpl::ReadBody(URLRequest* request) {
  int num_bytes;
  if (request->Read(buf_, kBufSize, &num_bytes)) {
    OnReadCompleted(request, num_bytes);
  } else if (!request->status().is_io_pending()) {
    // Read failed synchronously.
    OnResponseCompleted(request);
  }
}

void ProxyScriptFetcherImpl::FetchCompleted() {
  // On error, the caller expects empty string for bytes.
  if (result_code_ != OK)
    result_bytes_->clear();

  int result_code = result_code_;
  CompletionCallback* callback = callback_;

  ResetCurRequestState();

  callback->Run(result_code);
}

void ProxyScriptFetcherImpl::ResetCurRequestState() {
  cur_request_.reset();
  cur_request_id_ = 0;
  callback_ = NULL;
  result_code_ = OK;
  result_bytes_ = NULL;
}

void ProxyScriptFetcherImpl::OnTimeout(int id) {
  // Timeout tasks may outlive the URLRequest they reference. Make sure it
  // is still applicable.
  if (cur_request_id_ != id)
    return;

  DCHECK(cur_request_.get());
  result_code_ = ERR_TIMED_OUT;
  cur_request_->Cancel();
}

// static
ProxyScriptFetcher* ProxyScriptFetcher::Create(
    URLRequestContext* url_request_context) {
  return new ProxyScriptFetcherImpl(url_request_context);
}

// static
int ProxyScriptFetcher::SetTimeoutConstraintForUnittest(
    int timeout_ms) {
  int prev = max_duration_ms;
  max_duration_ms = timeout_ms;
  return prev;
}

// static
size_t ProxyScriptFetcher::SetSizeConstraintForUnittest(size_t size_bytes) {
  size_t prev = max_response_bytes;
  max_response_bytes = size_bytes;
  return prev;
}

}  // namespace net
<commit_msg>Fix a typo (one extra '!') in the previous checkin (r13601).<commit_after>// Copyright (c) 2008 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 "net/proxy/proxy_script_fetcher.h"

#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/ref_counted.h"
#include "base/string_util.h"
#include "net/base/io_buffer.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request.h"

// TODO(eroman):
//   - Support auth-prompts.

namespace net {

namespace {

// The maximum size (in bytes) allowed for a PAC script. Responses exceeding
// this will fail with ERR_FILE_TOO_BIG.
int max_response_bytes = 1048576;  // 1 megabyte

// The maximum duration (in milliseconds) allowed for fetching the PAC script.
// Responses exceeding this will fail with ERR_TIMED_OUT.
int max_duration_ms = 300000;  // 5 minutes

// Returns true if |mime_type| is one of the known PAC mime type.
bool IsPacMimeType(const std::string& mime_type) {
  static const char * const kSupportedPacMimeTypes[] = {
    "application/x-ns-proxy-autoconfig",
    "application/x-javascript-config",
  };
  for (size_t i = 0; i < arraysize(kSupportedPacMimeTypes); ++i) {
    if (LowerCaseEqualsASCII(mime_type, kSupportedPacMimeTypes[i]))
      return true;
  }
  return false;
}

}  // namespace

class ProxyScriptFetcherImpl : public ProxyScriptFetcher,
                               public URLRequest::Delegate {
 public:
  // Creates a ProxyScriptFetcher that issues requests through
  // |url_request_context|. |url_request_context| must remain valid for the
  // lifetime of ProxyScriptFetcherImpl.
  explicit ProxyScriptFetcherImpl(URLRequestContext* url_request_context);

  virtual ~ProxyScriptFetcherImpl();

  // ProxyScriptFetcher methods:

  virtual void Fetch(const GURL& url, std::string* bytes,
                     CompletionCallback* callback);
  virtual void Cancel();

  // URLRequest::Delegate methods:

  virtual void OnAuthRequired(URLRequest* request,
                              AuthChallengeInfo* auth_info);
  virtual void OnSSLCertificateError(URLRequest* request, int cert_error,
                                     X509Certificate* cert);
  virtual void OnReceivedRedirect(URLRequest* request, const GURL& to_url);
  virtual void OnResponseStarted(URLRequest* request);
  virtual void OnReadCompleted(URLRequest* request, int num_bytes);
  virtual void OnResponseCompleted(URLRequest* request);

 private:
  // Read more bytes from the response.
  void ReadBody(URLRequest* request);

  // Called once the request has completed to notify the caller of
  // |response_code_| and |response_bytes_|.
  void FetchCompleted();

  // Clear out the state for the current request.
  void ResetCurRequestState();

  // Callback for time-out task of request with id |id|.
  void OnTimeout(int id);

  // Factory for creating the time-out task. This takes care of revoking
  // outstanding tasks when |this| is deleted.
  ScopedRunnableMethodFactory<ProxyScriptFetcherImpl> task_factory_;

  // The context used for making network requests.
  URLRequestContext* url_request_context_;

  // Buffer that URLRequest writes into.
  enum { kBufSize = 4096 };
  scoped_refptr<net::IOBuffer> buf_;

  // The next ID to use for |cur_request_| (monotonically increasing).
  int next_id_;

  // The current (in progress) request, or NULL.
  scoped_ptr<URLRequest> cur_request_;

  // State for current request (only valid when |cur_request_| is not NULL):

  // Unique ID for the current request.
  int cur_request_id_;

  // Callback to invoke on completion of the fetch.
  CompletionCallback* callback_;

  // Holds the error condition that was hit on the current request, or OK.
  int result_code_;

  // Holds the bytes read so far. Will not exceed |max_response_bytes|. This
  // buffer is owned by the owner of |callback|.
  std::string* result_bytes_;
};

ProxyScriptFetcherImpl::ProxyScriptFetcherImpl(
    URLRequestContext* url_request_context)
    : ALLOW_THIS_IN_INITIALIZER_LIST(task_factory_(this)),
      url_request_context_(url_request_context),
      buf_(new net::IOBuffer(kBufSize)),
      next_id_(0),
      cur_request_(NULL),
      cur_request_id_(0),
      callback_(NULL),
      result_code_(OK),
      result_bytes_(NULL) {
  DCHECK(url_request_context);
}

ProxyScriptFetcherImpl::~ProxyScriptFetcherImpl() {
  // The URLRequest's destructor will cancel the outstanding request, and
  // ensure that the delegate (this) is not called again.
}

void ProxyScriptFetcherImpl::Fetch(const GURL& url,
                                   std::string* bytes,
                                   CompletionCallback* callback) {
  // It is invalid to call Fetch() while a request is already in progress.
  DCHECK(!cur_request_.get());

  DCHECK(callback);
  DCHECK(bytes);

  cur_request_.reset(new URLRequest(url, this));
  cur_request_->set_context(url_request_context_);
  cur_request_->set_method("GET");

  // Make sure that the PAC script is downloaded using a direct connection,
  // to avoid circular dependencies (fetching is a part of proxy resolution).
  cur_request_->set_load_flags(LOAD_BYPASS_PROXY);

  // Save the caller's info for notification on completion.
  callback_ = callback;
  result_bytes_ = bytes;
  result_bytes_->clear();

  // Post a task to timeout this request if it takes too long.
  cur_request_id_ = ++next_id_;
  MessageLoop::current()->PostDelayedTask(FROM_HERE,
      task_factory_.NewRunnableMethod(&ProxyScriptFetcherImpl::OnTimeout,
                                      cur_request_id_),
      static_cast<int>(max_duration_ms));

  // Start the request.
  cur_request_->Start();
}

void ProxyScriptFetcherImpl::Cancel() {
  // ResetCurRequestState will free the URLRequest, which will cause
  // cancellation.
  ResetCurRequestState();
}

void ProxyScriptFetcherImpl::OnAuthRequired(URLRequest* request,
                                            AuthChallengeInfo* auth_info) {
  DCHECK(request == cur_request_.get());
  // TODO(eroman):
  LOG(WARNING) << "Auth required to fetch PAC script, aborting.";
  result_code_ = ERR_NOT_IMPLEMENTED;
  request->CancelAuth();
}

void ProxyScriptFetcherImpl::OnSSLCertificateError(URLRequest* request,
                                                   int cert_error,
                                                   X509Certificate* cert) {
  DCHECK(request == cur_request_.get());
  LOG(WARNING) << "SSL certificate error when fetching PAC script, aborting.";
  // Certificate errors are in same space as net errors.
  result_code_ = cert_error;
  request->Cancel();
}

void ProxyScriptFetcherImpl::OnReceivedRedirect(URLRequest* request,
                                                const GURL& to_url) {
  DCHECK(request == cur_request_.get());
  // OK, thanks for telling.
}

void ProxyScriptFetcherImpl::OnResponseStarted(URLRequest* request) {
  DCHECK(request == cur_request_.get());

  if (!request->status().is_success()) {
    OnResponseCompleted(request);
    return;
  }

  // Require HTTP responses to have a success status code.
  if (request->url().SchemeIs("http") || request->url().SchemeIs("https")) {
    // NOTE about status codes: We are like Firefox 3 in this respect.
    // {IE 7, Safari 3, Opera 9.5} do not care about the status code.
    if (request->GetResponseCode() != 200) {
      result_code_ = ERR_PAC_STATUS_NOT_OK;
      request->Cancel();
      return;
    }

    // NOTE about mime types: We do not enforce mime types on PAC files.
    // This is for compatibility with {IE 7, Firefox 3, Opera 9.5}. We will
    // however log mismatches to help with debugging.
    if (logging::GetMinLogLevel() <= logging::LOG_INFO) {
      std::string mime_type;
      cur_request_->GetMimeType(&mime_type);
      if (!IsPacMimeType(mime_type)) {
        LOG(INFO) << "Fetched PAC script does not have a proper mime type: "
                  << mime_type;
      }
    }
  }

  ReadBody(request);
}

void ProxyScriptFetcherImpl::OnReadCompleted(URLRequest* request,
                                             int num_bytes) {
  DCHECK(request == cur_request_.get());
  if (num_bytes > 0) {
    // Enforce maximum size bound.
    if (num_bytes + result_bytes_->size() >
        static_cast<size_t>(max_response_bytes)) {
      result_code_ = ERR_FILE_TOO_BIG;
      request->Cancel();
      return;
    }
    result_bytes_->append(buf_->data(), num_bytes);
    ReadBody(request);
  } else {  // Error while reading, or EOF
    OnResponseCompleted(request);
  }
}

void ProxyScriptFetcherImpl::OnResponseCompleted(URLRequest* request) {
  DCHECK(request == cur_request_.get());

  // Use |result_code_| as the request's error if we have already set it to
  // something specific.
  if (result_code_ == OK && !request->status().is_success())
    result_code_ = request->status().os_error();

  FetchCompleted();
}

void ProxyScriptFetcherImpl::ReadBody(URLRequest* request) {
  int num_bytes;
  if (request->Read(buf_, kBufSize, &num_bytes)) {
    OnReadCompleted(request, num_bytes);
  } else if (!request->status().is_io_pending()) {
    // Read failed synchronously.
    OnResponseCompleted(request);
  }
}

void ProxyScriptFetcherImpl::FetchCompleted() {
  // On error, the caller expects empty string for bytes.
  if (result_code_ != OK)
    result_bytes_->clear();

  int result_code = result_code_;
  CompletionCallback* callback = callback_;

  ResetCurRequestState();

  callback->Run(result_code);
}

void ProxyScriptFetcherImpl::ResetCurRequestState() {
  cur_request_.reset();
  cur_request_id_ = 0;
  callback_ = NULL;
  result_code_ = OK;
  result_bytes_ = NULL;
}

void ProxyScriptFetcherImpl::OnTimeout(int id) {
  // Timeout tasks may outlive the URLRequest they reference. Make sure it
  // is still applicable.
  if (cur_request_id_ != id)
    return;

  DCHECK(cur_request_.get());
  result_code_ = ERR_TIMED_OUT;
  cur_request_->Cancel();
}

// static
ProxyScriptFetcher* ProxyScriptFetcher::Create(
    URLRequestContext* url_request_context) {
  return new ProxyScriptFetcherImpl(url_request_context);
}

// static
int ProxyScriptFetcher::SetTimeoutConstraintForUnittest(
    int timeout_ms) {
  int prev = max_duration_ms;
  max_duration_ms = timeout_ms;
  return prev;
}

// static
size_t ProxyScriptFetcher::SetSizeConstraintForUnittest(size_t size_bytes) {
  size_t prev = max_response_bytes;
  max_response_bytes = size_bytes;
  return prev;
}

}  // namespace net
<|endoftext|>


<commit_before>#ifndef _ordering_annealing_cpp_included_
#define _ordering_annealing_cpp_included_

// c++ header files
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>

// my header files
#include "ordering-annealing.hpp"
#include "ordering-io.hpp"
#include "ordering-tools.hpp"

// namespaces
using namespace std;

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

This program reorders the elements of a matrix making first a blocking
into kernels (so it is better that they are hierarchically clustered
first. The program will not perform hierarhchical clustering itself.
Then, the algorith repositions bloks selected at random, the width of
the block is selected so that at low temperature is of size one.

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

int ChangeSegmentOrder(vector<int>& order, int line1, int line2, int width){

  if( line1 < line2 )
    rotate(order.begin()+line1,order.begin()+line1+width,order.begin()+line2+width);
  else
    rotate(order.begin()+line2,order.begin()+line1,order.begin()+line1+width);

  return 1;
}

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

int MakeChangeVectors(const vector <int>& order,
                      vector<int>& change,
                      vector<int>& nochange,
                      int line1,
                      int line2,
                      int width,
                      int n,
                      const vector<int>& klines){

  int i,in,in2,j,jmax, nk = klines.size();
  vector<bool> changed(n,false);

  change.clear();
  change.reserve(n);

  for(i=line1; i<line1+width; i++){
    in = order[i];

    if(in != nk-1)
      jmax = klines[in+1] - klines[in];
    else
      jmax = n - klines[in];

    for(j=0;j<jmax;j++){
      change.push_back( klines[in] + j );
      changed[klines[in]+j] = true;
    }

  }

  if(line1<line2){

    for(i=line1+width; i<line2+width; i++){
      in = order[i];

      if(in != nk-1)
        jmax = klines[in+1] - klines[in];
      else
        jmax = n-klines[in];

      for(j=0; j<jmax; j++){
        change.push_back( klines[in] + j );
        changed[klines[in]+j] = true;
      }

    }

  }

  if( line1 > line2 ){

    for(i=line2; i<line1; i++){
      in = order[i];

      if(in != nk-1)
        jmax = klines[in+1] - klines[in];
      else
        jmax = n - klines[in];

      for(j=0; j<jmax; j++){
        change.push_back( klines[in] + j );
        changed[klines[in]+j] = true;
      }

    }

  }

  nochange.clear();
  nochange.reserve(n-change.size());
  for(i=0;i<n;i++){
    if(!changed[i]){
      nochange.push_back(i);
    }
  }

  return 1;

}

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

double ComputeEnergy(const vector<double>& mat, int netSize, const vector<int>& kernelOrder,
		                 const vector<int>& klines){
  //kernelOrder: vector with the order of kernels
  //klines: line in original matrix where kernel starts
  int i,j;
  double energy = 0.;
  vector<int> nodeOrder = GetNodeOrder(kernelOrder, klines, netSize, 1);

  for(i=0;i<netSize-1;i++){
    for(j=i+1;j<netSize;j++){
      energy += double(abs(i-j)) * mat[ nodeOrder[i] + netSize* nodeOrder[j] ];
      // cout<<i<< " "<<j<<" "<< nodeOrder[i] << " "<< netSize<<endl;
      // cout<<i<< " "<<j<<" "<<mat[ nodeOrder[i] + netSize* nodeOrder[j] ]<<endl;
    }
  }

  energy = 2*energy/double(netSize);

  return energy;

}

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

double EnergyChangeReOrd(const vector<double>& mat,int l1,int l2,int w,int n,
			                   const vector<int>& kernelOrder,
                         const vector<int>& klines,
                         vector<int>& newKernelOrder){

  double deltaen = 0;
  unsigned int i,j;
  int line1,line2;
  int do1, do2, oo1, no1;

  // determine what the new order will be
  ChangeSegmentOrder(newKernelOrder,l1,l2,w);

    // only calculate a change in energy when some lines actually changed
  if(newKernelOrder != kernelOrder){

    // determine what the node by node order is based on their kernels
    vector<int> oldorder,neworder;
    oldorder=GetNodeOrder(kernelOrder,klines,n,0);
    neworder=GetNodeOrder(newKernelOrder,klines,n,0);

    //make two vectors, one with the rows that
    //change position and one with the rows
    //that keep the same position
    vector<int> lchange,lfix;
    MakeChangeVectors(kernelOrder, lchange, lfix, l1, l2, w, n, klines);

    // calculate the change in energy only for pairs that are altered by change
    for(i=0;i<lchange.size();i++){
      line1 = lchange[i];
      oo1 = oldorder[line1];
      no1 = neworder[line1];
      for(j=0;j<lfix.size();j++){
        line2=lfix[j];
        do1 = abs(oo1-oldorder[line2]);
        do2 = abs(no1-neworder[line2]);
        deltaen+=mat[line1+line2*n]*(do2-do1);
      }

      for(j=i+1;j<lchange.size();j++){
        line2=lchange[j];
        do1 = abs(oo1-oldorder[line2]);
        do2 = abs(no1-neworder[line2]);
        deltaen+=mat[line1+line2*n]*(do2-do1);
      }
    }

    deltaen = 2*deltaen/double(n);
  }

  return deltaen;
}

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

double AnnealStep(double temperature,
                  const vector<double>& matrix,
                  int netSize,
		              vector <int>& order,
                  int nblocks,
                  const vector<int>& klines,
                  bool freeStep)
  //Only reordering matrix rordering matrix
{

  int line1,line2,width, nkernels=klines.size();
  double deltaE;

//    double energy,energyold;
//    energyold=energy=ComputeEnergy(*mat, n, *order, klines);

   //1 pick two random numbers (starting line that we are swapping)

  line1 = line2 = width = 0;

  //"Computing line and width\n";

  width = (int)( fabs(gauss(sqrt(temperature)*.05*nkernels) ) ) + nblocks;
//   width = nblocks;
  width -= (width%nblocks);

  line1 = width/2 + (int)( (nkernels-width)*ran1f() );
  line1 -= width/2;
  line1 -= (line1%nblocks);

  if ( line1 < 0 ) line1 = 0;

  while( width > nkernels-line1 ){

    width = (int)( fabs( gauss( sqrt(temperature)*.05*nkernels ) ) ) + nblocks;
    width -= (width%nblocks);

  }

  line2=(int)(gauss(sqrt(temperature)*.1));

  if( line2 < 0 ){

    line2 -= line1;
    if( line2 < 0 ) line2=0;

  }
  else{

    line2 += line1 + width;
    if ( line2 > nkernels-width ) line2 = nkernels-width;

  }

  line2 -= (line2%nblocks);

  vector<int> neworder(order);
  deltaE = EnergyChangeReOrd(matrix, line1, line2, width, netSize, order, klines, neworder);

  if(freeStep || ranf() < exp( -deltaE/temperature )){
    order = neworder;
    return deltaE;
  }

  return 0;
}

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

void AnnealIter(double temperature,
                const vector<double>& matrix,
                const vector<int>& translationTable,
                const vector<vector<int> >& kernels,
		            int nsteps,int n,
                vector<int>& order,double& energy,double& minenergy,int nblocks,
		            const vector<int>& kline){

  int step,i1,ii1;
  double deltaen;

  for( step=0; step<nsteps; step++ ){
    deltaen = AnnealStep(temperature, matrix, n, order, nblocks, kline, false);
    energy += deltaen;

    if(energy < minenergy ){
      minenergy = energy;
      //PrintMatrix( "coclas-minimum.dat", matrix, order, kline, n, 0);
      PrintTranstable( "transtable-minimum.dat", translationTable, order, kernels);
      PrintValue( "energy-minimum.dat", minenergy);
    }
  }

}

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

void InitialTemp(double& temperature,
            		 const vector<double>& matrix,
                 const vector<int>& translationTable,
		             const vector<vector<int> >& kernels,
                 int nsteps,int n,
                 vector<int>& order,
                 int nblocks,
                 const vector<int>& kline){

  int step;
  double deltaen;
  double initialProbability = 0.95;
  int i;
  vector<int> itorder(order);

  temperature = ComputeEnergy(matrix, n, itorder, kline);
  for(i=0;i<20;i++){
    deltaen = 0;
    for( step=0; step<nsteps; step++ ){
        deltaen += fabs(AnnealStep(temperature, matrix, n, itorder, nblocks, kline, true));
    }

    deltaen /= double(nsteps);
    temperature = deltaen/(-log(initialProbability));
  }

  order = itorder;
}

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

double ExhaustiveStep(const vector<double>& matrix,int n,
            		      vector<int>& order,
                      const vector<int>& klines,
                      int row, int nblocks)
{

  int line1, line2, width, nk=klines.size();
  double deltaE,maxdeltaE=0;
  int line=-1,wl=0;
  vector<int> maxorder, neworder(order);

  line1=row;

  //cout<<"Iterating \n"<<endl;
  for (width = nblocks; width>0 ; width--){

    if( line1+width < nk ){

      for (line2=0;line2<= nk-width;line2++){

        if(line2<line1 || line2 >= line1+width){

          deltaE = EnergyChangeReOrd(matrix, line1, line2, width, n, order, klines, neworder);

          if(deltaE<maxdeltaE){
            maxdeltaE = deltaE;
            line = line2;
            wl = width;
            maxorder = neworder;
          }
        }
      }
    }
  }

  if(line !=-1){
    order = maxorder;
    return maxdeltaE;
  }
  else{
    return 0;
  }
}

void ExhaustiveIter(const vector<double>& matrix,
                    int n,
		                vector<int>& order,
                    double& energy,
                    const vector<int>& kline,
                    int nblocks){

  int step,nsteps=kline.size();
  double deltaen;
  int line;

  for(step=0;step<nsteps;step++){
    ///we try to change the kernel originally at position 0, line is ist current position
    line = find(order.begin(),order.end(),step) - order.begin();
    deltaen = ExhaustiveStep(matrix, n, order, kline, line, nblocks);
    energy+=deltaen;
  }
}

#endif
<commit_msg>removing a few more warnings about unused variables and making ChangeSegmentOrder fully consistent<commit_after>#ifndef _ordering_annealing_cpp_included_
#define _ordering_annealing_cpp_included_

// c++ header files
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>

// my header files
#include "ordering-annealing.hpp"
#include "ordering-io.hpp"
#include "ordering-tools.hpp"

// namespaces
using namespace std;

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

This program reorders the elements of a matrix making first a blocking
into kernels (so it is better that they are hierarchically clustered
first. The program will not perform hierarhchical clustering itself.
Then, the algorith repositions bloks selected at random, the width of
the block is selected so that at low temperature is of size one.

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

int ChangeSegmentOrder(vector<int>& order, int line1, int line2, int width){

  if( line1 < line2 )
    rotate(order.begin()+line1,order.begin()+line2,order.begin()+line2+width);
  else
    rotate(order.begin()+line2,order.begin()+line1,order.begin()+line1+width);

  return 1;
}

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

int MakeChangeVectors(const vector <int>& order,
                      vector<int>& change,
                      vector<int>& nochange,
                      int line1,
                      int line2,
                      int width,
                      int n,
                      const vector<int>& klines){

  int i,in,j,jmax, nk = klines.size();
  vector<bool> changed(n,false);

  change.clear();
  change.reserve(n);

  for(i=line1; i<line1+width; i++){
    in = order[i];

    if(in != nk-1)
      jmax = klines[in+1] - klines[in];
    else
      jmax = n - klines[in];

    for(j=0;j<jmax;j++){
      change.push_back( klines[in] + j );
      changed[klines[in]+j] = true;
    }

  }

  if(line1<line2){

    for(i=line1+width; i<line2+width; i++){
      in = order[i];

      if(in != nk-1)
        jmax = klines[in+1] - klines[in];
      else
        jmax = n-klines[in];

      for(j=0; j<jmax; j++){
        change.push_back( klines[in] + j );
        changed[klines[in]+j] = true;
      }

    }

  }

  if( line1 > line2 ){

    for(i=line2; i<line1; i++){
      in = order[i];

      if(in != nk-1)
        jmax = klines[in+1] - klines[in];
      else
        jmax = n - klines[in];

      for(j=0; j<jmax; j++){
        change.push_back( klines[in] + j );
        changed[klines[in]+j] = true;
      }

    }

  }

  nochange.clear();
  nochange.reserve(n-change.size());
  for(i=0;i<n;i++){
    if(!changed[i]){
      nochange.push_back(i);
    }
  }

  return 1;

}

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

double ComputeEnergy(const vector<double>& mat, int netSize, const vector<int>& kernelOrder,
		                 const vector<int>& klines){
  //kernelOrder: vector with the order of kernels
  //klines: line in original matrix where kernel starts
  int i,j;
  double energy = 0.;
  vector<int> nodeOrder = GetNodeOrder(kernelOrder, klines, netSize, 1);

  for(i=0;i<netSize-1;i++){
    for(j=i+1;j<netSize;j++){
      energy += double(abs(i-j)) * mat[ nodeOrder[i] + netSize* nodeOrder[j] ];
      // cout<<i<< " "<<j<<" "<< nodeOrder[i] << " "<< netSize<<endl;
      // cout<<i<< " "<<j<<" "<<mat[ nodeOrder[i] + netSize* nodeOrder[j] ]<<endl;
    }
  }

  energy = 2*energy/double(netSize);

  return energy;

}

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

double EnergyChangeReOrd(const vector<double>& mat,int l1,int l2,int w,int n,
			                   const vector<int>& kernelOrder,
                         const vector<int>& klines,
                         vector<int>& newKernelOrder){

  double deltaen = 0;
  unsigned int i,j;
  int line1,line2;
  int do1, do2, oo1, no1;

  // determine what the new order will be
  ChangeSegmentOrder(newKernelOrder,l1,l2,w);

    // only calculate a change in energy when some lines actually changed
  if(newKernelOrder != kernelOrder){

    // determine what the node by node order is based on their kernels
    vector<int> oldorder,neworder;
    oldorder=GetNodeOrder(kernelOrder,klines,n,0);
    neworder=GetNodeOrder(newKernelOrder,klines,n,0);

    //make two vectors, one with the rows that
    //change position and one with the rows
    //that keep the same position
    vector<int> lchange,lfix;
    MakeChangeVectors(kernelOrder, lchange, lfix, l1, l2, w, n, klines);

    // calculate the change in energy only for pairs that are altered by change
    for(i=0;i<lchange.size();i++){
      line1 = lchange[i];
      oo1 = oldorder[line1];
      no1 = neworder[line1];
      for(j=0;j<lfix.size();j++){
        line2=lfix[j];
        do1 = abs(oo1-oldorder[line2]);
        do2 = abs(no1-neworder[line2]);
        deltaen+=mat[line1+line2*n]*(do2-do1);
      }

      for(j=i+1;j<lchange.size();j++){
        line2=lchange[j];
        do1 = abs(oo1-oldorder[line2]);
        do2 = abs(no1-neworder[line2]);
        deltaen+=mat[line1+line2*n]*(do2-do1);
      }
    }

    deltaen = 2*deltaen/double(n);
  }

  return deltaen;
}

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

double AnnealStep(double temperature,
                  const vector<double>& matrix,
                  int netSize,
		              vector <int>& order,
                  int nblocks,
                  const vector<int>& klines,
                  bool freeStep)
  //Only reordering matrix rordering matrix
{

  int line1,line2,width, nkernels=klines.size();
  double deltaE;

//    double energy,energyold;
//    energyold=energy=ComputeEnergy(*mat, n, *order, klines);

   //1 pick two random numbers (starting line that we are swapping)

  line1 = line2 = width = 0;

  //"Computing line and width\n";

  width = (int)( fabs(gauss(sqrt(temperature)*.05*nkernels) ) ) + nblocks;
//   width = nblocks;
  width -= (width%nblocks);

  line1 = width/2 + (int)( (nkernels-width)*ran1f() );
  line1 -= width/2;
  line1 -= (line1%nblocks);

  if ( line1 < 0 ) line1 = 0;

  while( width > nkernels-line1 ){

    width = (int)( fabs( gauss( sqrt(temperature)*.05*nkernels ) ) ) + nblocks;
    width -= (width%nblocks);

  }

  line2=(int)(gauss(sqrt(temperature)*.1));

  if( line2 < 0 ){

    line2 -= line1;
    if( line2 < 0 ) line2=0;

  }
  else{

    line2 += line1 + width;
    if ( line2 > nkernels-width ) line2 = nkernels-width;

  }

  line2 -= (line2%nblocks);

  vector<int> neworder(order);
  deltaE = EnergyChangeReOrd(matrix, line1, line2, width, netSize, order, klines, neworder);

  if(freeStep || ranf() < exp( -deltaE/temperature )){
    order = neworder;
    return deltaE;
  }

  return 0;
}

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

void AnnealIter(double temperature,
                const vector<double>& matrix,
                const vector<int>& translationTable,
                const vector<vector<int> >& kernels,
		            int nsteps,int n,
                vector<int>& order,double& energy,double& minenergy,int nblocks,
		            const vector<int>& kline){

  int step; //,i1,ii1;
  double deltaen;

  for( step=0; step<nsteps; step++ ){
    deltaen = AnnealStep(temperature, matrix, n, order, nblocks, kline, false);
    energy += deltaen;

    if(energy < minenergy ){
      minenergy = energy;
      //PrintMatrix( "coclas-minimum.dat", matrix, order, kline, n, 0);
      PrintTranstable( "transtable-minimum.dat", translationTable, order, kernels);
      PrintValue( "energy-minimum.dat", minenergy);
    }
  }

}

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

void InitialTemp(double& temperature,
            		 const vector<double>& matrix,
                 const vector<int>& translationTable,
		             const vector<vector<int> >& kernels,
                 int nsteps,int n,
                 vector<int>& order,
                 int nblocks,
                 const vector<int>& kline){

  int step;
  double deltaen;
  double initialProbability = 0.95;
  int i;
  vector<int> itorder(order);

  temperature = ComputeEnergy(matrix, n, itorder, kline);
  for(i=0;i<20;i++){
    deltaen = 0;
    for( step=0; step<nsteps; step++ ){
        deltaen += fabs(AnnealStep(temperature, matrix, n, itorder, nblocks, kline, true));
    }

    deltaen /= double(nsteps);
    temperature = deltaen/(-log(initialProbability));
  }

  order = itorder;
}

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

double ExhaustiveStep(const vector<double>& matrix,int n,
            		      vector<int>& order,
                      const vector<int>& klines,
                      int row, int nblocks)
{

  int line1, line2, width, nk=klines.size();
  double deltaE,maxdeltaE=0;
  int line=-1,wl=0;
  vector<int> maxorder, neworder(order);

  line1=row;

  //cout<<"Iterating \n"<<endl;
  for (width = nblocks; width>0 ; width--){

    if( line1+width < nk ){

      for (line2=0;line2<= nk-width;line2++){

        if(line2<line1 || line2 >= line1+width){

          deltaE = EnergyChangeReOrd(matrix, line1, line2, width, n, order, klines, neworder);

          if(deltaE<maxdeltaE){
            maxdeltaE = deltaE;
            line = line2;
            wl = width;
            maxorder = neworder;
          }
        }
      }
    }
  }

  if(line !=-1){
    order = maxorder;
    return maxdeltaE;
  }
  else{
    return 0;
  }
}

void ExhaustiveIter(const vector<double>& matrix,
                    int n,
		                vector<int>& order,
                    double& energy,
                    const vector<int>& kline,
                    int nblocks){

  int step,nsteps=kline.size();
  double deltaen;
  int line;

  for(step=0;step<nsteps;step++){
    ///we try to change the kernel originally at position 0, line is ist current position
    line = find(order.begin(),order.end(),step) - order.begin();
    deltaen = ExhaustiveStep(matrix, n, order, kline, line, nblocks);
    energy+=deltaen;
  }
}

#endif
<|endoftext|>


<commit_before><commit_msg>set up the basic arena endpoint<commit_after><|endoftext|>


<commit_before><commit_msg>binding: fix build on *nix<commit_after><|endoftext|>


<commit_before>#include "Codegen.h"
#include <stdexcept>

#define __ m_Assembler.

namespace snow {
namespace x86_64 {
	static const Register* arg_regs[] = { &rdi, &rsi, &rdx, &rcx, &r8, &r9 };

	static const Register* tmp_regs[] = { &rax,  &r10,  &r11,  &rbx, &r12, &r13, &r14, &r15 };
	static const bool preserve_regs[] = { false, false, false, true, true, true, true, true };

	static inline Address addr_for_local(const Scope::Local& local) {
		return Address(rbp, (local.index + 1 + sizeof(StackFrame)) * -8, true);
	}

	static inline const Register& reg_for_arg(int index) {
		return *arg_regs[index];
	}

	static inline const Register& reg_for_tmp(int index) {
		return *tmp_regs[index];
	}

	void Codegen::preserve_tmp_reg(int index) {
		if (preserve_regs[index]) {
			m_CurrentScope.enter_asm->push(*tmp_regs[index]);
			m_PreservedTempRegisters.push_back(tmp_regs[index]);
		}
	}

	RefPtr<CompiledCode> Codegen::compile() {
		return __ compile();
	}

	Scope Codegen::function_entry(int num_locals) {
		int stack_size = sizeof(StackFrame) + sizeof(VALUE)*num_locals;
		// maintain 16-byte stack alignment
		stack_size += stack_size % 16;

		// enter uses a 16-bit immediate for stack size
		if (stack_size < 1 << 16)
			__ enter(stack_size);
		else {
			// ... which may be too little
			__ push(rbp);
			__ mov(rsp, rbp);
			__ sub(stack_size, rsp);
		}

		// Establish scope
		x86_64::Assembler* enter_asm = new x86_64::Assembler;
		x86_64::Assembler* leave_asm = new x86_64::Assembler;

		if (m_CurrentScope.enter_asm)
			m_ScopeData.push_back(m_CurrentScope);
		m_CurrentScope = ScopeData(enter_asm, leave_asm);

		int stack_frame_offset = -(int)sizeof(StackFrame);

		// Create stack frame
		__ mov(rdi, rbx);           // preserve first argument
		__ mov(num_locals, rcx);    // frame->num_locals = num_locals
		__ mov(rcx, Address(rbp, stack_frame_offset+offsetof(StackFrame, num_locals)));
		__ mov(rbp, rax);
		__ add(stack_frame_offset, rax);
		__ mov(rax, rdi);           // StackFrame* is first argument below
		__ sub(sizeof(VALUE)*num_locals, rax);  // frame->locals = %rbp - stack_frame - locals
		__ mov(rax, Address(rbp, stack_frame_offset+offsetof(StackFrame, locals)));
		__ call("snow_create_stack_frame");     // initialize with runtime info
		__ mov(rbx, rdi);           // restore first argument

		// Preserve registers
		__ subasm(enter_asm);

		return Scope();
	}

	void Codegen::function_return() {
		// Restore non-volatile registers
		for (auto iter = riterate(m_PreservedTempRegisters); iter; ++iter) {
			m_CurrentScope.leave_asm->pop(**iter);
		}
		m_PreservedTempRegisters.clear();

		__ subasm(m_CurrentScope.leave_asm);
		__ leave();
		__ ret();

		// Restore parent scope, if any
		if (m_ScopeData.size() > 0) {
			m_CurrentScope = ScopeData(m_ScopeData.back());
			m_ScopeData.pop_back();
		} else {
			m_CurrentScope = ScopeData();
		}
	}

	void Codegen::set_argument(int index, const Scope::Local& src) {
		__ mov(addr_for_local(src), reg_for_arg(index));
	}

	void Codegen::set_argument(int index, const Scope::Temporary& src) {
		__ mov(reg_for_tmp(src.index), reg_for_arg(index));
	}

	void Codegen::set_argument(int index, const void* ptr) {
		__ mov((const char*)ptr, reg_for_arg(index));
	}

	void Codegen::set_argument(int index, int immediate) {
		__ mov(immediate, reg_for_arg(index));
	}

	void Codegen::get_argument(int index, const Scope::Local& dst) {
		__ mov(reg_for_arg(index), addr_for_local(dst));
	}

	void Codegen::get_argument(int index, const Scope::Temporary& dst) {
		preserve_tmp_reg(dst.index);
		__ mov(reg_for_arg(index), reg_for_tmp(dst.index));
	}

	void Codegen::set_return(const Scope::Local& src) {
		__ mov(addr_for_local(src), rax);
	}

	void Codegen::set_return(const Scope::Temporary& src) {
		if (reg_for_tmp(src.index) != rax)
			__ mov(reg_for_tmp(src.index), rax);
	}

	void Codegen::call(const char* symbol) {
		__ clear(rax);
		__ call(symbol);
	}

	void Codegen::call(const char* symbol, const Scope::Local& retval) {
		call(symbol);
		__ mov(rax, addr_for_local(retval));
	}

	void Codegen::call(const char* symbol, const Scope::Temporary& retval) {
		call(symbol);
		if (reg_for_tmp(retval.index) != rax)
			__ mov(rax, reg_for_tmp(retval.index));
	}
}
}<commit_msg>comment: stack layout<commit_after>#include "Codegen.h"
#include <stdexcept>

#define __ m_Assembler.

namespace snow {
namespace x86_64 {
	static const Register* arg_regs[] = { &rdi, &rsi, &rdx, &rcx, &r8, &r9 };

	static const Register* tmp_regs[] = { &rax,  &r10,  &r11,  &rbx, &r12, &r13, &r14, &r15 };
	static const bool preserve_regs[] = { false, false, false, true, true, true, true, true };

	static inline Address addr_for_local(const Scope::Local& local) {
		return Address(rbp, (local.index + 1 + sizeof(StackFrame)) * -8, true);
	}

	static inline const Register& reg_for_arg(int index) {
		return *arg_regs[index];
	}

	static inline const Register& reg_for_tmp(int index) {
		return *tmp_regs[index];
	}

	void Codegen::preserve_tmp_reg(int index) {
		if (preserve_regs[index]) {
			m_CurrentScope.enter_asm->push(*tmp_regs[index]);
			m_PreservedTempRegisters.push_back(tmp_regs[index]);
		}
	}

	RefPtr<CompiledCode> Codegen::compile() {
		return __ compile();
	}

	Scope Codegen::function_entry(int num_locals) {
		/*
			STACK LAYOUT:

			struct StackFrame
				StackFrame* previous
				uint64_t num_locals
				VALUE* locals
			VALUE* local1 = self
			VALUE* local2 = arg1
			VALUE* local3 = arg2
			VALUE* local4
			...
			VALUE* local(num_locals-1)
		*/

		int stack_size = sizeof(StackFrame) + sizeof(VALUE)*num_locals;
		// maintain 16-byte stack alignment
		stack_size += stack_size % 16;

		// enter uses a 16-bit immediate for stack size
		if (stack_size < 1 << 16)
			__ enter(stack_size);
		else {
			// ... which may be too little
			__ push(rbp);
			__ mov(rsp, rbp);
			__ sub(stack_size, rsp);
		}

		// Establish scope
		x86_64::Assembler* enter_asm = new x86_64::Assembler;
		x86_64::Assembler* leave_asm = new x86_64::Assembler;

		if (m_CurrentScope.enter_asm)
			m_ScopeData.push_back(m_CurrentScope);
		m_CurrentScope = ScopeData(enter_asm, leave_asm);

		int stack_frame_offset = -(int)sizeof(StackFrame);

		// Create stack frame
		__ mov(rdi, rbx);           // preserve first argument
		__ mov(num_locals, rcx);    // frame->num_locals = num_locals
		__ mov(rcx, Address(rbp, stack_frame_offset+offsetof(StackFrame, num_locals)));
		__ mov(rbp, rax);
		__ add(stack_frame_offset, rax);
		__ mov(rax, rdi);           // StackFrame* is first argument below
		__ sub(sizeof(VALUE)*num_locals, rax);  // frame->locals = %rbp - stack_frame - locals
		__ mov(rax, Address(rbp, stack_frame_offset+offsetof(StackFrame, locals)));
		__ call("snow_create_stack_frame");     // initialize with runtime info
		__ mov(rbx, rdi);           // restore first argument

		// Preserve registers
		__ subasm(enter_asm);

		return Scope();
	}

	void Codegen::function_return() {
		// Restore non-volatile registers
		for (auto iter = riterate(m_PreservedTempRegisters); iter; ++iter) {
			m_CurrentScope.leave_asm->pop(**iter);
		}
		m_PreservedTempRegisters.clear();

		__ subasm(m_CurrentScope.leave_asm);
		__ leave();
		__ ret();

		// Restore parent scope, if any
		if (m_ScopeData.size() > 0) {
			m_CurrentScope = ScopeData(m_ScopeData.back());
			m_ScopeData.pop_back();
		} else {
			m_CurrentScope = ScopeData();
		}
	}

	void Codegen::set_argument(int index, const Scope::Local& src) {
		__ mov(addr_for_local(src), reg_for_arg(index));
	}

	void Codegen::set_argument(int index, const Scope::Temporary& src) {
		__ mov(reg_for_tmp(src.index), reg_for_arg(index));
	}

	void Codegen::set_argument(int index, const void* ptr) {
		__ mov((const char*)ptr, reg_for_arg(index));
	}

	void Codegen::set_argument(int index, int immediate) {
		__ mov(immediate, reg_for_arg(index));
	}

	void Codegen::get_argument(int index, const Scope::Local& dst) {
		__ mov(reg_for_arg(index), addr_for_local(dst));
	}

	void Codegen::get_argument(int index, const Scope::Temporary& dst) {
		preserve_tmp_reg(dst.index);
		__ mov(reg_for_arg(index), reg_for_tmp(dst.index));
	}

	void Codegen::set_return(const Scope::Local& src) {
		__ mov(addr_for_local(src), rax);
	}

	void Codegen::set_return(const Scope::Temporary& src) {
		if (reg_for_tmp(src.index) != rax)
			__ mov(reg_for_tmp(src.index), rax);
	}

	void Codegen::call(const char* symbol) {
		__ clear(rax);
		__ call(symbol);
	}

	void Codegen::call(const char* symbol, const Scope::Local& retval) {
		call(symbol);
		__ mov(rax, addr_for_local(retval));
	}

	void Codegen::call(const char* symbol, const Scope::Temporary& retval) {
		call(symbol);
		if (reg_for_tmp(retval.index) != rax)
			__ mov(rax, reg_for_tmp(retval.index));
	}
}
}<|endoftext|>


<commit_before><commit_msg>Flush the queue after every run iteration<commit_after><|endoftext|>