<commit_before>#include <Arduino.h>
#include <stdint.h>
#include <setjmp.h>
#include "task.h"

static task_queue delaying;

void task_queue::insert(task *p, task *t) {
	if (p) {
		t->next = p->next;
		p->next = t;
		if (p == _tail)
			_tail = t;
	} else {
		t->next = _head;
		_head = t;
	}
}

#define MAX_DELAY       0xf000000

void Tasks::delay(unsigned long ms) {
	unsigned long now = millis();
	task *p, *q;
	for (p = 0, q = delaying.head(); q; p = q, q = q->next) {
		unsigned long qms = q->wake - now;
		if (qms >= MAX_DELAY) {
			Tasks::ready(delaying.remove());
			q = delaying.head();
			continue;
		}
		if (qms > ms)
			break;
	}
	task *t = Tasks::current();
	t->wake = now + ms;
	delaying.insert(p, t);
	Tasks::reschedule();
}

void timer_sleep() {
	task *t = delaying.remove();
	unsigned long ms = t->wake - millis();
	if (ms < MAX_DELAY)
		delay(ms);
	Tasks::ready(t);
}
<commit_msg>add Atomic<commit_after>#include <Arduino.h>
#include <stdint.h>
#include <setjmp.h>
#include "atomic.h"
#include "task.h"

static task_queue delaying;

void task_queue::insert(task *p, task *t) {
	if (p) {
		t->next = p->next;
		p->next = t;
		if (p == _tail)
			_tail = t;
	} else {
		t->next = _head;
		_head = t;
	}
}

#define MAX_DELAY       0xf000000

void Tasks::delay(unsigned long ms) {
	Atomic block;
	unsigned long now = millis();
	task *p, *q;
	for (p = 0, q = delaying.head(); q; p = q, q = q->next) {
		unsigned long qms = q->wake - now;
		if (qms >= MAX_DELAY) {
			Tasks::ready(delaying.remove());
			q = delaying.head();
			continue;
		}
		if (qms > ms)
			break;
	}
	task *t = Tasks::current();
	t->wake = now + ms;
	delaying.insert(p, t);
	Tasks::reschedule();
}

void timer_sleep() {
	task *t = delaying.remove();
	unsigned long ms = t->wake - millis();
	if (ms < MAX_DELAY)
		delay(ms);
	Tasks::ready(t);
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/ecc/mainline_rce_trap.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file mainline_rce_trap.H
/// @brief Subroutines for the MC mainline rce address trap registers (MBRCER*Q)
///
// *HWP HWP Owner: Louis Stermole <stermole@us.ibm.com>
// *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#ifndef _MSS_MAINLINE_RCE_TRAP_H_
#define _MSS_MAINLINE_RCE_TRAP_H_

#include <fapi2.H>
#include <lib/mcbist/address.H>
#include <generic/memory/lib/utils/scom.H>
#include <lib/utils/find.H>
#include <lib/ecc/ecc_traits.H>

namespace mss
{

namespace ecc
{

namespace mainline_rce_trap
{

///
/// @brief Read MBS Mainline RCE Address Trap (MBRCER*Q) register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in] i_target the fapi2 target of the mc
/// @param[out] o_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T, typename TT = eccTraits<T> >
inline fapi2::ReturnCode read( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data )
{
    const auto& l_mcbist_target = mss::find_target<fapi2::TARGET_TYPE_MCBIST>(i_target);
    const auto& l_port = mss::relative_pos<fapi2::TARGET_TYPE_MCBIST>(i_target);

    FAPI_TRY( mss::getScom(l_mcbist_target, (TT::MAINLINE_RCE_REGS[l_port]), o_data) );
    FAPI_INF("read: 0x%016lx", o_data);
fapi_try_exit:
    return fapi2::current_err;
}

///
/// @brief Write MBS Mainline RCE Address Trap (MBRCER*Q) register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in] i_target the fapi2 target of the mc
/// @param[in] i_data the value to write to the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T, typename TT = eccTraits<T> >
inline fapi2::ReturnCode write( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data )
{
    const auto& l_mcbist_target = mss::find_target<fapi2::TARGET_TYPE_MCBIST>(i_target);
    const auto& l_port = mss::relative_pos<fapi2::TARGET_TYPE_MCBIST>(i_target);

    FAPI_TRY( mss::putScom(l_mcbist_target, (TT::MAINLINE_RCE_REGS[l_port]), i_data) );
    FAPI_INF("write: 0x%016lx", i_data);
fapi_try_exit:
    return fapi2::current_err;
}

///
/// @brief set_address
/// @tparam T fapi2 Target Type defaults to TARGET_TYPE_MCA
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in, out] io_data the register value
/// @param[in] i_address mcbist::address form of address field
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = eccTraits<T> >
inline void set_address( fapi2::buffer<uint64_t>& io_data, const mcbist::address& i_address)
{
    io_data.insertFromRight<TT::RCE_ADDR_TRAP, TT::RCE_ADDR_TRAP_LEN>(uint64_t(i_address));
    FAPI_INF("set_address: 0x%016lx", uint64_t(i_address));
}

///
/// @brief get_address
/// @tparam T fapi2 Target Type defaults to TARGET_TYPE_MCA
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in] i_data the register value
/// @param[out] o_address mcbist::address form of address field
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = eccTraits<T> >
inline void get_address( const fapi2::buffer<uint64_t>& i_data, mcbist::address& o_address )
{
    uint64_t l_addr = 0;
    i_data.extractToRight<TT::RCE_ADDR_TRAP, TT::RCE_ADDR_TRAP_LEN>(l_addr);
    o_address = mcbist::address(l_addr);
    FAPI_INF("get_address: 0x%016lx", uint64_t(l_addr));
}

} // close namespace mainline_rce_trap

} // close namespace ecc

} // close namespace mss

#endif
<commit_msg>Move find API to share among memory controllers<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/ecc/mainline_rce_trap.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file mainline_rce_trap.H
/// @brief Subroutines for the MC mainline rce address trap registers (MBRCER*Q)
///
// *HWP HWP Owner: Louis Stermole <stermole@us.ibm.com>
// *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#ifndef _MSS_MAINLINE_RCE_TRAP_H_
#define _MSS_MAINLINE_RCE_TRAP_H_

#include <fapi2.H>
#include <lib/mcbist/address.H>
#include <generic/memory/lib/utils/scom.H>
#include <generic/memory/lib/utils/find.H>
#include <lib/ecc/ecc_traits.H>

namespace mss
{

namespace ecc
{

namespace mainline_rce_trap
{

///
/// @brief Read MBS Mainline RCE Address Trap (MBRCER*Q) register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in] i_target the fapi2 target of the mc
/// @param[out] o_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T, typename TT = eccTraits<T> >
inline fapi2::ReturnCode read( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data )
{
    const auto& l_mcbist_target = mss::find_target<fapi2::TARGET_TYPE_MCBIST>(i_target);
    const auto& l_port = mss::relative_pos<fapi2::TARGET_TYPE_MCBIST>(i_target);

    FAPI_TRY( mss::getScom(l_mcbist_target, (TT::MAINLINE_RCE_REGS[l_port]), o_data) );
    FAPI_INF("read: 0x%016lx", o_data);
fapi_try_exit:
    return fapi2::current_err;
}

///
/// @brief Write MBS Mainline RCE Address Trap (MBRCER*Q) register
/// @tparam T fapi2 Target Type - derived from i_target's type
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in] i_target the fapi2 target of the mc
/// @param[in] i_data the value to write to the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< fapi2::TargetType T, typename TT = eccTraits<T> >
inline fapi2::ReturnCode write( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data )
{
    const auto& l_mcbist_target = mss::find_target<fapi2::TARGET_TYPE_MCBIST>(i_target);
    const auto& l_port = mss::relative_pos<fapi2::TARGET_TYPE_MCBIST>(i_target);

    FAPI_TRY( mss::putScom(l_mcbist_target, (TT::MAINLINE_RCE_REGS[l_port]), i_data) );
    FAPI_INF("write: 0x%016lx", i_data);
fapi_try_exit:
    return fapi2::current_err;
}

///
/// @brief set_address
/// @tparam T fapi2 Target Type defaults to TARGET_TYPE_MCA
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in, out] io_data the register value
/// @param[in] i_address mcbist::address form of address field
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = eccTraits<T> >
inline void set_address( fapi2::buffer<uint64_t>& io_data, const mcbist::address& i_address)
{
    io_data.insertFromRight<TT::RCE_ADDR_TRAP, TT::RCE_ADDR_TRAP_LEN>(uint64_t(i_address));
    FAPI_INF("set_address: 0x%016lx", uint64_t(i_address));
}

///
/// @brief get_address
/// @tparam T fapi2 Target Type defaults to TARGET_TYPE_MCA
/// @tparam TT traits type defaults to eccTraits<T>
/// @param[in] i_data the register value
/// @param[out] o_address mcbist::address form of address field
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = eccTraits<T> >
inline void get_address( const fapi2::buffer<uint64_t>& i_data, mcbist::address& o_address )
{
    uint64_t l_addr = 0;
    i_data.extractToRight<TT::RCE_ADDR_TRAP, TT::RCE_ADDR_TRAP_LEN>(l_addr);
    o_address = mcbist::address(l_addr);
    FAPI_INF("get_address: 0x%016lx", uint64_t(l_addr));
}

} // close namespace mainline_rce_trap

} // close namespace ecc

} // close namespace mss

#endif
<|endoftext|>


<commit_before>// ============================================================================
//
//                      Compressible Thermal GKS
//
// ============================================================================

#include "GKSMesh.h"
#include "BoundaryCondition.h"
#include <iostream>
#include <sstream>
#include <chrono>

using namespace std;

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

    // ========================================================================
    //
    //                  Couette-Flow (Periodic)
    //
    // ========================================================================

    Parameters param;

    double H = 1.0;
    double W = 0.25;

    param.numberOfIterations = 1000000;
    param.outputIntervalVTK = 1000000;
    param.outputInterval = 10000;

    param.convergenceCriterium = 1.0e-6;

    param.CFL = 0.5;

    param.verbose = false;

    // ========================================================================

    FluidParameter fluidParam;

    fluidParam.K = 1;
    fluidParam.nu = 1e-2;
    fluidParam.R = 200.0;
    fluidParam.Force.x = 1e-4;
    fluidParam.Force.y = 0.0;

    // ========================================================================

    GKSMesh* mesh = new GKSMesh(param, fluidParam);

    // Define Boundary Conditions
    //    -----------
    //    |    3    |
    //    | 0     2 |
    //    |    1    |
    //    -----------
    mesh->addBoundaryCondition(1, 1, 1, 1, 0.0, 0.00, 0.0, 0.0);
    mesh->addBoundaryCondition(1, 0, 0, 1, 0.0, 0.00, 0.0, 0.0);
    mesh->addBoundaryCondition(1, 1, 1, 1, 0.0, 0.00, 0.0, 0.0);
    mesh->addBoundaryCondition(1, 0, 0, 1, 0.0, 0.005, 0.0, 0.0);

    // Generate Mesh
    mesh->generateRectMesh(W, H, 2, 2);

    // Initialize Values
    mesh->initMeshConstant(1.0, 0.0, 0.0, 1.0);

    */

    ///*

    // ========================================================================
    //
    //                  Poiseuille-Flow (Force driven)
    //
    // ========================================================================

    Parameters param;

    double H = 1.0;
    double W = 1.0;

    param.numberOfIterations = 100;
    param.outputInterval = 1;
    param.CFL = 0.5;

    param.verbose = false;

    // ========================================================================

    FluidParameter fluidParam;

    fluidParam.K  = 1;
    fluidParam.nu = 1e-2;
    fluidParam.R = 200.0;
    fluidParam.Force.x = 1e-4;
    fluidParam.Force.y = 0.0;

    // ========================================================================

    GKSMesh* mesh = new GKSMesh(param, fluidParam);

    // Define Boundary Conditions
    //    -----------
    //    |    1    |
    //    |         |
    //    |    0    |
    //    -----------
    mesh->addInterfaceBoundaryCondition(0.0);
    mesh->addInterfaceBoundaryCondition(0.0);

    // Generate Mesh
    mesh->generateRectMeshPeriodicInterfaceBCs(W, H, 1, 64);

    // Initialize Values
    mesh->initMeshConstant(1.0, 0.0, 0.0, 1.0);

    //*/

    // ========================================================================
    // ========================================================================
    // ========================================================================
    // ========================================================================
    // ========================================================================

    GKSMesh* mesh = new GKSMesh(param, fluidParam);

    // Define Boundary Conditions
    //    -----------
    //    |    3    |
    //    | 0     2 |
    //    |    1    |
    //    -----------
    mesh->addBoundaryCondition(1, 1, 1, 1, 0.0, 0.0, 0.0, 1.0);
    mesh->addBoundaryCondition(1, 0, 0, 1, 0.0, 0.0, 0.0, 1.0);
    mesh->addBoundaryCondition(1, 1, 1, 1, 0.0, 0.0, 0.0, 1.0);
    mesh->addBoundaryCondition(1, 0, 0, 1, 0.0, 0.0, 0.0, 1.0);

    // Generate Mesh
    mesh->generateRectMesh(W, H, 100, 100);

    // Initialize Values
    // mesh->initMeshConstant(1.0, 0.0, 0.0, 1.0);

    double rho[] = { 1.0, 1.0 + 1.0e-3 };

    mesh->initMeshLinearDensity(rho, 0.0, 0.0, lambda);

    */

    // ================================================================================================================================================
    // ================================================================================================================================================
    // ================================================================================================================================================
    // ================================================================================================================================================
    // ================================================================================================================================================

    //cout << mesh->toString();

    //mesh->writeMeshAsText("out/Mesh.txt");

    mesh->iterate();

    //mesh->writeTimeSteps("out/timeSteps.dat");

    //mesh->writeVelocityU("out/VelocityU.dat");
    //mesh->writeVelocityV("out/VelocityV.dat");

    //ostringstream filename;
    //filename << "out/PoiseuillePresGradConvergenceStudy/" << ny;
    //mesh->writeVelocityProfile(    ( filename.str() + "/VelocityProfile.dat" )  , 0.5);
    //mesh->writeConvergenceHistory( ( filename.str() + "/ConvergenceHistory.dat" )    );
    //mesh->writeOverviewFile(       ( filename.str() + "/OverviewFile.dat" )          );

    ostringstream filename;
    filename << "out/DrivenCavity/Re" << Re << "/" << nx;
    //mesh->writeVelocityProfile(( filename.str() + "/VelocityProfile.dat" ), 0.5);
    mesh->writeVelocityU(          (filename.str() + "/VelocityU.dat"          ));
    mesh->writeVelocityV(          (filename.str() + "/VelocityV.dat"          ));
    mesh->writeConvergenceHistory(( filename.str() + "/ConvergenceHistory.dat" ));
    mesh->writeOverviewFile(      ( filename.str() + "/OverviewFile.dat" ));

    //mesh->writeConvergenceHistory("out/ConvergenceHistory.dat");
    //mesh->writeOverviewFile("out/OverviewFile.dat");

    //char a; cin >> a;
}<commit_msg>double method from merge deleted<commit_after>// ============================================================================
//
//                      Compressible Thermal GKS
//
// ============================================================================

#include "GKSMesh.h"
#include "BoundaryCondition.h"
#include <iostream>
#include <sstream>
#include <chrono>

using namespace std;

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

    // ========================================================================
    //
    //                  Couette-Flow (Periodic)
    //
    // ========================================================================

    Parameters param;

    double H = 1.0;
    double W = 0.25;

    param.numberOfIterations = 1000000;
    param.outputIntervalVTK = 1000000;
    param.outputInterval = 10000;

    param.convergenceCriterium = 1.0e-6;

    param.CFL = 0.5;

    param.verbose = false;

    // ========================================================================

    FluidParameter fluidParam;

    fluidParam.K = 1;
    fluidParam.nu = 1e-2;
    fluidParam.R = 200.0;
    fluidParam.Force.x = 1e-4;
    fluidParam.Force.y = 0.0;

    // ========================================================================

    GKSMesh* mesh = new GKSMesh(param, fluidParam);

    // Define Boundary Conditions
    //    -----------
    //    |    3    |
    //    | 0     2 |
    //    |    1    |
    //    -----------
    mesh->addBoundaryCondition(1, 1, 1, 1, 0.0, 0.00, 0.0, 0.0);
    mesh->addBoundaryCondition(1, 0, 0, 1, 0.0, 0.00, 0.0, 0.0);
    mesh->addBoundaryCondition(1, 1, 1, 1, 0.0, 0.00, 0.0, 0.0);
    mesh->addBoundaryCondition(1, 0, 0, 1, 0.0, 0.005, 0.0, 0.0);

    // Generate Mesh
    mesh->generateRectMesh(W, H, 2, 2);

    // Initialize Values
    mesh->initMeshConstant(1.0, 0.0, 0.0, 1.0);

    */

    ///*

    // ========================================================================
    //
    //                  Poiseuille-Flow (Force driven)
    //
    // ========================================================================

    Parameters param;

    double H = 1.0;
    double W = 0.1;

    param.numberOfIterations = 100000;
    param.outputInterval = 100;
    param.CFL = 0.5;

    param.verbose = false;

    // ========================================================================

    FluidParameter fluidParam;

    fluidParam.K  = 1;
    fluidParam.nu = 1e-2;
    fluidParam.R = 200.0;
    fluidParam.Force.x = 1e-4;
    fluidParam.Force.y = 0.0;

    // ========================================================================

    GKSMesh* mesh = new GKSMesh(param, fluidParam);

    // Define Boundary Conditions
    //    -----------
    //    |    1    |
    //    |         |
    //    |    0    |
    //    -----------
    mesh->addInterfaceBoundaryCondition(0.0);
    mesh->addInterfaceBoundaryCondition(0.0);

    // Generate Mesh
    mesh->generateRectMeshPeriodicInterfaceBCs(W, H, 1, 64);

    // Initialize Values
    mesh->initMeshConstant(1.0, 0.0, 0.0, 1.0);

    //*/

    // ========================================================================
    // ========================================================================
    // ========================================================================
    // ========================================================================
    // ========================================================================

    GKSMesh* mesh = new GKSMesh(param, fluidParam);

    // Define Boundary Conditions
    //    -----------
    //    |    3    |
    //    | 0     2 |
    //    |    1    |
    //    -----------
    mesh->addBoundaryCondition(1, 1, 1, 1, 0.0, 0.0, 0.0, 1.0);
    mesh->addBoundaryCondition(1, 0, 0, 1, 0.0, 0.0, 0.0, 1.0);
    mesh->addBoundaryCondition(1, 1, 1, 1, 0.0, 0.0, 0.0, 1.0);
    mesh->addBoundaryCondition(1, 0, 0, 1, 0.0, 0.0, 0.0, 1.0);

    // Generate Mesh
    mesh->generateRectMesh(W, H, 100, 100);

    // Initialize Values
    // mesh->initMeshConstant(1.0, 0.0, 0.0, 1.0);

    double rho[] = { 1.0, 1.0 + 1.0e-3 };

    mesh->initMeshLinearDensity(rho, 0.0, 0.0, lambda);

    */

    // ================================================================================================================================================
    // ================================================================================================================================================
    // ================================================================================================================================================
    // ================================================================================================================================================
    // ================================================================================================================================================

    //cout << mesh->toString();

    //mesh->writeMeshAsText("out/Mesh.txt");

    mesh->iterate();

    //mesh->writeTimeSteps("out/timeSteps.dat");

    //mesh->writeVelocityU("out/VelocityU.dat");
    //mesh->writeVelocityV("out/VelocityV.dat");

    //ostringstream filename;
    //filename << "out/PoiseuillePresGradConvergenceStudy/" << ny;
    //mesh->writeVelocityProfile(    ( filename.str() + "/VelocityProfile.dat" )  , 0.5);
    //mesh->writeConvergenceHistory( ( filename.str() + "/ConvergenceHistory.dat" )    );
    //mesh->writeOverviewFile(       ( filename.str() + "/OverviewFile.dat" )          );

    ostringstream filename;
    filename << "out/DrivenCavity/Re" << Re << "/" << nx;
    //mesh->writeVelocityProfile(( filename.str() + "/VelocityProfile.dat" ), 0.5);
    mesh->writeVelocityU(          (filename.str() + "/VelocityU.dat"          ));
    mesh->writeVelocityV(          (filename.str() + "/VelocityV.dat"          ));
    mesh->writeConvergenceHistory(( filename.str() + "/ConvergenceHistory.dat" ));
    mesh->writeOverviewFile(      ( filename.str() + "/OverviewFile.dat" ));

    //mesh->writeConvergenceHistory("out/ConvergenceHistory.dat");
    //mesh->writeOverviewFile("out/OverviewFile.dat");

    //char a; cin >> a;
}<|endoftext|>


<commit_before>// This file is part of the "x0" project, http://xzero.io/
//   (c) 2009-2014 Christian Parpart <trapni@gmail.com>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT

#include <xzero/http/http1/Connection.h>
#include <xzero/http/http1/Channel.h>
#include <xzero/http/HttpBufferedInput.h>
#include <xzero/http/HttpDateGenerator.h>
#include <xzero/http/HttpResponseInfo.h>
#include <xzero/http/HttpResponse.h>
#include <xzero/http/HttpRequest.h>
#include <xzero/http/BadMessage.h>
#include <xzero/net/Connection.h>
#include <xzero/net/EndPoint.h>
#include <xzero/net/EndPointWriter.h>
#include <xzero/executor/Executor.h>
#include <xzero/logging.h>
#include <xzero/RuntimeError.h>
#include <xzero/StringUtil.h>
#include <xzero/sysconfig.h>
#include <cassert>
#include <cstdlib>

namespace xzero {
namespace http {
namespace http1 {

#define ERROR(msg...) logError("http.http1.Connection", msg)

#ifndef NDEBUG
#define TRACE(msg...) logTrace("http.http1.Connection", msg)
#else
#define TRACE(msg...) do {} while (0)
#endif

Connection::Connection(EndPoint* endpoint,
                       Executor* executor,
                       const HttpHandler& handler,
                       HttpDateGenerator* dateGenerator,
                       HttpOutputCompressor* outputCompressor,
                       size_t maxRequestUriLength,
                       size_t maxRequestBodyLength,
                       size_t maxRequestCount,
                       Duration maxKeepAlive,
                       bool corkStream)
    : ::xzero::Connection(endpoint, executor),
      parser_(Parser::REQUEST),
      inputBuffer_(),
      inputOffset_(0),
      writer_(),
      onComplete_(),
      generator_(&writer_),
      channel_(new Channel(
          this, executor, handler,
          std::unique_ptr<HttpInput>(new HttpBufferedInput()),
          maxRequestUriLength, maxRequestBodyLength,
          dateGenerator, outputCompressor)),
      maxKeepAlive_(maxKeepAlive),
      requestCount_(0),
      requestMax_(maxRequestCount),
      corkStream_(corkStream) {

  channel_->request()->setRemoteIP(endpoint->remoteIP());

  parser_.setListener(channel_.get());
  TRACE("$0 ctor", this);
}

Connection::~Connection() {
  TRACE("$0 dtor", this);
}

void Connection::onOpen() {
  TRACE("$0 onOpen", this);
  ::xzero::Connection::onOpen();

  // TODO support TCP_DEFER_ACCEPT here
#if 0
  if (connector()->deferAccept())
    onFillable();
  else
    wantFill();
#else
  wantFill();
#endif
}

void Connection::onClose() {
  TRACE("$0 onClose", this);
  ::xzero::Connection::onClose();
}

void Connection::abort() {
  TRACE("$0 abort()", this);
  channel_->response()->setBytesTransmitted(generator_.bytesTransmitted());
  channel_->responseEnd();

  TRACE("$0 abort", this);
  endpoint()->close();
}

void Connection::completed() {
  TRACE("$0 completed", this);

  if (onComplete_)
    RAISE(IllegalStateError, "there is still another completion hook.");

  if (channel_->request()->method() != HttpMethod::HEAD &&
      !generator_.isChunked() &&
      generator_.pendingContentLength() > 0)
    RAISE(IllegalStateError, "Invalid State. Response not fully written but completed() invoked.");

  onComplete_ = std::bind(&Connection::onResponseComplete, this,
                          std::placeholders::_1);

  generator_.generateTrailer(channel_->response()->trailers());
  wantFlush();
}

void Connection::onResponseComplete(bool succeed) {
  TRACE("$0 onResponseComplete($1)", this, succeed ? "succeed" : "failure");
  channel_->response()->setBytesTransmitted(generator_.bytesTransmitted());
  channel_->responseEnd();

  if (!succeed) {
    // writing trailer failed. do not attempt to do anything on the wire.
    return;
  }

  if (channel_->isPersistent()) {
    TRACE("$0 completed.onComplete", this);

    // re-use on keep-alive
    channel_->reset();

    endpoint()->setCorking(false);

    if (inputOffset_ < inputBuffer_.size()) {
      // have some request pipelined
      TRACE("$0 completed.onComplete: pipelined read", this);
      executor()->execute(std::bind(&Connection::parseFragment, this));
    } else {
      // wait for next request
      TRACE("$0 completed.onComplete: keep-alive read", this);
      wantFill();
    }
  } else {
    endpoint()->close();
  }
}

void Connection::send(HttpResponseInfo&& responseInfo,
                          const BufferRef& chunk,
                          CompletionHandler onComplete) {
  if (onComplete && onComplete_)
    RAISE(IllegalStateError, "There is still another completion hook.");

  TRACE("$0 send(BufferRef, status=$1, persistent=$2, chunkSize=$2)",
        this, responseInfo.status(), channel_->isPersistent() ? "yes" : "no",
        chunk.size());

  patchResponseInfo(responseInfo);

  if (corkStream_)
    endpoint()->setCorking(true);

  generator_.generateResponse(responseInfo, chunk);
  onComplete_ = std::move(onComplete);
  wantFlush();
}

void Connection::send(HttpResponseInfo&& responseInfo,
                          Buffer&& chunk,
                          CompletionHandler onComplete) {
  if (onComplete && onComplete_)
    RAISE(IllegalStateError, "There is still another completion hook.");

  TRACE("$0 send(Buffer, status=$1, persistent=$2, chunkSize=$3)",
        this, responseInfo.status(), channel_->isPersistent() ? "yes" : "no",
        chunk.size());

  patchResponseInfo(responseInfo);

  const bool corking_ = true;  // TODO(TCP_CORK): part of HttpResponseInfo?
  if (corking_)
    endpoint()->setCorking(true);

  generator_.generateResponse(responseInfo, std::move(chunk));
  onComplete_ = std::move(onComplete);
  wantFlush();
}

void Connection::send(HttpResponseInfo&& responseInfo,
                          FileRef&& chunk,
                          CompletionHandler onComplete) {
  if (onComplete && onComplete_)
    RAISE(IllegalStateError, "There is still another completion hook.");

  TRACE("$0 send(FileRef, status=$1, persistent=$2, fileRef.fd=$3, chunkSize=$4)",
        this, responseInfo.status(), channel_->isPersistent() ? "yes" : "no",
        chunk.handle(), chunk.size());

  patchResponseInfo(responseInfo);

  const bool corking_ = true;  // TODO(TCP_CORK): part of HttpResponseInfo?
  if (corking_)
    endpoint()->setCorking(true);

  generator_.generateResponse(responseInfo, std::move(chunk));
  onComplete_ = std::move(onComplete);
  wantFlush();
}

void Connection::patchResponseInfo(HttpResponseInfo& responseInfo) {
  if (static_cast<int>(responseInfo.status()) >= 200) {
    // patch in HTTP transport-layer headers
    if (channel_->isPersistent() && requestCount_ < requestMax_) {
      ++requestCount_;

      char keepAlive[64];
      snprintf(keepAlive, sizeof(keepAlive), "timeout=%llu, max=%zu",
               (unsigned long long) maxKeepAlive_.seconds(),
               requestMax_ - requestCount_);

      responseInfo.headers().push_back("Connection", "Keep-Alive");
      responseInfo.headers().push_back("Keep-Alive", keepAlive);
    } else {
      channel_->setPersistent(false);
      responseInfo.headers().push_back("Connection", "closed");
    }
  }
}

void Connection::send(Buffer&& chunk, CompletionHandler onComplete) {
  if (onComplete && onComplete_)
    RAISE(IllegalStateError, "There is still another completion hook.");

  TRACE("$0 send(Buffer, chunkSize=$1)", this, chunk.size());

  generator_.generateBody(std::move(chunk));
  onComplete_ = std::move(onComplete);

  wantFlush();
}

void Connection::send(const BufferRef& chunk,
                          CompletionHandler onComplete) {
  if (onComplete && onComplete_)
    RAISE(IllegalStateError, "There is still another completion hook.");

  TRACE("$0 send(BufferRef, chunkSize=$1)", this, chunk.size());

  generator_.generateBody(chunk);
  onComplete_ = std::move(onComplete);

  wantFlush();
}

void Connection::send(FileRef&& chunk, CompletionHandler onComplete) {
  if (onComplete && onComplete_)
    RAISE(IllegalStateError, "There is still another completion hook.");

  TRACE("$0 send(FileRef, chunkSize=$1)", this, chunk.size());

  generator_.generateBody(std::move(chunk));
  onComplete_ = std::move(onComplete);
  wantFlush();
}

void Connection::setInputBufferSize(size_t size) {
  TRACE("$0 setInputBufferSize($1)", this, size);
  inputBuffer_.reserve(size);
}

void Connection::onFillable() {
  TRACE("$0 onFillable", this);

  TRACE("$0 onFillable: calling fill()", this);
  if (endpoint()->fill(&inputBuffer_) == 0) {
    TRACE("$0 onFillable: fill() returned 0", this);
    // RAISE("client EOF");
    abort();
    return;
  }

  parseFragment();
}

void Connection::parseFragment() {
  try {
    TRACE("parseFragment: calling parseFragment ($0 into $1)",
          inputOffset_, inputBuffer_.size());
    size_t n = parser_.parseFragment(inputBuffer_.ref(inputOffset_));
    TRACE("parseFragment: called ($0 into $1) => $2 ($3)",
          inputOffset_, inputBuffer_.size(), n,
          parser_.state());
    inputOffset_ += n;
  } catch (const BadMessage& e) {
    TRACE("$0 parseFragment: BadMessage caught (while in state $1). $2",
          this, to_string(channel_->state()), e.what());

    if (channel_->response()->version() == HttpVersion::UNKNOWN)
      channel_->response()->setVersion(HttpVersion::VERSION_0_9);

    if (channel_->state() == HttpChannelState::READING)
      channel_->setState(HttpChannelState::HANDLING);

    channel_->response()->sendError(e.httpCode(), e.what());
  }
}

void Connection::onFlushable() {
  TRACE("$0 onFlushable", this);

  if (channel_->state() != HttpChannelState::SENDING)
    channel_->setState(HttpChannelState::SENDING);

  const bool complete = writer_.flush(endpoint());

  if (complete) {
    TRACE("$0 onFlushable: completed. ($1)",
          this,
          (onComplete_ ? "onComplete cb set" : "onComplete cb not set"));
    channel_->setState(HttpChannelState::HANDLING);

    if (onComplete_) {
      TRACE("$0 onFlushable: invoking completion callback", this);
      auto callback = std::move(onComplete_);
      onComplete_ = nullptr;
      callback(true);
    }
  } else {
    // continue flushing as we still have data pending
    wantFlush();
  }
}

void Connection::onInterestFailure(const std::exception& error) {
  TRACE("$0 onInterestFailure($1): $2",
        this, typeid(error).name(), error.what());

  // TODO: improve logging here, as this eats our exception here.
  // e.g. via (factory or connector)->error(error);
  logError("Connection", error, "Unhandled exception caught in I/O loop");

  auto callback = std::move(onComplete_);
  onComplete_ = nullptr;

  // notify the callback that we failed doing something wrt. I/O.
  if (callback) {
    TRACE("$0 onInterestFailure: invoking onComplete(false)", this);
    callback(false);
  }

  abort();
}

}  // namespace http1
}  // namespace http

template <>
std::string StringUtil::toString(http::http1::Connection* c) {
  auto remote = c->endpoint()->remoteAddress();
  if (remote.isEmpty())
    return "<EOF>";
  else
    return StringUtil::format("$0:$1", remote->first, remote->second);
}

}  // namespace xzero
<commit_msg>http1::Connection: fix on partial reads<commit_after>// This file is part of the "x0" project, http://xzero.io/
//   (c) 2009-2014 Christian Parpart <trapni@gmail.com>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT

#include <xzero/http/http1/Connection.h>
#include <xzero/http/http1/Channel.h>
#include <xzero/http/HttpBufferedInput.h>
#include <xzero/http/HttpDateGenerator.h>
#include <xzero/http/HttpResponseInfo.h>
#include <xzero/http/HttpResponse.h>
#include <xzero/http/HttpRequest.h>
#include <xzero/http/BadMessage.h>
#include <xzero/net/Connection.h>
#include <xzero/net/EndPoint.h>
#include <xzero/net/EndPointWriter.h>
#include <xzero/executor/Executor.h>
#include <xzero/logging.h>
#include <xzero/RuntimeError.h>
#include <xzero/StringUtil.h>
#include <xzero/sysconfig.h>
#include <cassert>
#include <cstdlib>

namespace xzero {
namespace http {
namespace http1 {

#define ERROR(msg...) logError("http.http1.Connection", msg)

#ifndef NDEBUG
#define TRACE(msg...) logTrace("http.http1.Connection", msg)
#else
#define TRACE(msg...) do {} while (0)
#endif

Connection::Connection(EndPoint* endpoint,
                       Executor* executor,
                       const HttpHandler& handler,
                       HttpDateGenerator* dateGenerator,
                       HttpOutputCompressor* outputCompressor,
                       size_t maxRequestUriLength,
                       size_t maxRequestBodyLength,
                       size_t maxRequestCount,
                       Duration maxKeepAlive,
                       bool corkStream)
    : ::xzero::Connection(endpoint, executor),
      parser_(Parser::REQUEST),
      inputBuffer_(),
      inputOffset_(0),
      writer_(),
      onComplete_(),
      generator_(&writer_),
      channel_(new Channel(
          this, executor, handler,
          std::unique_ptr<HttpInput>(new HttpBufferedInput()),
          maxRequestUriLength, maxRequestBodyLength,
          dateGenerator, outputCompressor)),
      maxKeepAlive_(maxKeepAlive),
      requestCount_(0),
      requestMax_(maxRequestCount),
      corkStream_(corkStream) {

  channel_->request()->setRemoteIP(endpoint->remoteIP());

  parser_.setListener(channel_.get());
  TRACE("$0 ctor", this);
}

Connection::~Connection() {
  TRACE("$0 dtor", this);
}

void Connection::onOpen() {
  TRACE("$0 onOpen", this);
  ::xzero::Connection::onOpen();

  // TODO support TCP_DEFER_ACCEPT here
#if 0
  if (connector()->deferAccept())
    onFillable();
  else
    wantFill();
#else
  wantFill();
#endif
}

void Connection::onClose() {
  TRACE("$0 onClose", this);
  ::xzero::Connection::onClose();
}

void Connection::abort() {
  TRACE("$0 abort()", this);
  channel_->response()->setBytesTransmitted(generator_.bytesTransmitted());
  channel_->responseEnd();

  TRACE("$0 abort", this);
  endpoint()->close();
}

void Connection::completed() {
  TRACE("$0 completed", this);

  if (onComplete_)
    RAISE(IllegalStateError, "there is still another completion hook.");

  if (channel_->request()->method() != HttpMethod::HEAD &&
      !generator_.isChunked() &&
      generator_.pendingContentLength() > 0)
    RAISE(IllegalStateError, "Invalid State. Response not fully written but completed() invoked.");

  onComplete_ = std::bind(&Connection::onResponseComplete, this,
                          std::placeholders::_1);

  generator_.generateTrailer(channel_->response()->trailers());
  wantFlush();
}

void Connection::onResponseComplete(bool succeed) {
  TRACE("$0 onResponseComplete($1)", this, succeed ? "succeed" : "failure");
  channel_->response()->setBytesTransmitted(generator_.bytesTransmitted());
  channel_->responseEnd();

  if (!succeed) {
    // writing trailer failed. do not attempt to do anything on the wire.
    return;
  }

  if (channel_->isPersistent()) {
    TRACE("$0 completed.onComplete", this);

    // re-use on keep-alive
    channel_->reset();

    endpoint()->setCorking(false);

    if (inputOffset_ < inputBuffer_.size()) {
      // have some request pipelined
      TRACE("$0 completed.onComplete: pipelined read", this);
      executor()->execute(std::bind(&Connection::parseFragment, this));
    } else {
      // wait for next request
      TRACE("$0 completed.onComplete: keep-alive read", this);
      wantFill();
    }
  } else {
    endpoint()->close();
  }
}

void Connection::send(HttpResponseInfo&& responseInfo,
                          const BufferRef& chunk,
                          CompletionHandler onComplete) {
  if (onComplete && onComplete_)
    RAISE(IllegalStateError, "There is still another completion hook.");

  TRACE("$0 send(BufferRef, status=$1, persistent=$2, chunkSize=$2)",
        this, responseInfo.status(), channel_->isPersistent() ? "yes" : "no",
        chunk.size());

  patchResponseInfo(responseInfo);

  if (corkStream_)
    endpoint()->setCorking(true);

  generator_.generateResponse(responseInfo, chunk);
  onComplete_ = std::move(onComplete);
  wantFlush();
}

void Connection::send(HttpResponseInfo&& responseInfo,
                          Buffer&& chunk,
                          CompletionHandler onComplete) {
  if (onComplete && onComplete_)
    RAISE(IllegalStateError, "There is still another completion hook.");

  TRACE("$0 send(Buffer, status=$1, persistent=$2, chunkSize=$3)",
        this, responseInfo.status(), channel_->isPersistent() ? "yes" : "no",
        chunk.size());

  patchResponseInfo(responseInfo);

  const bool corking_ = true;  // TODO(TCP_CORK): part of HttpResponseInfo?
  if (corking_)
    endpoint()->setCorking(true);

  generator_.generateResponse(responseInfo, std::move(chunk));
  onComplete_ = std::move(onComplete);
  wantFlush();
}

void Connection::send(HttpResponseInfo&& responseInfo,
                          FileRef&& chunk,
                          CompletionHandler onComplete) {
  if (onComplete && onComplete_)
    RAISE(IllegalStateError, "There is still another completion hook.");

  TRACE("$0 send(FileRef, status=$1, persistent=$2, fileRef.fd=$3, chunkSize=$4)",
        this, responseInfo.status(), channel_->isPersistent() ? "yes" : "no",
        chunk.handle(), chunk.size());

  patchResponseInfo(responseInfo);

  const bool corking_ = true;  // TODO(TCP_CORK): part of HttpResponseInfo?
  if (corking_)
    endpoint()->setCorking(true);

  generator_.generateResponse(responseInfo, std::move(chunk));
  onComplete_ = std::move(onComplete);
  wantFlush();
}

void Connection::patchResponseInfo(HttpResponseInfo& responseInfo) {
  if (static_cast<int>(responseInfo.status()) >= 200) {
    // patch in HTTP transport-layer headers
    if (channel_->isPersistent() && requestCount_ < requestMax_) {
      ++requestCount_;

      char keepAlive[64];
      snprintf(keepAlive, sizeof(keepAlive), "timeout=%llu, max=%zu",
               (unsigned long long) maxKeepAlive_.seconds(),
               requestMax_ - requestCount_);

      responseInfo.headers().push_back("Connection", "Keep-Alive");
      responseInfo.headers().push_back("Keep-Alive", keepAlive);
    } else {
      channel_->setPersistent(false);
      responseInfo.headers().push_back("Connection", "closed");
    }
  }
}

void Connection::send(Buffer&& chunk, CompletionHandler onComplete) {
  if (onComplete && onComplete_)
    RAISE(IllegalStateError, "There is still another completion hook.");

  TRACE("$0 send(Buffer, chunkSize=$1)", this, chunk.size());

  generator_.generateBody(std::move(chunk));
  onComplete_ = std::move(onComplete);

  wantFlush();
}

void Connection::send(const BufferRef& chunk,
                          CompletionHandler onComplete) {
  if (onComplete && onComplete_)
    RAISE(IllegalStateError, "There is still another completion hook.");

  TRACE("$0 send(BufferRef, chunkSize=$1)", this, chunk.size());

  generator_.generateBody(chunk);
  onComplete_ = std::move(onComplete);

  wantFlush();
}

void Connection::send(FileRef&& chunk, CompletionHandler onComplete) {
  if (onComplete && onComplete_)
    RAISE(IllegalStateError, "There is still another completion hook.");

  TRACE("$0 send(FileRef, chunkSize=$1)", this, chunk.size());

  generator_.generateBody(std::move(chunk));
  onComplete_ = std::move(onComplete);
  wantFlush();
}

void Connection::setInputBufferSize(size_t size) {
  TRACE("$0 setInputBufferSize($1)", this, size);
  inputBuffer_.reserve(size);
}

void Connection::onFillable() {
  TRACE("$0 onFillable", this);

  TRACE("$0 onFillable: calling fill()", this);
  if (endpoint()->fill(&inputBuffer_) == 0) {
    TRACE("$0 onFillable: fill() returned 0", this);
    // RAISE("client EOF");
    abort();
    return;
  }

  parseFragment();
}

void Connection::parseFragment() {
  try {
    TRACE("parseFragment: calling parseFragment ($0 into $1)",
          inputOffset_, inputBuffer_.size());
    size_t n = parser_.parseFragment(inputBuffer_.ref(inputOffset_));
    TRACE("parseFragment: called ($0 into $1) => $2 ($3)",
          inputOffset_, inputBuffer_.size(), n,
          parser_.state());
    inputOffset_ += n;

    // on a partial read we must make sure that we wait for more input
    if (parser_.state() != Parser::MESSAGE_BEGIN) {
      wantFill();
    }
  } catch (const BadMessage& e) {
    TRACE("$0 parseFragment: BadMessage caught (while in state $1). $2",
          this, to_string(channel_->state()), e.what());

    if (channel_->response()->version() == HttpVersion::UNKNOWN)
      channel_->response()->setVersion(HttpVersion::VERSION_0_9);

    if (channel_->state() == HttpChannelState::READING)
      channel_->setState(HttpChannelState::HANDLING);

    channel_->response()->sendError(e.httpCode(), e.what());
  }
}

void Connection::onFlushable() {
  TRACE("$0 onFlushable", this);

  if (channel_->state() != HttpChannelState::SENDING)
    channel_->setState(HttpChannelState::SENDING);

  const bool complete = writer_.flush(endpoint());

  if (complete) {
    TRACE("$0 onFlushable: completed. ($1)",
          this,
          (onComplete_ ? "onComplete cb set" : "onComplete cb not set"));
    channel_->setState(HttpChannelState::HANDLING);

    if (onComplete_) {
      TRACE("$0 onFlushable: invoking completion callback", this);
      auto callback = std::move(onComplete_);
      onComplete_ = nullptr;
      callback(true);
    }
  } else {
    // continue flushing as we still have data pending
    wantFlush();
  }
}

void Connection::onInterestFailure(const std::exception& error) {
  TRACE("$0 onInterestFailure($1): $2",
        this, typeid(error).name(), error.what());

  // TODO: improve logging here, as this eats our exception here.
  // e.g. via (factory or connector)->error(error);
  logError("Connection", error, "Unhandled exception caught in I/O loop");

  auto callback = std::move(onComplete_);
  onComplete_ = nullptr;

  // notify the callback that we failed doing something wrt. I/O.
  if (callback) {
    TRACE("$0 onInterestFailure: invoking onComplete(false)", this);
    callback(false);
  }

  abort();
}

}  // namespace http1
}  // namespace http

template <>
std::string StringUtil::toString(http::http1::Connection* c) {
  auto remote = c->endpoint()->remoteAddress();
  if (remote.isEmpty())
    return "<EOF>";
  else
    return StringUtil::format("$0:$1", remote->first, remote->second);
}

}  // namespace xzero
<|endoftext|>


<commit_before><commit_msg>startup: move sandbox initialization together<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2017 Franka Emika GmbH
// Use of this source code is governed by the Apache-2.0 license, see LICENSE
#include <iostream>
#include <sstream>
#include <string>
#include <thread>

#include <franka/exception.h>
#include <franka/gripper.h>

/**
 * @example grasp_object.cpp
 * An example showing how to control FRANKA's gripper.
 */

int main(int argc, char** argv) {
  if (argc != 4) {
    std::cerr << "Usage: ./grasp_object <gripper-hostname> <homing> <object-width>" << std::endl;
    return -1;
  }

  try {
    franka::Gripper gripper(argv[1]);
    double grasping_width = std::stod(argv[3]);

    std::stringstream ss(argv[2]);
    bool homing;
    if (!(ss >> homing)) {
      std::cerr << "<homing> can be 0 or 1." << std::endl;
      return -1;
    }

    if (homing) {
      // Do a homing in order to estimate the maximum grasping width with the current fingers.
      gripper.homing();
    }

    // Check for the maximum grasping width.
    franka::GripperState gripper_state = gripper.readOnce();
    if (gripper_state.max_width < grasping_width) {
      std::cout << "Object is too large for the current fingers on the gripper." << std::endl;
      return -1;
    }

    // Grasp the object.
    if (!gripper.grasp(grasping_width, 0.1, 300)) {
      std::cout << "Failed to grasp object." << std::endl;
      return -1;
    }

    // Wait 3s and check afterwards, if the object is still grasped.
    std::this_thread::sleep_for(std::chrono::duration<double, std::milli>(3000));

    gripper_state = gripper.readOnce();
    if (!gripper_state.is_grasped) {
      std::cout << "Object lost." << std::endl;
      return -1;
    }

    std::cout << "Grasped object, will release it now." << std::endl;
    gripper.stop();
  } catch (franka::Exception const& e) {
    std::cout << e.what() << std::endl;
    return -1;
  }

  return 0;
}
<commit_msg>Update gripper example.<commit_after>// Copyright (c) 2017 Franka Emika GmbH
// Use of this source code is governed by the Apache-2.0 license, see LICENSE
#include <iostream>
#include <sstream>
#include <string>
#include <thread>

#include <franka/exception.h>
#include <franka/gripper.h>

/**
 * @example grasp_object.cpp
 * An example showing how to control FRANKA's gripper.
 */

int main(int argc, char** argv) {
  if (argc != 4) {
    std::cerr << "Usage: ./grasp_object <gripper-hostname> <homing> <object-width>" << std::endl;
    return -1;
  }

  try {
    franka::Gripper gripper(argv[1]);
    double grasping_width = std::stod(argv[3]);

    std::stringstream ss(argv[2]);
    bool homing;
    if (!(ss >> homing)) {
      std::cerr << "<homing> can be 0 or 1." << std::endl;
      return -1;
    }

    if (homing) {
      // Do a homing in order to estimate the maximum grasping width with the current fingers.
      gripper.homing();
    }

    // Check for the maximum grasping width.
    franka::GripperState gripper_state = gripper.readOnce();
    if (gripper_state.max_width < grasping_width) {
      std::cout << "Object is too large for the current fingers on the gripper." << std::endl;
      return -1;
    }

    // Grasp the object.
    if (!gripper.grasp(grasping_width, 0.1, 60)) {
      std::cout << "Failed to grasp object." << std::endl;
      return -1;
    }

    // Wait 3s and check afterwards, if the object is still grasped.
    std::this_thread::sleep_for(std::chrono::duration<double, std::milli>(3000));

    gripper_state = gripper.readOnce();
    if (!gripper_state.is_grasped) {
      std::cout << "Object lost." << std::endl;
      return -1;
    }

    std::cout << "Grasped object, will release it now." << std::endl;
    gripper.stop();
  } catch (franka::Exception const& e) {
    std::cout << e.what() << std::endl;
    return -1;
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <functional>
#include <initializer_list>
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>

#include <iostream>

#include <memory>

namespace parser{

 	class Sign_{
        std::string name_;
        bool isTerm_;
      public:
        Sign_(std::string n, bool t){
            name_ = n;
            isTerm_ = t;
        }
		Sign_(std::string n){
			name_ = n;
		    isTerm_ = true;
		}
		Sign_(){
			name_ ="";
			isTerm_ = true;
		}
        bool isTerm(){
            return isTerm_;
        }
        std::string name(){
            return name_;
        }
		operator std::string() const{
    		return name_;
		}
	};

	using Sign = std::shared_ptr<Sign_>;

	class Item{
	  public:
        Sign left;
        std::vector<Sign> rights;
        int pos;
        Item(Sign l, std::initializer_list<Sign> const & r){
			pos = 0;
            left = l;
            rights.insert(rights.end(),r.begin(), r.end());
        }
        Sign nextSign(){
        	return rights[pos];
        }
        void next(){
			if(rights.size() > pos+1)
            	pos++;
        }
		bool isLast(){
			return pos == rights.size()-1;
		}
		friend std::ostream& operator<<(std::ostream &out, const Item &i){
			out << std::string(*i.left) <<" => ";
			if(i.pos == 0){
				out<< " . ";
			}
			for(int j=0;j<i.rights.size();j++){
				out << std::string(*i.rights[j]);
				if(i.pos == j+1){
					out<< " . ";
				}else{
					out<<"   ";
				}
			}
			out << "\n";
			return out;
		}
	};

	Sign mS(std::string name){
		return Sign(new Sign_(name,false));
	}
	Sign mtS(std::string name){
		return Sign(new Sign_(name));
	}

    auto  E = mS("E");
    auto Eq = mS("Eq");
    auto  T = mS("T");
    auto Tq = mS("Tq");
    auto  F = mS("F");

	auto Eps = mtS("Epsilon");
	auto Fin = mtS("Fin");

	std::vector<Item> rules;

	std::vector<Item> getItems(Sign s){
		//std::cout << std::string(*s) << std::endl;
		std::vector<Item> res;
		for(auto& i : rules){
			if(i.left->name() == s->name()){
				res.push_back(i);
			}
		}
		return res;
	}

    std::vector<Sign> first(Sign sign){
        if(sign->isTerm()){
            return {sign};
        }
        std::vector<Sign> res;
		auto items = getItems( sign );
		if(items.size() == 0)
			return res;

        for(auto& i : items){
			//std::cout << std::string( *i.left ) << " " << i.rights.size()  <<std::endl;
        	auto ext = first(i.rights[0]);
            if(find(ext.begin(), ext.end(), Eps) != ext.end()){
				//std::cout <<"Eps!\n";
            	ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end());
               	res.insert(res.end(), ext.begin(), ext.end());
                    if(i.rights.size() >= 2){
                        auto nxt = first(i.rights[1]);
                        res.insert(res.end(), nxt.begin(), nxt.end());
                    }else{
                        res.push_back( Eps);
                    }
            }else{
            	res.insert(res.end(), ext.begin(), ext.end());
			}
		}
        return res;
    }
/*
    std::vector<Sing> first(initializer_list<Sign>& l){
        if(l.size() == 0)
            return {Sign("Epsilon")};

        std::vector<Rule> res;

        auto it = l.begin();
        if(*it == Sign("Epsilon")) return {Sign("Epsilon")};
        if((*it)->isTerm()) return {*it};

        auto ext = first(*it);
        if(find(ext.begin(), ext.end(), Sign("Epsilon")) != ext.end()){
            ext.erase(remove(ext.begin(), ext.end(), Sign("Epsilon")), ext.end());
            res.insert(res.end(), ext.begin(), ext.end());
            if(l.size() >= 2 ){
                it++;
                auto next = first(*it);
                res.insert(res.end(), next.begin(), next.end());
            }
            return res;
        }else{
            return ext;
        }
    }
*/
    std::vector<Sign> follow(Sign& s){
		std::cout<< std::string(*s) << std::endl;
        std::vector<Sign> res;

        if(s == E){
            res.push_back(Fin);
        }

        for(auto rit = rules.cbegin(); rit != rules.cend(); ++rit){
            auto ls = rit->left;
            if(ls == s) continue;

			auto rs = rit->rights;
            for(size_t i = 1; i < rs.size(); i++){
            	if(rs[i] == s){
                	if(i + 1 < rs.size()){
                    	auto ext = first(rs[i+1]);
                        if(find(ext.begin(), ext.end(), Eps) != ext.end()){
               	        	auto left = follow(ls);
                            res.insert(res.end(), left.begin(), left.end());
                        }
                        ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end());
                       	res.insert(res.end(), ext.begin(), ext.end());
                    }else{
                        auto left = follow(ls);
                        res.insert(res.end(), left.begin(), left.end());
                    }
                }
            }
        }
        return res;
    }

	void closure(std::vector<Item>& I){
		int size = I.size();
		std::vector<Sign> alreadys;
		do{
			size = I.size();
			std::cout<<"LOOP\n";
			for(auto i : I){
				//std::cout<< i << std::endl;
				auto X = getItems( i.nextSign() );

				std::cout<< "SIZE:"<<X.size()<<std::endl;
				//std::cout<<"item \n";
				for(auto x : X){
					std::cout<< "#######\n" << x <<"\n";
					//if(find(alreadys.begin(), alreadys.end(), x.left) != alreadys.end()){
						//std::cout<<":CON\n";
					//		continue;
					//}
					//std::cout<<"loop\n";
					//x.next();
					//std::cout<<"push X\n";
					I.push_back(x);
					//alreadys.push_back(x.left);
				}
			}
			std::cout<< size <<" "<<I.size() << "\n";
		}while( size != I.size() );
	}

	std::vector<Item> Goto(std::vector<Item> I,Sign X){
		std::vector<Item> J;
		/*
		std::cout << "Goto argv b--------\n";
		for(auto i : I) std::cout<< i;
		std::cout<< std::string(*X)<<std::endl;;
		std::cout << "Goto argv e--------\n";
		// */
		for(auto i : I){
			if(i.nextSign() == X && !i.isLast()){
				//std::cout<<"1^^^^\n";
				i.next();
				//std::cout<< i;
            	J.push_back(i);
				//std::cout<<"2^^^^\n";
			}
		}
		closure(J);
		return J;
	}

	void DFA(){
		std::cout<<"Start\n";
		std::vector<std::vector<Item>> T;
		std::vector<std::vector<Item>> Tt;
		std::vector<Item> f({ Item( mS("S"),{ E, Fin}) });
		closure(f);
		T.push_back(f);
		int size = T.size();
		int count = 0;
		std::cout<< f[0];
		std::cout<<"++++++++++++++++\n";
		Tt = T;
		std::vector<Sign> alreadys;
		while( count < 5){
			count++;
			for(auto t : T){
				for(auto i : t){
					std::cout<< "i loop start\n"<< i;
					if(find(alreadys.begin(), alreadys.end(), i.nextSign()) != alreadys.end())
						continue;
					alreadys.push_back(i.nextSign());
					auto J = Goto( t, i.nextSign());
					std::cout << "***************************\n";
					std::cout << "I:"<< std::string(*i.nextSign()) << std::endl;
					for(auto j : J)
						std::cout << j;
					std::cout << "***************************\n";
					T.push_back(J);
					std::cout<<"i loop end\n";
				}
				std::cout<<"t loop end\n";
			}
			std::cout<< size << " " << T.size() << std::endl;
			if( size != T.size()){
				size = T.size();
			}else{
				break;
			}
		}
		std::cout<<"####################\n";
		for(auto t : T){
			std::cout<<"~~~~~~~~~~~~~~~\n";
			for(auto i : t){
				std::cout<< i;
			}
		}
	}
	void setup(){

        rules.push_back(Item( E,
            { T, Eq }
        ));

        rules.push_back(Item( Eq,
            {mtS("+"), T,  Eq }
        ));
        rules.push_back(Item( Eq,
            { Eps }
        ));

		rules.push_back(Item( T,
            { F, Tq}
        ));

		rules.push_back(Item( Tq,
            { mtS("*"), F, Tq }
        ));
        rules.push_back(Item( Tq,
            { Eps }
        ));

        rules.push_back(Item( F,
            { mtS("("), E, mtS(")")}
        ));
        rules.push_back(Item( F,
            { mtS("i")}
		));
    }

	using namespace std;

    void test(Sign S){
        std::cout << "==== "<<std::string(*S)<< " ===\n";
        for(auto& s: first(S)){
            std::cout << std::string(*s) << std::endl;
        }
        std::cout<<"===\n";
        for(auto& r: follow(S)){
            std::cout << std::string(*r) << std::endl;
        }
	}

    void parser(){
        setup();
        /*
		test(E);

        test(Eq);

        test(T);

        test(Tq);

        test(F);

        std::cout<<"===\n";
		std::vector<Item> items = { Item( mS("S"), { E, Fin}) };
        closure(items);
		std::cout<<"~~~~~~~~~~~~~~~\n";
        for(auto i : items)
			std::cout << i;
		*/
		DFA();

        //delete items;

        //create_dfa();
        //for(auto rit = rule_table.begin(); rit != rule_table.end(); ++rit){
        //    if(rit->second)
        //        rit->second.reset();
        //}
    }
}

int main(){
    parser::parser();
    return 0;
}
/*
 * ==== T ===
 * (
 * i
 * ===
 * FIN
 * )
 * +
 * ==== Tq ===
 * *
 * Epsilon
 * ===
 * FIN
 * )
 * +
 * ==== F ===
 * (
 * i
 * ===
 * FIN
 * )
 * +
 * *
 * ===
 */

<commit_msg>[Fix] first(initializer_list).<commit_after>#include <functional>
#include <initializer_list>
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>

#include <iostream>

#include <memory>

namespace parser{

 	class Sign_{
        std::string name_;
        bool isTerm_;
      public:
        Sign_(std::string n, bool t){
            name_ = n;
            isTerm_ = t;
        }
		Sign_(std::string n){
			name_ = n;
		    isTerm_ = true;
		}
		Sign_(){
			name_ ="";
			isTerm_ = true;
		}
        bool isTerm(){
            return isTerm_;
        }
        std::string name(){
            return name_;
        }
		operator std::string() const{
    		return name_;
		}
	};

	using Sign = std::shared_ptr<Sign_>;

	class Item{
	  public:
        Sign left;
        std::vector<Sign> rights;
        int pos;
        Item(Sign l, std::initializer_list<Sign> const & r){
			pos = 0;
            left = l;
            rights.insert(rights.end(),r.begin(), r.end());
        }
        Sign nextSign(){
        	return rights[pos];
        }
        void next(){
			if(rights.size() > pos+1)
            	pos++;
        }
		bool isLast(){
			return pos == rights.size()-1;
		}
		friend std::ostream& operator<<(std::ostream &out, const Item &i){
			out << std::string(*i.left) <<" => ";
			if(i.pos == 0){
				out<< " . ";
			}
			for(int j=0;j<i.rights.size();j++){
				out << std::string(*i.rights[j]);
				if(i.pos == j+1){
					out<< " . ";
				}else{
					out<<"   ";
				}
			}
			out << "\n";
			return out;
		}
	};

	Sign mS(std::string name){
		return Sign(new Sign_(name,false));
	}
	Sign mtS(std::string name){
		return Sign(new Sign_(name));
	}

    auto  E = mS("E");
    auto Eq = mS("Eq");
    auto  T = mS("T");
    auto Tq = mS("Tq");
    auto  F = mS("F");

	auto Eps = mtS("Epsilon");
	auto Fin = mtS("Fin");

	std::vector<Item> rules;

	std::vector<Item> getItems(Sign s){
		//std::cout << std::string(*s) << std::endl;
		std::vector<Item> res;
		for(auto& i : rules){
			if(i.left->name() == s->name()){
				res.push_back(i);
			}
		}
		return res;
	}

    std::vector<Sign> first(Sign sign){
        if(sign->isTerm()){
            return {sign};
        }
        std::vector<Sign> res;
		auto items = getItems( sign );
		if(items.size() == 0)
			return res;

        for(auto& i : items){
			//std::cout << std::string( *i.left ) << " " << i.rights.size()  <<std::endl;
        	auto ext = first(i.rights[0]);
            if(find(ext.begin(), ext.end(), Eps) != ext.end()){
				//std::cout <<"Eps!\n";
            	ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end());
               	res.insert(res.end(), ext.begin(), ext.end());
                    if(i.rights.size() >= 2){
                        auto nxt = first(i.rights[1]);
                        res.insert(res.end(), nxt.begin(), nxt.end());
                    }else{
                        res.push_back( Eps);
                    }
            }else{
            	res.insert(res.end(), ext.begin(), ext.end());
			}
		}
        return res;
    }

    std::vector<Sign> first(std::initializer_list<Sign>& l){
        if(l.size() == 0)
            return {Eps};

        std::vector<Sign> res;

        auto it = l.begin();
        if(*it == Eps) return {Eps};
        if((*it)->isTerm()) return {*it};

        auto ext = first(*it);
        if(find(ext.begin(), ext.end(), Eps) != ext.end()){
            ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end());
            res.insert(res.end(), ext.begin(), ext.end());
            if(l.size() >= 2 ){
                it++;
                auto next = first(*it);
                res.insert(res.end(), next.begin(), next.end());
            }else{
				res.push_back(Eps);
			}
        }
        return ext;
    }

    std::vector<Sign> follow(Sign& s){
		std::cout<< std::string(*s) << std::endl;
        std::vector<Sign> res;

        if(s == E){
            res.push_back(Fin);
        }

        for(auto rit = rules.cbegin(); rit != rules.cend(); ++rit){
            auto ls = rit->left;
            if(ls == s) continue;

			auto rs = rit->rights;
            for(size_t i = 1; i < rs.size(); i++){
            	if(rs[i] == s){
                	if(i + 1 < rs.size()){
                    	auto ext = first(rs[i+1]);
                        if(find(ext.begin(), ext.end(), Eps) != ext.end()){
               	        	auto left = follow(ls);
                            res.insert(res.end(), left.begin(), left.end());
                        }
                        ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end());
                       	res.insert(res.end(), ext.begin(), ext.end());
                    }else{
                        auto left = follow(ls);
                        res.insert(res.end(), left.begin(), left.end());
                    }
                }
            }
        }
        return res;
    }

	void closure(std::vector<Item>& I){
		int size = I.size();
		std::vector<Sign> alreadys;
		do{
			size = I.size();
			std::cout<<"LOOP\n";
			for(auto i : I){
				//std::cout<< i << std::endl;
				auto X = getItems( i.nextSign() );

				std::cout<< "SIZE:"<<X.size()<<std::endl;
				//std::cout<<"item \n";
				for(auto x : X){
					std::cout<< "#######\n" << x <<"\n";
					//if(find(alreadys.begin(), alreadys.end(), x.left) != alreadys.end()){
						//std::cout<<":CON\n";
					//		continue;
					//}
					//std::cout<<"loop\n";
					//x.next();
					//std::cout<<"push X\n";
					I.push_back(x);
					//alreadys.push_back(x.left);
				}
			}
			std::cout<< size <<" "<<I.size() << "\n";
		}while( size != I.size() );
	}

	std::vector<Item> Goto(std::vector<Item> I,Sign X){
		std::vector<Item> J;
		/*
		std::cout << "Goto argv b--------\n";
		for(auto i : I) std::cout<< i;
		std::cout<< std::string(*X)<<std::endl;;
		std::cout << "Goto argv e--------\n";
		// */
		for(auto i : I){
			if(i.nextSign() == X && !i.isLast()){
				//std::cout<<"1^^^^\n";
				i.next();
				//std::cout<< i;
            	J.push_back(i);
				//std::cout<<"2^^^^\n";
			}
		}
		closure(J);
		return J;
	}

	void DFA(){
		std::cout<<"Start\n";
		std::vector<std::vector<Item>> T;
		std::vector<std::vector<Item>> Tt;
		std::vector<Item> f({ Item( mS("S"),{ E, Fin}) });
		closure(f);
		T.push_back(f);
		int size = T.size();
		int count = 0;
		std::cout<< f[0];
		std::cout<<"++++++++++++++++\n";
		Tt = T;
		std::vector<Sign> alreadys;
		while( count < 5){
			count++;
			for(auto t : T){
				for(auto i : t){
					std::cout<< "i loop start\n"<< i;
					if(find(alreadys.begin(), alreadys.end(), i.nextSign()) != alreadys.end())
						continue;
					alreadys.push_back(i.nextSign());
					auto J = Goto( t, i.nextSign());
					std::cout << "***************************\n";
					std::cout << "I:"<< std::string(*i.nextSign()) << std::endl;
					for(auto j : J)
						std::cout << j;
					std::cout << "***************************\n";
					T.push_back(J);
					std::cout<<"i loop end\n";
				}
				std::cout<<"t loop end\n";
			}
			std::cout<< size << " " << T.size() << std::endl;
			if( size != T.size()){
				size = T.size();
			}else{
				break;
			}
		}
		std::cout<<"####################\n";
		for(auto t : T){
			std::cout<<"~~~~~~~~~~~~~~~\n";
			for(auto i : t){
				std::cout<< i;
			}
		}
	}
	void setup(){

        rules.push_back(Item( E,
            { T, Eq }
        ));

        rules.push_back(Item( Eq,
            {mtS("+"), T,  Eq }
        ));
        rules.push_back(Item( Eq,
            { Eps }
        ));

		rules.push_back(Item( T,
            { F, Tq}
        ));

		rules.push_back(Item( Tq,
            { mtS("*"), F, Tq }
        ));
        rules.push_back(Item( Tq,
            { Eps }
        ));

        rules.push_back(Item( F,
            { mtS("("), E, mtS(")")}
        ));
        rules.push_back(Item( F,
            { mtS("i")}
		));
    }

	using namespace std;

    void test(Sign S){
        std::cout << "==== "<<std::string(*S)<< " ===\n";
        for(auto& s: first(S)){
            std::cout << std::string(*s) << std::endl;
        }
        std::cout<<"===\n";
        for(auto& r: follow(S)){
            std::cout << std::string(*r) << std::endl;
        }
	}

    void parser(){
        setup();
        /*
		test(E);

        test(Eq);

        test(T);

        test(Tq);

        test(F);

        std::cout<<"===\n";
		std::vector<Item> items = { Item( mS("S"), { E, Fin}) };
        closure(items);
		std::cout<<"~~~~~~~~~~~~~~~\n";
        for(auto i : items)
			std::cout << i;
		*/
		DFA();

        //delete items;

        //create_dfa();
        //for(auto rit = rule_table.begin(); rit != rule_table.end(); ++rit){
        //    if(rit->second)
        //        rit->second.reset();
        //}
    }
}

int main(){
    parser::parser();
    return 0;
}
/*
 * ==== T ===
 * (
 * i
 * ===
 * FIN
 * )
 * +
 * ==== Tq ===
 * *
 * Epsilon
 * ===
 * FIN
 * )
 * +
 * ==== F ===
 * (
 * i
 * ===
 * FIN
 * )
 * +
 * *
 * ===
 */

<|endoftext|>


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

#include <zippylog/envelope.hpp>

#include <gtest/gtest.h>
#include <string.h>

using ::std::invalid_argument;
using ::std::string;
using ::zippylog::Envelope;
using ::zmq::message_t;

namespace zippylog {

TEST(EnvelopeTest, EmptyConstructor)
{
    ASSERT_NO_THROW(Envelope e());

    Envelope e;
    EXPECT_EQ(0, e.MessageCount());
    string s;
    EXPECT_TRUE(e.Serialize(s));
}

TEST(EnvelopeTest, InvalidDataConstruct)
{
    ASSERT_THROW(Envelope e(NULL, 0), invalid_argument);
    ASSERT_THROW(Envelope e(NULL, 10), invalid_argument);
    ASSERT_THROW(Envelope e((void *)324234, 0), invalid_argument);
    ASSERT_THROW(Envelope e((void *)352537, -10), invalid_argument);
}

TEST(EnvelopeTest, ZMQSerialization)
{
    Envelope e;

    string expected;
    ASSERT_TRUE(e.Serialize(expected));
    message_t m;

    ASSERT_TRUE(e.ToZmqMessage(m));
    ASSERT_EQ(expected.length(), m.size());
    EXPECT_TRUE(0 == memcmp(m.data(), expected.data(), m.size()));
}

TEST(EnvelopeTest, ZMQProtocolSerialization)
{
    Envelope e;

    string expected(1, 0x01);
    ASSERT_TRUE(e.Serialize(expected));
    message_t m;
    ASSERT_TRUE(e.ToProtocolZmqMessage(m));
    ASSERT_EQ(expected.length(), m.size());
    EXPECT_EQ(0x01, *((char *)m.data()));
    EXPECT_TRUE(0 == memcmp(m.data(), expected.data(), m.size()));
}

} // namespace
<commit_msg>add a Serialize() test<commit_after>//  Copyright 2010 Gregory Szorc
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

#include <zippylog/envelope.hpp>

#include <gtest/gtest.h>
#include <string.h>

using ::std::invalid_argument;
using ::std::string;
using ::zippylog::Envelope;
using ::zmq::message_t;

namespace zippylog {

TEST(EnvelopeTest, EmptyConstructor)
{
    ASSERT_NO_THROW(Envelope e());

    Envelope e;
    EXPECT_EQ(0, e.MessageCount());
    string s;
    EXPECT_TRUE(e.Serialize(s));
}

TEST(EnvelopeTest, InvalidDataConstruct)
{
    ASSERT_THROW(Envelope e(NULL, 0), invalid_argument);
    ASSERT_THROW(Envelope e(NULL, 10), invalid_argument);
    ASSERT_THROW(Envelope e((void *)324234, 0), invalid_argument);
    ASSERT_THROW(Envelope e((void *)352537, -10), invalid_argument);
}

TEST(EnvelopeTest, Serialize)
{
    Envelope e;
    string s;
    ASSERT_TRUE(e.Serialize(s));

    string s2 = "foo";
    ASSERT_TRUE(e.Serialize(s2));
    ASSERT_EQ(3 + s.length(), s2.length());
}

TEST(EnvelopeTest, ZMQSerialization)
{
    Envelope e;

    string expected;
    ASSERT_TRUE(e.Serialize(expected));
    message_t m;

    ASSERT_TRUE(e.ToZmqMessage(m));
    ASSERT_EQ(expected.length(), m.size());
    EXPECT_TRUE(0 == memcmp(m.data(), expected.data(), m.size()));
}

TEST(EnvelopeTest, ZMQProtocolSerialization)
{
    Envelope e;

    string expected(1, 0x01);
    ASSERT_TRUE(e.Serialize(expected));
    message_t m;
    ASSERT_TRUE(e.ToProtocolZmqMessage(m));
    ASSERT_EQ(expected.length(), m.size());
    EXPECT_EQ(0x01, *((char *)m.data()));
    EXPECT_TRUE(0 == memcmp(m.data(), expected.data(), m.size()));
}

} // namespace
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_eff_config_thermal.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p9_mss_eff_config_thermal.C
/// @brief Perform thermal calculations as part of the effective configuration
///
// *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <vector>
#include <p9_mss_eff_config_thermal.H>
#include <p9_mss_bulk_pwr_throttles.H>
#include <lib/power_thermal/throttle.H>
#include <lib/power_thermal/decoder.H>
#include <lib/dimm/kind.H>
#include <lib/utils/count_dimm.H>
#include <lib/shared/mss_const.H>
#include <mss.H>
extern "C"
{
    ///
    /// @brief Perform thermal calculations as part of the effective configuration
    /// @param[in] i_targets an array of MCS targets all on the same VDDR domain
    /// @return FAPI2_RC_SUCCESS iff ok
    /// @note sets ATTR_MSS_MEM_WATT_TARGET, ATTR_MSS_RUNTIME_MEM_THROTTLED_N_COMMANDS_PER_PORT and _PER_SLOT, and ATTR_MSS_PORT_MAXPOWER
    fapi2::ReturnCode p9_mss_eff_config_thermal( const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MCS> >& i_targets )
    {
        FAPI_INF("Start effective config thermal");
        fapi2::ReturnCode l_rc;

        std::vector< uint64_t > l_slope (mss::power_thermal::SIZE_OF_POWER_CURVES_ATTRS, 0);
        std::vector< uint64_t > l_intercept (mss::power_thermal::SIZE_OF_POWER_CURVES_ATTRS, 0);
        std::vector< uint64_t > l_thermal_power_limit (mss::power_thermal::SIZE_OF_THERMAL_ATTR, 0);

        uint16_t l_vddr_slope     [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};
        uint16_t l_vddr_int       [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};
        uint16_t l_total_slope    [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};
        uint16_t l_total_int      [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};
        uint32_t l_thermal_power  [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};

        FAPI_TRY( mss::mrw_pwr_slope (l_slope.data()), "Error in p9_mss_eff_config_thermal");
        FAPI_TRY( mss::mrw_pwr_intercept (l_intercept.data()), "Error in p9_mss_eff_config_thermal" );
        FAPI_TRY( mss::mrw_thermal_memory_power_limit (l_thermal_power_limit.data()), "Error in p9_mss_eff_config_thermal" );
        FAPI_TRY( mss::power_thermal::set_runtime_m_and_watt_limit (i_targets), "Error in p9_mss_eff_config_thermal");

        FAPI_INF("Size of vectors are %d %d %d", l_slope.size(), l_intercept.size(), l_thermal_power_limit.size());

        //Restore runtime_throttles from safemode setting
        //Decode and set power curve attributes at the same time
        for (const auto& l_mcs : i_targets )
        {
            //Not doing any work if there are no dimms installed
            if (mss::count_dimm(l_mcs) == 0)
            {
                FAPI_INF("Skipping eff_config thermal because no dimms %s", mss::c_str(l_mcs));
                continue;
            }

            FAPI_TRY( mss::power_thermal::get_power_attrs(l_mcs,
                      l_slope,
                      l_intercept,
                      l_thermal_power_limit,
                      l_vddr_slope,
                      l_vddr_int,
                      l_total_slope,
                      l_total_int,
                      l_thermal_power));

            //Sets throttles to max_databus_util value
            FAPI_INF("Restoring throttles");
            FAPI_TRY( mss::power_thermal::restore_runtime_throttles(l_mcs), "Error in p9_mss_eff_config_thermal");

            //Set the power attribute (TOTAL_PWR) to just VDDR for the POWER bulk_pwr_throttles, restore to vddr+vpp  later for OCC
            FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_SLOPE,
                                    l_mcs,
                                    l_vddr_slope));

            FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_INTERCEPT,
                                    l_mcs,
                                    l_vddr_int));

            FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_DIMM_THERMAL_LIMIT,
                                    l_mcs,
                                    l_thermal_power));
        }

        FAPI_INF("Starting bulk_pwr");
        //get the thermal limits, done per dimm and set to worst case for the slot and port throttles
        //Bulk_pwr sets the general, all purpose ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_SLOT, _PER_PORT, and MAXPOWER ATTRs
        FAPI_EXEC_HWP(l_rc, p9_mss_bulk_pwr_throttles, i_targets, mss::throttle_type::POWER);
        FAPI_TRY(l_rc, "Failed running p9_mss_bulk_pwr_throttles");

        //Set runtime throttles to worst case between ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_SLOT
        //and ATTR_MSS_MEM_RUNTIME_THROTTLED_N_COMMANDS_PER_SLOT and the _PORT equivalents also
        FAPI_INF("Starting update");
        FAPI_TRY( mss::power_thermal::update_runtime_throttles (i_targets), "Error in p9_mss_eff_config_thermal" );
        FAPI_INF("finished update");

        //Set VDDR+VPP power curve values
        for ( const auto& l_mcs : i_targets )
        {
            if (mss::count_dimm(l_mcs) == 0)
            {
                continue;
            }

            //Zero out the arrays
            memset(l_vddr_slope, 0, sizeof(l_vddr_slope));
            memset(l_vddr_int, 0, sizeof(l_vddr_int));
            memset(l_total_slope, 0, sizeof(l_total_slope));
            memset(l_total_int, 0, sizeof(l_total_int));
            memset(l_thermal_power, 0, sizeof(l_thermal_power));

            FAPI_TRY( mss::power_thermal::get_power_attrs(l_mcs,
                      l_slope,
                      l_intercept,
                      l_thermal_power_limit,
                      l_vddr_slope,
                      l_vddr_int,
                      l_total_slope,
                      l_total_int,
                      l_thermal_power));

            FAPI_INF( "VDDR+VPP power curve slope is %d, int is %d, thermal_power is %d", l_total_slope[0][0], l_total_int[0][0],
                      l_thermal_power[0][0]);

            //Set the power curve attributes (TOTAL_PWR) to vpp+vdd power slope and intercept
            FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_SLOPE,
                                    l_mcs,
                                    l_total_slope));

            FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_INTERCEPT,
                                    l_mcs,
                                    l_total_int));
        }

        //Run thermal throttles with the VDDR+VPP power curves
        FAPI_EXEC_HWP(l_rc, p9_mss_bulk_pwr_throttles, i_targets, mss::throttle_type::THERMAL);
        FAPI_TRY(l_rc, "Failed running p9_mss_bulk_pwr_throttles with THERMAL throttling in p9_mss_eff_config_thermal");
        //Update everything to worst case
        FAPI_TRY( mss::power_thermal::update_runtime_throttles (i_targets), "Error in p9_mss_eff_config_thermal" );

        //Done
        FAPI_INF( "End effective config thermal");

    fapi_try_exit:
        return fapi2::current_err;
    }
} //extern C
<commit_msg>Moves count_dimm to be in the memory generic folder<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_eff_config_thermal.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p9_mss_eff_config_thermal.C
/// @brief Perform thermal calculations as part of the effective configuration
///
// *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <vector>
#include <p9_mss_eff_config_thermal.H>
#include <p9_mss_bulk_pwr_throttles.H>
#include <lib/power_thermal/throttle.H>
#include <lib/power_thermal/decoder.H>
#include <lib/dimm/kind.H>
#include <generic/memory/lib/utils/count_dimm.H>
#include <lib/shared/mss_const.H>
#include <mss.H>
extern "C"
{
    ///
    /// @brief Perform thermal calculations as part of the effective configuration
    /// @param[in] i_targets an array of MCS targets all on the same VDDR domain
    /// @return FAPI2_RC_SUCCESS iff ok
    /// @note sets ATTR_MSS_MEM_WATT_TARGET, ATTR_MSS_RUNTIME_MEM_THROTTLED_N_COMMANDS_PER_PORT and _PER_SLOT, and ATTR_MSS_PORT_MAXPOWER
    fapi2::ReturnCode p9_mss_eff_config_thermal( const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MCS> >& i_targets )
    {
        FAPI_INF("Start effective config thermal");
        fapi2::ReturnCode l_rc;

        std::vector< uint64_t > l_slope (mss::power_thermal::SIZE_OF_POWER_CURVES_ATTRS, 0);
        std::vector< uint64_t > l_intercept (mss::power_thermal::SIZE_OF_POWER_CURVES_ATTRS, 0);
        std::vector< uint64_t > l_thermal_power_limit (mss::power_thermal::SIZE_OF_THERMAL_ATTR, 0);

        uint16_t l_vddr_slope     [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};
        uint16_t l_vddr_int       [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};
        uint16_t l_total_slope    [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};
        uint16_t l_total_int      [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};
        uint32_t l_thermal_power  [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};

        FAPI_TRY( mss::mrw_pwr_slope (l_slope.data()), "Error in p9_mss_eff_config_thermal");
        FAPI_TRY( mss::mrw_pwr_intercept (l_intercept.data()), "Error in p9_mss_eff_config_thermal" );
        FAPI_TRY( mss::mrw_thermal_memory_power_limit (l_thermal_power_limit.data()), "Error in p9_mss_eff_config_thermal" );
        FAPI_TRY( mss::power_thermal::set_runtime_m_and_watt_limit (i_targets), "Error in p9_mss_eff_config_thermal");

        FAPI_INF("Size of vectors are %d %d %d", l_slope.size(), l_intercept.size(), l_thermal_power_limit.size());

        //Restore runtime_throttles from safemode setting
        //Decode and set power curve attributes at the same time
        for (const auto& l_mcs : i_targets )
        {
            //Not doing any work if there are no dimms installed
            if (mss::count_dimm(l_mcs) == 0)
            {
                FAPI_INF("Skipping eff_config thermal because no dimms %s", mss::c_str(l_mcs));
                continue;
            }

            FAPI_TRY( mss::power_thermal::get_power_attrs(l_mcs,
                      l_slope,
                      l_intercept,
                      l_thermal_power_limit,
                      l_vddr_slope,
                      l_vddr_int,
                      l_total_slope,
                      l_total_int,
                      l_thermal_power));

            //Sets throttles to max_databus_util value
            FAPI_INF("Restoring throttles");
            FAPI_TRY( mss::power_thermal::restore_runtime_throttles(l_mcs), "Error in p9_mss_eff_config_thermal");

            //Set the power attribute (TOTAL_PWR) to just VDDR for the POWER bulk_pwr_throttles, restore to vddr+vpp  later for OCC
            FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_SLOPE,
                                    l_mcs,
                                    l_vddr_slope));

            FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_INTERCEPT,
                                    l_mcs,
                                    l_vddr_int));

            FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_DIMM_THERMAL_LIMIT,
                                    l_mcs,
                                    l_thermal_power));
        }

        FAPI_INF("Starting bulk_pwr");
        //get the thermal limits, done per dimm and set to worst case for the slot and port throttles
        //Bulk_pwr sets the general, all purpose ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_SLOT, _PER_PORT, and MAXPOWER ATTRs
        FAPI_EXEC_HWP(l_rc, p9_mss_bulk_pwr_throttles, i_targets, mss::throttle_type::POWER);
        FAPI_TRY(l_rc, "Failed running p9_mss_bulk_pwr_throttles");

        //Set runtime throttles to worst case between ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_SLOT
        //and ATTR_MSS_MEM_RUNTIME_THROTTLED_N_COMMANDS_PER_SLOT and the _PORT equivalents also
        FAPI_INF("Starting update");
        FAPI_TRY( mss::power_thermal::update_runtime_throttles (i_targets), "Error in p9_mss_eff_config_thermal" );
        FAPI_INF("finished update");

        //Set VDDR+VPP power curve values
        for ( const auto& l_mcs : i_targets )
        {
            if (mss::count_dimm(l_mcs) == 0)
            {
                continue;
            }

            //Zero out the arrays
            memset(l_vddr_slope, 0, sizeof(l_vddr_slope));
            memset(l_vddr_int, 0, sizeof(l_vddr_int));
            memset(l_total_slope, 0, sizeof(l_total_slope));
            memset(l_total_int, 0, sizeof(l_total_int));
            memset(l_thermal_power, 0, sizeof(l_thermal_power));

            FAPI_TRY( mss::power_thermal::get_power_attrs(l_mcs,
                      l_slope,
                      l_intercept,
                      l_thermal_power_limit,
                      l_vddr_slope,
                      l_vddr_int,
                      l_total_slope,
                      l_total_int,
                      l_thermal_power));

            FAPI_INF( "VDDR+VPP power curve slope is %d, int is %d, thermal_power is %d", l_total_slope[0][0], l_total_int[0][0],
                      l_thermal_power[0][0]);

            //Set the power curve attributes (TOTAL_PWR) to vpp+vdd power slope and intercept
            FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_SLOPE,
                                    l_mcs,
                                    l_total_slope));

            FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_INTERCEPT,
                                    l_mcs,
                                    l_total_int));
        }

        //Run thermal throttles with the VDDR+VPP power curves
        FAPI_EXEC_HWP(l_rc, p9_mss_bulk_pwr_throttles, i_targets, mss::throttle_type::THERMAL);
        FAPI_TRY(l_rc, "Failed running p9_mss_bulk_pwr_throttles with THERMAL throttling in p9_mss_eff_config_thermal");
        //Update everything to worst case
        FAPI_TRY( mss::power_thermal::update_runtime_throttles (i_targets), "Error in p9_mss_eff_config_thermal" );

        //Done
        FAPI_INF( "End effective config thermal");

    fapi_try_exit:
        return fapi2::current_err;
    }
} //extern C
<|endoftext|>