<commit_before>// Copyright 2015 The Statify Authors.
//
// 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. See the AUTHORS file for names of
// contributors.

#include <event2/event.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "statify/log.h"
#include "statify/program_options.h"

using statify::Log;
using statify::ProgramOptions;

int main(int argc, char* argv[]) {
  // Log startup
  Log::Write(Log::INFO, "statifyd - Copyright (C) 2015 The Statify Authors");
  Log::Write(Log::INFO, "starting up");

  // Extract program options from command line
  ProgramOptions options;
  options.ParseCommandLine(argc, argv);

  // Log important startup parameters
  Log::Write(Log::INFO, "listener port: %d", options.port());
  Log::Write(Log::INFO, "listener size: %d", options.backlog());

  // Create event base
  struct event_base* evbase = event_base_new();
  if (evbase == NULL) {
    Log::Write(Log::ABORT, "failed to create event base");
    return EXIT_FAILURE;
  }

  // Create a TCP listener
  // struct evconnlistener* listener = NULL;
  // listener = evconnlistener_new_bind(evbase, accept_callback, 0

  Log::Write(Log::INFO, "startup complete");

  // Dispatch events
  event_base_dispatch(evbase);

  // Log that we're initiating shutdown
  Log::Write(Log::INFO, "shutting down");

  // Free the event base
  event_base_free(evbase);

  // Finally, log that we're done and exiting.
  Log::Write(Log::INFO, "shutdown complete");

  return EXIT_SUCCESS;
}
<commit_msg>got server accepting connections<commit_after>// Copyright 2015 The Statify Authors.
//
// 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. See the AUTHORS file for names of
// contributors.

#include <arpa/inet.h>
#include <event2/event.h>
#include <event2/listener.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include "statify/log.h"
#include "statify/program_options.h"

using statify::Log;
using statify::ProgramOptions;

namespace {

// Callback that is registered to handle new connection attempts.
void accept_callback(struct evconnlistener* listener, evutil_socket_t sock,
                     struct sockaddr* addr, int, void* arg) {
  // Reference arguments
  (void)listener;
  (void)sock;
  (void)addr;
  (void)arg;

  Log::Write(Log::INFO, "accepted connection");
  close(sock);
  Log::Write(Log::INFO, "closed connection");
}

// Callback that is registered to handle errors occurring during accept.
void accept_error_callback(struct evconnlistener* listener, void* arg) {
  (void)listener;
  (void)arg;

  Log::Write(Log::ERROR, "failed to accept connection");
}

}  // namespace

int main(int argc, char* argv[]) {
  // Log startup
  Log::Write(Log::INFO, "statifyd - Copyright (C) 2015 The Statify Authors");
  Log::Write(Log::INFO, "starting up");

  // Extract program options from command line
  ProgramOptions options;
  options.ParseCommandLine(argc, argv);

  // Log important startup parameters
  Log::Write(Log::INFO, "listener port: %d", options.port());
  Log::Write(Log::INFO, "listener size: %d", options.backlog());

  // Create event base
  struct event_base* evbase = event_base_new();
  if (evbase == NULL) {
    Log::Write(Log::ABORT, "failed to create event base");
    return EXIT_FAILURE;
  }

  // Construct wildcard address for listening on the chosen port.
  struct sockaddr_in address;
  memset(&address, 0, sizeof(address));
  address.sin_family = AF_INET;
  address.sin_addr.s_addr = htonl(0);
  address.sin_port = htons(options.port());

  // Create a TCP listener
  struct evconnlistener* listener = NULL;
  listener = evconnlistener_new_bind(
      evbase, accept_callback, 0, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE,
      options.backlog(), reinterpret_cast<struct sockaddr*>(&address),
      sizeof(address));
  if (listener == NULL) {
    Log::Write(Log::ABORT, "failed to establish listener");
  }

  // Configure a callback function to invoke on errors
  evconnlistener_set_error_cb(listener, accept_error_callback);

  Log::Write(Log::INFO, "startup complete");

  // Dispatch events: This runs the event loop.
  event_base_dispatch(evbase);

  evconnlistener_free(listener);

  // Log that we're initiating shutdown
  Log::Write(Log::INFO, "shutting down");

  // Free the event base
  event_base_free(evbase);

  // Finally, log that we're done and exiting.
  Log::Write(Log::INFO, "shutdown complete");

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>
#include "dogbot/LegKinematics.hh"
#include <math.h>
#include <assert.h>
#include <iostream>

namespace DogBotN {

  static float Sqr(float val)
  { return val * val; }

  LegKinematicsC::LegKinematicsC()
  {}

  //! Construct from a json object
  LegKinematicsC::LegKinematicsC(const Json::Value &value)
  {
    ConfigureFromJSON(value);
  }

  //! Create
  LegKinematicsC::LegKinematicsC(float l1,float l2)
   : m_l1(l1),
     m_l2(l2)
  {}

  //! Configure from JSON
  bool LegKinematicsC::ConfigureFromJSON(const Json::Value &value)
  {
    m_name = value.get("name","").asString();
    m_l1 = value.get("l1",m_l1).asFloat();
    m_l2 = value.get("l2",m_l2).asFloat();
    m_zoff = value.get("ZOffset",m_zoff).asFloat();
    m_linkA = value.get("LinkA",m_linkA).asFloat();
    m_linkB = value.get("LinkB",m_linkB).asFloat();
    m_linkH = value.get("LinkH",m_linkH).asFloat();

    m_footDrop = value.get("FootDrop",m_footDrop).asFloat();
    m_footSphereRadius = value.get("FootSphereRadius",m_footSphereRadius).asFloat();

    m_jointDirections[0] = value.get("dirRoll",m_jointDirections[0]).asFloat();
    m_jointDirections[1] = value.get("dirPitch",m_jointDirections[1]).asFloat();
    m_jointDirections[2] = value.get("dirKnee",m_jointDirections[2]).asFloat();

    m_alternateSolution = value.get("alternateSolution",false).asBool();

    // Generate some default leg positions.

    if(m_name == "front_left") {
      m_legOrigin[0] = -m_bodyWidth/2.0;
      m_legOrigin[1] = m_bodyLength/2.0;
      m_legOrigin[2] = 0;
    } else if(m_name == "front_right") {
      m_legOrigin[0] = m_bodyWidth/2.0;
      m_legOrigin[1] = m_bodyLength/2.0;
      m_legOrigin[2] = 0;
    } else if(m_name == "back_left") {
      m_legOrigin[0] = -m_bodyWidth/2.0;
      m_legOrigin[1] = -m_bodyLength/2.0;
      m_legOrigin[2] = 0;
    } else if(m_name == "back_right") {
      m_legOrigin[0] = m_bodyWidth/2.0;
      m_legOrigin[1] = -m_bodyLength/2.0;
      m_legOrigin[2] = 0;
    }
    std::cout << " Name:" << m_name << "  Origin:" << m_legOrigin[0] << " " << m_legOrigin[1] << " " << m_legOrigin[2] << " " << std::endl;
    std::cout << "  Leg: L1=" << m_l1 << " L2=" << m_l2 << " linkA=" << m_linkA << " linkB=" << m_linkB << " LinkH=" << m_linkH << std::endl;
    return true;
  }

  //! Get the servo configuration as JSON
  Json::Value LegKinematicsC::ConfigAsJSON() const
  {
    Json::Value ret;

    ret["name"] = m_name;
    ret["l1"] = m_l1;
    ret["l2"] = m_l2;
    ret["ZOffset"] = m_zoff;
    ret["LinkA"] = m_linkA;
    ret["LinkB"] = m_linkB;
    ret["LinkH"] = m_linkH;

    ret["dirRoll"] = m_jointDirections[0];
    ret["dirPitch"] = m_jointDirections[1];
    ret["dirKnee"] = m_jointDirections[2];

    ret["FootDrop"] = m_footDrop;
    ret["FootSphereRadius"] = m_footSphereRadius;

    ret["alternateSolution"] = m_alternateSolution;

    return ret;
  }

  //! Inverse kinematics for the leg using a virtual joint for the knee
  //! Compute joint angles needed to get to a 3d position in a leg coordinate system
  //! Return true if position is reachable
  bool LegKinematicsC::InverseVirtual(const Eigen::Vector3f &at, Eigen::Vector3f &angles) const
  {
#if 1
    float x = -at[0];
    float y = -at[1];
    float z = -at[2];
#else
    float x = -at[0] - m_legOrigin[0];
    float y = -at[1] - m_legOrigin[1];
    float z = -at[2] - m_legOrigin[2];
#endif

    {
      float ta = atan2(x,z);

      angles[0] = ta;

      z = sin(ta) * x + cos(ta) * z - m_zoff;
    }

    float l2 = Sqr(z) + Sqr(y);
    double ac1 = (l2 + Sqr(m_l1) - Sqr(m_l2))/(2 * sqrt(l2) * m_l1);
    if(ac1 < -1 || ac1 > 1) {
      std::cerr << "No pitch solution." << std::endl;
      std::cerr << "L1=" << m_l1 << " L2=" << m_l2 << " Zoff=" << m_zoff << " ." << std::endl;
      return false;
    }

    float a1 = atan2(y,z);
    angles[1] = -1 *(a1 + acos(ac1));

    double ac2 = (Sqr(m_l2) + Sqr(m_l1) -l2)/(2 * m_l2 * m_l1);
    if(ac2 < -1 || ac2 > 1) {
      std::cerr << "No knee solution." << std::endl;
      std::cerr << "L1=" << m_l1 << " L2=" << m_l2 << " Zoff=" << m_zoff << " ." << std::endl;
      return false;
    }

    float kneeTarget = M_PI - acos(ac2);

    angles[2] = kneeTarget;

    for(int i = 0;i < 3;i++)
      angles[i] *= m_jointDirections[i];

    return true;
  }

  //! Forward kinematics for the leg using a virtual joint for the knee
  //! Compute the position of the foot relative to the top of the leg from the joint angles.
  bool LegKinematicsC::ForwardVirtual(const Eigen::Vector3f &anglesIn,Eigen::Vector3f &at) const
  {
    Eigen::Vector3f angles;

    for(int i = 0;i < 3;i++)
      angles[i] = anglesIn[i] * m_jointDirections[i];

    float kneeAngle = angles[2];

    float y = m_l1 * sin(angles[1]) + m_l2 * sin(angles[1] + kneeAngle);
    float z = m_l1 * cos(angles[1]) + m_l2 * cos(angles[1] + kneeAngle);

    //float xr = 0;
    at[0] =  -sin(angles[0]) * (m_zoff + z); //  + cos(angles[0]) * xr
    at[1] =  + y;
    at[2] =  -cos(angles[0]) * (m_zoff + z); // + sin(angles[0]) * xr

    //for(int i = 0;i < 3;i++) at[i] += m_legOrigin[i];

    return true;
  }

  //! Inverse kinematics for the leg
  //! Compute joint angles needed to get to a 3d position in a leg coordinate system
  //! Return true if position is reachable
  bool LegKinematicsC::InverseDirect(const Eigen::Vector3f &at,Eigen::Vector3f &angles) const
  {
    if(!InverseVirtual(at,angles))
      return false;

    // Allow for 4 bar linkage
    float theta = 0;
    if(!Linkage4BarBack(angles[2] ,theta,UseAlternateSolution())) {
      return false;
    }
    angles[2] = theta - angles[1];

    return true;
  }

  //! Forward kinematics for the leg
  //! Compute the position of the foot relative to the top of the leg from the joint angles.
  bool LegKinematicsC::ForwardDirect(const Eigen::Vector3f &angles,Eigen::Vector3f &at) const
  {
    float theta = angles[2] + angles[1];

    // Theta = Knee Servo
    // Psi = Knee joint
    float psi = Linkage4BarForward(theta,UseAlternateSolution());
    Eigen::Vector3f anglesVirtual = {angles[0],angles[1],psi};

    if(!ForwardVirtual(anglesVirtual,at))
      return false;
    return false;
  }

  //! 4 bar linkage angle backward,
  // Returns true if angle exists.
  bool LegKinematicsC::Linkage4BarBack(float psi,float &theta,bool solution2) const
  {
    float val = 0;
    if(!Linkage4Bar(M_PI - psi,m_linkB,m_linkA,m_l1,m_linkH,val,solution2))
      return false;
    theta = M_PI - val;
    return true;
  }

  float LegKinematicsC::Linkage4BarForward(float theta,bool solution2) const
  {
    float ret = 0;
    bool ok = Linkage4Bar(theta,m_linkA,m_linkB,m_l1,m_linkH,ret,solution2);
    //assert(ok);
    return ret; // Psi
  }

  bool LegKinematicsC::Linkage4Bar(
      float theta,
      float a,float b,float g,float h,
      float &psi,
      bool solution2
      ) const
  {
    float At = 2 * b * g - 2 * a * b * cos(theta);
    float Bt = -2 * a * b * sin(theta);
    float Ct = a*a + b * b + g * g -h * h - 2 * a * g * cos(theta);

    float delta = atan(Bt/At);
    float cosAngle = -Ct / sqrt(At * At + Bt * Bt);
    if(cosAngle > 1.0 || cosAngle < -1.0) {
      std::cerr << "No angle found for linkage. " << std::endl;
      return false;
    }
    psi = delta + (solution2 ? -1 : 1) * acos(cosAngle);
    return true;
  }

  // Compute the speed ratio at the given input angle.

  float LegKinematicsC::LinkageSpeedRatio(float theta,float psi) const
  {
    float a = m_linkA;
    float b = m_linkB;
    float g = m_l1;
    float h = m_linkH;

    float result =
        -(- a * b * cos(psi) * sin(theta) - b * g * sin(psi) + a * b * cos(theta) * sin(psi)) /
        (a * g * sin(theta) + a * b * cos(psi) * sin(theta) - a * b * cos(theta) * sin(psi) );

    return result;
  }

}

<commit_msg>Disable failure messages.<commit_after>
#include "dogbot/LegKinematics.hh"
#include <math.h>
#include <assert.h>
#include <iostream>

namespace DogBotN {

  static float Sqr(float val)
  { return val * val; }

  LegKinematicsC::LegKinematicsC()
  {}

  //! Construct from a json object
  LegKinematicsC::LegKinematicsC(const Json::Value &value)
  {
    ConfigureFromJSON(value);
  }

  //! Create
  LegKinematicsC::LegKinematicsC(float l1,float l2)
   : m_l1(l1),
     m_l2(l2)
  {}

  //! Configure from JSON
  bool LegKinematicsC::ConfigureFromJSON(const Json::Value &value)
  {
    m_name = value.get("name","").asString();
    m_l1 = value.get("l1",m_l1).asFloat();
    m_l2 = value.get("l2",m_l2).asFloat();
    m_zoff = value.get("ZOffset",m_zoff).asFloat();
    m_linkA = value.get("LinkA",m_linkA).asFloat();
    m_linkB = value.get("LinkB",m_linkB).asFloat();
    m_linkH = value.get("LinkH",m_linkH).asFloat();

    m_footDrop = value.get("FootDrop",m_footDrop).asFloat();
    m_footSphereRadius = value.get("FootSphereRadius",m_footSphereRadius).asFloat();

    m_jointDirections[0] = value.get("dirRoll",m_jointDirections[0]).asFloat();
    m_jointDirections[1] = value.get("dirPitch",m_jointDirections[1]).asFloat();
    m_jointDirections[2] = value.get("dirKnee",m_jointDirections[2]).asFloat();

    m_alternateSolution = value.get("alternateSolution",false).asBool();

    // Generate some default leg positions.

    if(m_name == "front_left") {
      m_legOrigin[0] = -m_bodyWidth/2.0;
      m_legOrigin[1] = m_bodyLength/2.0;
      m_legOrigin[2] = 0;
    } else if(m_name == "front_right") {
      m_legOrigin[0] = m_bodyWidth/2.0;
      m_legOrigin[1] = m_bodyLength/2.0;
      m_legOrigin[2] = 0;
    } else if(m_name == "back_left") {
      m_legOrigin[0] = -m_bodyWidth/2.0;
      m_legOrigin[1] = -m_bodyLength/2.0;
      m_legOrigin[2] = 0;
    } else if(m_name == "back_right") {
      m_legOrigin[0] = m_bodyWidth/2.0;
      m_legOrigin[1] = -m_bodyLength/2.0;
      m_legOrigin[2] = 0;
    }
    std::cout << " Name:" << m_name << "  Origin:" << m_legOrigin[0] << " " << m_legOrigin[1] << " " << m_legOrigin[2] << " " << std::endl;
    std::cout << "  Leg: L1=" << m_l1 << " L2=" << m_l2 << " linkA=" << m_linkA << " linkB=" << m_linkB << " LinkH=" << m_linkH << std::endl;
    return true;
  }

  //! Get the servo configuration as JSON
  Json::Value LegKinematicsC::ConfigAsJSON() const
  {
    Json::Value ret;

    ret["name"] = m_name;
    ret["l1"] = m_l1;
    ret["l2"] = m_l2;
    ret["ZOffset"] = m_zoff;
    ret["LinkA"] = m_linkA;
    ret["LinkB"] = m_linkB;
    ret["LinkH"] = m_linkH;

    ret["dirRoll"] = m_jointDirections[0];
    ret["dirPitch"] = m_jointDirections[1];
    ret["dirKnee"] = m_jointDirections[2];

    ret["FootDrop"] = m_footDrop;
    ret["FootSphereRadius"] = m_footSphereRadius;

    ret["alternateSolution"] = m_alternateSolution;

    return ret;
  }

  //! Inverse kinematics for the leg using a virtual joint for the knee
  //! Compute joint angles needed to get to a 3d position in a leg coordinate system
  //! Return true if position is reachable
  bool LegKinematicsC::InverseVirtual(const Eigen::Vector3f &at, Eigen::Vector3f &angles) const
  {
#if 1
    float x = -at[0];
    float y = -at[1];
    float z = -at[2];
#else
    float x = -at[0] - m_legOrigin[0];
    float y = -at[1] - m_legOrigin[1];
    float z = -at[2] - m_legOrigin[2];
#endif

    {
      float ta = atan2(x,z);

      angles[0] = ta;

      z = sin(ta) * x + cos(ta) * z - m_zoff;
    }

    float l2 = Sqr(z) + Sqr(y);
    double ac1 = (l2 + Sqr(m_l1) - Sqr(m_l2))/(2 * sqrt(l2) * m_l1);
    if(ac1 < -1 || ac1 > 1) {
      //std::cerr << "No pitch solution." << std::endl;
      return false;
    }

    float a1 = atan2(y,z);
    angles[1] = -1 *(a1 + acos(ac1));

    double ac2 = (Sqr(m_l2) + Sqr(m_l1) -l2)/(2 * m_l2 * m_l1);
    if(ac2 < -1 || ac2 > 1) {
      //std::cerr << "No knee solution." << std::endl;
      return false;
    }

    float kneeTarget = M_PI - acos(ac2);

    angles[2] = kneeTarget;

    for(int i = 0;i < 3;i++)
      angles[i] *= m_jointDirections[i];

    return true;
  }

  //! Forward kinematics for the leg using a virtual joint for the knee
  //! Compute the position of the foot relative to the top of the leg from the joint angles.
  bool LegKinematicsC::ForwardVirtual(const Eigen::Vector3f &anglesIn,Eigen::Vector3f &at) const
  {
    Eigen::Vector3f angles;

    for(int i = 0;i < 3;i++)
      angles[i] = anglesIn[i] * m_jointDirections[i];

    float kneeAngle = angles[2];

    float y = m_l1 * sin(angles[1]) + m_l2 * sin(angles[1] + kneeAngle);
    float z = m_l1 * cos(angles[1]) + m_l2 * cos(angles[1] + kneeAngle);

    //float xr = 0;
    at[0] =  -sin(angles[0]) * (m_zoff + z); //  + cos(angles[0]) * xr
    at[1] =  + y;
    at[2] =  -cos(angles[0]) * (m_zoff + z); // + sin(angles[0]) * xr

    //for(int i = 0;i < 3;i++) at[i] += m_legOrigin[i];

    return true;
  }

  //! Inverse kinematics for the leg
  //! Compute joint angles needed to get to a 3d position in a leg coordinate system
  //! Return true if position is reachable
  bool LegKinematicsC::InverseDirect(const Eigen::Vector3f &at,Eigen::Vector3f &angles) const
  {
    if(!InverseVirtual(at,angles))
      return false;

    // Allow for 4 bar linkage
    float theta = 0;
    if(!Linkage4BarBack(angles[2] ,theta,UseAlternateSolution())) {
      return false;
    }
    angles[2] = theta - angles[1];

    return true;
  }

  //! Forward kinematics for the leg
  //! Compute the position of the foot relative to the top of the leg from the joint angles.
  bool LegKinematicsC::ForwardDirect(const Eigen::Vector3f &angles,Eigen::Vector3f &at) const
  {
    float theta = angles[2] + angles[1];

    // Theta = Knee Servo
    // Psi = Knee joint
    float psi = Linkage4BarForward(theta,UseAlternateSolution());
    Eigen::Vector3f anglesVirtual = {angles[0],angles[1],psi};

    if(!ForwardVirtual(anglesVirtual,at))
      return false;
    return false;
  }

  //! 4 bar linkage angle backward,
  // Returns true if angle exists.
  bool LegKinematicsC::Linkage4BarBack(float psi,float &theta,bool solution2) const
  {
    float val = 0;
    if(!Linkage4Bar(M_PI - psi,m_linkB,m_linkA,m_l1,m_linkH,val,solution2))
      return false;
    theta = M_PI - val;
    return true;
  }

  float LegKinematicsC::Linkage4BarForward(float theta,bool solution2) const
  {
    float ret = 0;
    bool ok = Linkage4Bar(theta,m_linkA,m_linkB,m_l1,m_linkH,ret,solution2);
    //assert(ok);
    return ret; // Psi
  }

  bool LegKinematicsC::Linkage4Bar(
      float theta,
      float a,float b,float g,float h,
      float &psi,
      bool solution2
      ) const
  {
    float At = 2 * b * g - 2 * a * b * cos(theta);
    float Bt = -2 * a * b * sin(theta);
    float Ct = a*a + b * b + g * g -h * h - 2 * a * g * cos(theta);

    float delta = atan(Bt/At);
    float cosAngle = -Ct / sqrt(At * At + Bt * Bt);
    if(cosAngle > 1.0 || cosAngle < -1.0) {
      std::cerr << "No angle found for linkage. " << std::endl;
      return false;
    }
    psi = delta + (solution2 ? -1 : 1) * acos(cosAngle);
    return true;
  }

  // Compute the speed ratio at the given input angle.

  float LegKinematicsC::LinkageSpeedRatio(float theta,float psi) const
  {
    float a = m_linkA;
    float b = m_linkB;
    float g = m_l1;
    float h = m_linkH;

    float result =
        -(- a * b * cos(psi) * sin(theta) - b * g * sin(psi) + a * b * cos(theta) * sin(psi)) /
        (a * g * sin(theta) + a * b * cos(psi) * sin(theta) - a * b * cos(theta) * sin(psi) );

    return result;
  }

}

<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    MeshTraits.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

//  Software Guide : BeginLatex
//
//  This section illustrates the full power of
//  \href{http://www.boost.org/more/generic_programming.html}{Generic
//  Programming}.  This is sometimes perceived as \emph{too much of a good
//  thing}!
//
//  The toolkit has been designed to offer flexibility while keeping the
//  complexity of the code to a moderate level. This is achieved in the Mesh by
//  hiding most of its parameters and defining reasonable defaults for them.
//
//  The generic concept of a mesh integrates many different elements. It is
//  possible in principle to use independent types for every one of such
//  elements. The mechanism used in generic programming for specifying the many
//  different types involved in a concept is called \emph{traits}. They are
//  basically the list of all types that interact with the current class.
//
//  The \doxygen{Mesh} is templated over three parameters. So far only two of
//  them have been discussed, namely the \code{PixelType} and the
//  \code{Dimension}. The third parameter is a class providing the set of
//  traits required by the mesh. When the third parameter is omitted a default
//  class is used. This default class is the \doxygen{DefaultStaticMeshTraits}.
//  If you want to customize the types used by the mesh, the way to proceed is
//  to modify the default traits and provide them as the third parameter of the
//  Mesh class instantiation.
//
//  There are two ways of achieving this. The first is to use the existing
//  DefaultStaticMeshTraits class. This class is itself templated
//  over six parameters.  Customizing those parameters could provide enough
//  flexibility to define a very specific kind of mesh. The second way is to
//  write a traits class from scratch, in which case the easiest way to proceed
//  is to copy the DefaultStaticMeshTraits into another file and edit
//  its content. Only the first approach is illustrated here. The second is
//  discouraged unless you are familiar with Generic Programming, feel
//  comfortable with C++ templates and have access to an abundant supply of
//  (Columbian) coffee.
//
//  The first step in customizing the mesh is to include the header file of the
//  Mesh and its static traits.
//
//  \index{itk::DefaultStaticMeshTraits!Header}
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkMesh.h"
#include "itkDefaultStaticMeshTraits.h"
// Software Guide : EndCodeSnippet

#include "itkLineCell.h"
#include "itkVector.h"
#include "itkMatrix.h"

int main(int, char *[])
{
  //  Software Guide : BeginLatex
  //
  //  Then the MeshTraits class is instantiated by selecting the types of each
  //  one of its six template arguments. They are in order
  //
  //  \begin{description}
  //  \item[PixelType.] The type associated with every point.
  //  \item[PointDimension.] The dimension of the space in which the mesh is embedded.
  //  \item[MaxTopologicalDimension.] The highest dimension of the mesh cells.
  //  \item[CoordRepType.] The type used to represent space coordinates.
  //  \item[InterpolationWeightType.]  The type used to represent interpolation weights.
  //  \item[CellPixelType.] The type associated with every cell.
  //  \end{description}
  //
  //  Let's define types and values for each one of those elements. For example
  //  the following code will use points in 3D space as nodes of the
  //  Mesh. The maximum dimension of the cells will be two which means
  //  that this is a 2D manifold better know as a \emph{surface}. The data type
  //  associated with points is defined to be a four-dimensional vector. This
  //  type could represent values of membership for a four-classes segmentation
  //  method.  The value selected for the cells are $4\times3$ matrices which could
  //  have for example the derivative of the membership values with respect to
  //  coordinates in space. Finally a \code{double} type is selected for
  //  representing space coordinates on the mesh points and also for the weight
  //  used for interpolating values.
  //
  //  \index{itk::DefaultStaticMeshTraits!Instantiation}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  const unsigned int PointDimension = 3;
  const unsigned int MaxTopologicalDimension = 2;

  typedef itk::Vector<double,4>                  PixelType;
  typedef itk::Matrix<double,4,3>                CellDataType;

  typedef double CoordinateType;
  typedef double InterpolationWeightType;

  typedef itk::DefaultStaticMeshTraits<
            PixelType, PointDimension, MaxTopologicalDimension,
            CoordinateType, InterpolationWeightType, CellDataType > MeshTraits;

  typedef itk::Mesh< PixelType, PointDimension, MeshTraits > MeshType;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The \doxygen{LineCell} type can now be instantiated using the traits
  //  taken from the Mesh.
  //
  //  \index{itk::LineCell!Instantiation}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef MeshType::CellType                CellType;
  typedef itk::LineCell< CellType >         LineType;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Let's now create an Mesh and insert some points on it. Note
  //  that the dimension of the points matches the dimension of the Mesh. Here
  //  we insert a sequence of points that look like a plot of the $log()$
  //  function.
  //
  //  \index{itk::Mesh!New()}
  //  \index{itk::Mesh!SetPoint()}
  //  \index{itk::Mesh!PointType}
  //  \index{itk::Mesh!Pointer}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  MeshType::Pointer  mesh = MeshType::New();

  typedef MeshType::PointType PointType;
  PointType point;

  const unsigned int numberOfPoints = 10;
  for(unsigned int id=0; id<numberOfPoints; id++)
    {
    point[0] = 1.565;   // Initialize points here
    point[1] = 3.647;   // with arbitrary values
    point[2] = 4.129;
    mesh->SetPoint( id, point );
    }
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  A set of line cells is created and associated with the existing points by
  //  using point identifiers. In this simple case, the point identifiers can
  //  be deduced from cell identifiers since the line cells are ordered in the
  //  same way. Note that in the code above, the values assigned to point
  //  components are arbitrary. In a more realistic example, those values would
  //  be computed from another source.
  //
  //  \index{itk::AutoPointer!TakeOwnership()}
  //  \index{CellAutoPointer!TakeOwnership()}
  //  \index{CellType!creation}
  //  \index{itk::Mesh!SetCell()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  CellType::CellAutoPointer line;
  const unsigned int numberOfCells = numberOfPoints-1;
  for(unsigned int cellId=0; cellId<numberOfCells; cellId++)
    {
    line.TakeOwnership(  new LineType  );
    line->SetPointId( 0, cellId   ); // first point
    line->SetPointId( 1, cellId+1 ); // second point
    mesh->SetCell( cellId, line );   // insert the cell
    }
  // Software Guide : EndCodeSnippet

  std::cout << "Points = " << mesh->GetNumberOfPoints() << std::endl;
  std::cout << "Cells  = " << mesh->GetNumberOfCells()  << std::endl;

  //  Software Guide : BeginLatex
  //
  //  Data associated with cells is inserted in the Mesh by using
  //  the \code{SetCellData()} method.  It requires the user to provide an
  //  identifier and the value to be inserted. The identifier should match one
  //  of the inserted cells. In this simple example, the square of the cell
  //  identifier is used as cell data. Note the use of \code{static\_cast} to
  //  \code{PixelType} in the assignment.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  for(unsigned int cellId=0; cellId<numberOfCells; cellId++)
    {
    CellDataType value;
    mesh->SetCellData( cellId, value );
    }

  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Cell data can be read from the Mesh with the
  //  \code{GetCellData()} method. It requires the user to provide the
  //  identifier of the cell for which the data is to be retrieved. The user
  //  should provide also a valid pointer to a location where the data can be
  //  copied.
  //
  //  \index{itk::Mesh!GetCellData()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  for(unsigned int cellId=0; cellId<numberOfCells; cellId++)
    {
    CellDataType value;
    mesh->GetCellData( cellId, &value );
    std::cout << "Cell " << cellId << " = " << value << std::endl;
    }
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Neither \code{SetCellData()} or \code{GetCellData()} are efficient ways
  //  to access cell data. Efficient access to cell data can be achieved
  //  by using the Iterators built into the CellDataContainer.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef MeshType::CellDataContainer::ConstIterator CellDataIterator;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Note that the \code{ConstIterator} is used here because the data is only
  //  going to be read.  This approach is exactly the same already illustrated
  //  for getting access to point data. The iterator to the first cell data
  //  item can be obtained with the \code{Begin()} method of the
  //  CellDataContainer. The past-end iterator is returned by the \code{End()}
  //  method. The cell data container itself can be obtained from the mesh with
  //  the method \code{GetCellData()}.
  //
  //  \index{itk::Mesh!Iterating cell data}
  //  \index{itk::Mesh!GetCellData()}
  //  \index{CellDataContainer!Begin()}
  //  \index{CellDataContainer!End()}
  //  \index{CellDataContainer!Iterator}
  //  \index{CellDataContainer!ConstIterator}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  CellDataIterator cellDataIterator  = mesh->GetCellData()->Begin();
  CellDataIterator end               = mesh->GetCellData()->End();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Finally a standard loop is used to iterate over all the cell data
  //  entries. Note the use of the \code{Value()} method used to get the actual
  //  value of the data entry. \code{PixelType} elements are returned by copy.
  //
  //  \index{CellDataIterator!Value()}
  //  \index{CellDataIterator!increment}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  while( cellDataIterator != end )
    {
    CellDataType cellValue = cellDataIterator.Value();
    std::cout << cellValue << std::endl;
    ++cellDataIterator;
    }
  // Software Guide : EndCodeSnippet

  return 0;
}

<commit_msg>BUG: 5147. Fixing documentation that was copy-pasted from Mesh3.cxx.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    MeshTraits.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

//  Software Guide : BeginLatex
//
//  This section illustrates the full power of
//  \href{http://www.boost.org/more/generic_programming.html}{Generic
//  Programming}.  This is sometimes perceived as \emph{too much of a good
//  thing}!
//
//  The toolkit has been designed to offer flexibility while keeping the
//  complexity of the code to a moderate level. This is achieved in the Mesh by
//  hiding most of its parameters and defining reasonable defaults for them.
//
//  The generic concept of a mesh integrates many different elements. It is
//  possible in principle to use independent types for every one of such
//  elements. The mechanism used in generic programming for specifying the many
//  different types involved in a concept is called \emph{traits}. They are
//  basically the list of all types that interact with the current class.
//
//  The \doxygen{Mesh} is templated over three parameters. So far only two of
//  them have been discussed, namely the \code{PixelType} and the
//  \code{Dimension}. The third parameter is a class providing the set of
//  traits required by the mesh. When the third parameter is omitted a default
//  class is used. This default class is the \doxygen{DefaultStaticMeshTraits}.
//  If you want to customize the types used by the mesh, the way to proceed is
//  to modify the default traits and provide them as the third parameter of the
//  Mesh class instantiation.
//
//  There are two ways of achieving this. The first is to use the existing
//  DefaultStaticMeshTraits class. This class is itself templated
//  over six parameters.  Customizing those parameters could provide enough
//  flexibility to define a very specific kind of mesh. The second way is to
//  write a traits class from scratch, in which case the easiest way to proceed
//  is to copy the DefaultStaticMeshTraits into another file and edit
//  its content. Only the first approach is illustrated here. The second is
//  discouraged unless you are familiar with Generic Programming, feel
//  comfortable with C++ templates and have access to an abundant supply of
//  (Columbian) coffee.
//
//  The first step in customizing the mesh is to include the header file of the
//  Mesh and its static traits.
//
//  \index{itk::DefaultStaticMeshTraits!Header}
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkMesh.h"
#include "itkDefaultStaticMeshTraits.h"
// Software Guide : EndCodeSnippet

#include "itkLineCell.h"
#include "itkVector.h"
#include "itkMatrix.h"

int main(int, char *[])
{
  //  Software Guide : BeginLatex
  //
  //  Then the MeshTraits class is instantiated by selecting the types of each
  //  one of its six template arguments. They are in order
  //
  //  \begin{description}
  //  \item[PixelType.] The type associated with every point.
  //  \item[PointDimension.] The dimension of the space in which the mesh is embedded.
  //  \item[MaxTopologicalDimension.] The highest dimension of the mesh cells.
  //  \item[CoordRepType.] The type used to represent space coordinates.
  //  \item[InterpolationWeightType.]  The type used to represent interpolation weights.
  //  \item[CellPixelType.] The type associated with every cell.
  //  \end{description}
  //
  //  Let's define types and values for each one of those elements. For example
  //  the following code will use points in 3D space as nodes of the
  //  Mesh. The maximum dimension of the cells will be two which means
  //  that this is a 2D manifold better know as a \emph{surface}. The data type
  //  associated with points is defined to be a four-dimensional vector. This
  //  type could represent values of membership for a four-classes segmentation
  //  method.  The value selected for the cells are $4\times3$ matrices which could
  //  have for example the derivative of the membership values with respect to
  //  coordinates in space. Finally a \code{double} type is selected for
  //  representing space coordinates on the mesh points and also for the weight
  //  used for interpolating values.
  //
  //  \index{itk::DefaultStaticMeshTraits!Instantiation}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  const unsigned int PointDimension = 3;
  const unsigned int MaxTopologicalDimension = 2;

  typedef itk::Vector<double,4>                  PixelType;
  typedef itk::Matrix<double,4,3>                CellDataType;

  typedef double CoordinateType;
  typedef double InterpolationWeightType;

  typedef itk::DefaultStaticMeshTraits<
            PixelType, PointDimension, MaxTopologicalDimension,
            CoordinateType, InterpolationWeightType, CellDataType > MeshTraits;

  typedef itk::Mesh< PixelType, PointDimension, MeshTraits > MeshType;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The \doxygen{LineCell} type can now be instantiated using the traits
  //  taken from the Mesh.
  //
  //  \index{itk::LineCell!Instantiation}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef MeshType::CellType                CellType;
  typedef itk::LineCell< CellType >         LineType;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Let's now create an Mesh and insert some points on it. Note
  //  that the dimension of the points matches the dimension of the Mesh. Here
  //  we insert a sequence of points that look like a plot of the $log()$
  //  function.
  //
  //  \index{itk::Mesh!New()}
  //  \index{itk::Mesh!SetPoint()}
  //  \index{itk::Mesh!PointType}
  //  \index{itk::Mesh!Pointer}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  MeshType::Pointer  mesh = MeshType::New();

  typedef MeshType::PointType PointType;
  PointType point;

  const unsigned int numberOfPoints = 10;
  for(unsigned int id=0; id<numberOfPoints; id++)
    {
    point[0] = 1.565;   // Initialize points here
    point[1] = 3.647;   // with arbitrary values
    point[2] = 4.129;
    mesh->SetPoint( id, point );
    }
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  A set of line cells is created and associated with the existing points by
  //  using point identifiers. In this simple case, the point identifiers can
  //  be deduced from cell identifiers since the line cells are ordered in the
  //  same way. Note that in the code above, the values assigned to point
  //  components are arbitrary. In a more realistic example, those values would
  //  be computed from another source.
  //
  //  \index{itk::AutoPointer!TakeOwnership()}
  //  \index{CellAutoPointer!TakeOwnership()}
  //  \index{CellType!creation}
  //  \index{itk::Mesh!SetCell()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  CellType::CellAutoPointer line;
  const unsigned int numberOfCells = numberOfPoints-1;
  for(unsigned int cellId=0; cellId<numberOfCells; cellId++)
    {
    line.TakeOwnership(  new LineType  );
    line->SetPointId( 0, cellId   ); // first point
    line->SetPointId( 1, cellId+1 ); // second point
    mesh->SetCell( cellId, line );   // insert the cell
    }
  // Software Guide : EndCodeSnippet

  std::cout << "Points = " << mesh->GetNumberOfPoints() << std::endl;
  std::cout << "Cells  = " << mesh->GetNumberOfCells()  << std::endl;

  //  Software Guide : BeginLatex
  //
  //  Data associated with cells is inserted in the Mesh by using the
  //  \code{SetCellData()} method.  It requires the user to provide an
  //  identifier and the value to be inserted. The identifier should match one
  //  of the inserted cells. In this example, we simply store a CellDataType
  //  dummy variable named \code{value}.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  for(unsigned int cellId=0; cellId<numberOfCells; cellId++)
    {
    CellDataType value;
    mesh->SetCellData( cellId, value );
    }

  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Cell data can be read from the Mesh with the
  //  \code{GetCellData()} method. It requires the user to provide the
  //  identifier of the cell for which the data is to be retrieved. The user
  //  should provide also a valid pointer to a location where the data can be
  //  copied.
  //
  //  \index{itk::Mesh!GetCellData()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  for(unsigned int cellId=0; cellId<numberOfCells; cellId++)
    {
    CellDataType value;
    mesh->GetCellData( cellId, &value );
    std::cout << "Cell " << cellId << " = " << value << std::endl;
    }
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Neither \code{SetCellData()} or \code{GetCellData()} are efficient ways
  //  to access cell data. Efficient access to cell data can be achieved
  //  by using the Iterators built into the CellDataContainer.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef MeshType::CellDataContainer::ConstIterator CellDataIterator;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Note that the \code{ConstIterator} is used here because the data is only
  //  going to be read.  This approach is exactly the same already illustrated
  //  for getting access to point data. The iterator to the first cell data
  //  item can be obtained with the \code{Begin()} method of the
  //  CellDataContainer. The past-end iterator is returned by the \code{End()}
  //  method. The cell data container itself can be obtained from the mesh with
  //  the method \code{GetCellData()}.
  //
  //  \index{itk::Mesh!Iterating cell data}
  //  \index{itk::Mesh!GetCellData()}
  //  \index{CellDataContainer!Begin()}
  //  \index{CellDataContainer!End()}
  //  \index{CellDataContainer!Iterator}
  //  \index{CellDataContainer!ConstIterator}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  CellDataIterator cellDataIterator  = mesh->GetCellData()->Begin();
  CellDataIterator end               = mesh->GetCellData()->End();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Finally a standard loop is used to iterate over all the cell data
  //  entries. Note the use of the \code{Value()} method used to get the actual
  //  value of the data entry. \code{PixelType} elements are returned by copy.
  //
  //  \index{CellDataIterator!Value()}
  //  \index{CellDataIterator!increment}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  while( cellDataIterator != end )
    {
    CellDataType cellValue = cellDataIterator.Value();
    std::cout << cellValue << std::endl;
    ++cellDataIterator;
    }
  // Software Guide : EndCodeSnippet

  return 0;
}

<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    GaussianDensityFunction.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

     Copyright (c) 2002 Insight Consortium. All rights reserved.
     See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/

// Software Guide : BeginLatex
//
// \index{Statistics!Guassian (normal) probability density function}
//
// \index{itk::Statistics::GaussianDensityFunction}
//
// The Gaussian probability density function
// (\subdoxygen{Statistics}{GaussianDensityFunction} requires two
// distribution parameters---the mean vector and the covariance matrix.
//
// We include the header files for the class and the \doxygen{Vector}.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkVector.h"
#include "itkGaussianDensityFunction.h"
// Software Guide : EndCodeSnippet

// Software Guide : BeginLatex
//
// We define the type of the measurement vector that will be input to
// the Gaussian density function.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
typedef itk::Vector< float, 2 > MeasurementVectorType;
// Software Guide : EndCodeSnippet

int main()
{
  // Software Guide : BeginLatex
  //
  // The instantiation of the function is done through the usual
  // \code{New()} method and a smart pointer.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::Statistics::GaussianDensityFunction< MeasurementVectorType >
    DensityFunctionType;
  DensityFunctionType::Pointer densityFunction = DensityFunctionType::New();
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // We create the two distribution parameters and set them. The mean is
  // [0, 0], and the covariance matrix is:
  // \[
  // \begin{pmatrix}
  // 4 & 0 \cr
  // 0 & 4
  // \end{pmatrix}
  // \]
  // We get the probability density for the measurement vector: [0, 0]
  // using the \code{Evaluate(measurement vector)} method and print it out.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  DensityFunctionType::MeanType mean;
  mean.Fill( 0.0 );

  DensityFunctionType::CovarianceType cov;
  cov.SetIdentity();
  cov *= 4;

  densityFunction->SetMean( &mean );
  densityFunction->SetCovariance( &cov );

  MeasurementVectorType mv;
  mv.Fill( 0 );

  std::cout << densityFunction->Evaluate( mv ) << std::endl;
  // Software Guide : EndCodeSnippet

  return 0;
}
<commit_msg>statistically speaking, this is better<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    GaussianDensityFunction.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

     Copyright (c) 2002 Insight Consortium. All rights reserved.
     See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/

// Software Guide : BeginLatex
//
// \index{Statistics!Guassian (normal) probability density function}
//
// \index{itk::Statistics::GaussianDensityFunction}
//
// The Gaussian probability density function
// (\subdoxygen{Statistics}{GaussianDensityFunction} requires two
// distribution parameters---the mean vector and the covariance matrix.
//
// We include the header files for the class and the \doxygen{Vector}.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkVector.h"
#include "itkGaussianDensityFunction.h"
// Software Guide : EndCodeSnippet

// Software Guide : BeginLatex
//
// We define the type of the measurement vector that will be input to
// the Gaussian density function.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
typedef itk::Vector< float, 2 > MeasurementVectorType;
// Software Guide : EndCodeSnippet

int main()
{
  // Software Guide : BeginLatex
  //
  // The instantiation of the function is done through the usual
  // \code{New()} method and a smart pointer.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::Statistics::GaussianDensityFunction< MeasurementVectorType >
    DensityFunctionType;
  DensityFunctionType::Pointer densityFunction = DensityFunctionType::New();
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // We create the two distribution parameters and set them. The mean is
  // [0, 0], and the covariance matrix is:
  // \[
  // \begin{pmatrix}
  // 4 & 0 \cr
  // 0 & 4
  // \end{pmatrix}
  // \]
  // We obtain the probability density for the measurement vector: [0, 0]
  // using the \code{Evaluate(measurement vector)} method and print it out.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  DensityFunctionType::MeanType mean;
  mean.Fill( 0.0 );

  DensityFunctionType::CovarianceType cov;
  cov.SetIdentity();
  cov *= 4;

  densityFunction->SetMean( &mean );
  densityFunction->SetCovariance( &cov );

  MeasurementVectorType mv;
  mv.Fill( 0 );

  std::cout << densityFunction->Evaluate( mv ) << std::endl;
  // Software Guide : EndCodeSnippet

  return 0;
}
<|endoftext|>


<commit_before>// OcxFileCtl.cpp : Implementation of the COcxFileCtrl ActiveX Control class.

#include "stdafx.h"
#include "OcxFile.h"
#include "OcxFileCtl.h"
#include "OcxFilePpg.h"
#include "RetMsg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

IMPLEMENT_DYNCREATE(COcxFileCtrl, COleControl)

/////////////////////////////////////////////////////////////////////////////
// Message map

BEGIN_MESSAGE_MAP(COcxFileCtrl, COleControl)
	//{{AFX_MSG_MAP(COcxFileCtrl)
	// NOTE - ClassWizard will add and remove message map entries
	//    DO NOT EDIT what you see in these blocks of generated code !
	//}}AFX_MSG_MAP
	ON_OLEVERB(AFX_IDS_VERB_PROPERTIES, OnProperties)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// Dispatch map

BEGIN_DISPATCH_MAP(COcxFileCtrl, COleControl)
	//{{AFX_DISPATCH_MAP(COcxFileCtrl)
	DISP_FUNCTION(COcxFileCtrl, "create", create, VT_BSTR, VTS_BSTR)
	DISP_FUNCTION(COcxFileCtrl, "read", read, VT_BSTR, VTS_BSTR)
	//}}AFX_DISPATCH_MAP
	DISP_FUNCTION_ID(COcxFileCtrl, "AboutBox", DISPID_ABOUTBOX, AboutBox, VT_EMPTY, VTS_NONE)
END_DISPATCH_MAP()

/////////////////////////////////////////////////////////////////////////////
// Event map

BEGIN_EVENT_MAP(COcxFileCtrl, COleControl)
	//{{AFX_EVENT_MAP(COcxFileCtrl)
	// NOTE - ClassWizard will add and remove event map entries
	//    DO NOT EDIT what you see in these blocks of generated code !
	//}}AFX_EVENT_MAP
END_EVENT_MAP()

/////////////////////////////////////////////////////////////////////////////
// Property pages

// TODO: Add more property pages as needed.  Remember to increase the count!
BEGIN_PROPPAGEIDS(COcxFileCtrl, 1)
	PROPPAGEID(COcxFilePropPage::guid)
END_PROPPAGEIDS(COcxFileCtrl)

/////////////////////////////////////////////////////////////////////////////
// Initialize class factory and guid

IMPLEMENT_OLECREATE_EX(COcxFileCtrl, "OCXFILE.OcxFileCtrl.1",
	0x3f08c971, 0x449f, 0x4588, 0x85, 0x3f, 0x9e, 0x25, 0xdd, 0x73, 0x87, 0x9b)

/////////////////////////////////////////////////////////////////////////////
// Type library ID and version

IMPLEMENT_OLETYPELIB(COcxFileCtrl, _tlid, _wVerMajor, _wVerMinor)

/////////////////////////////////////////////////////////////////////////////
// Interface IDs

const IID BASED_CODE IID_DOcxFile =
		{ 0xb29222ea, 0x7db7, 0x4f0a, { 0xaf, 0x18, 0x79, 0x3f, 0xcc, 0xf, 0x23, 0x9 } };
const IID BASED_CODE IID_DOcxFileEvents =
		{ 0xf0b787d0, 0x2d92, 0x4fe1, { 0x9d, 0xf3, 0xce, 0x7d, 0xd3, 0xd, 0xf1, 0x8f } };

/////////////////////////////////////////////////////////////////////////////
// Control type information

static const DWORD BASED_CODE _dwOcxFileOleMisc =
	OLEMISC_ACTIVATEWHENVISIBLE |
	OLEMISC_SETCLIENTSITEFIRST |
	OLEMISC_INSIDEOUT |
	OLEMISC_CANTLINKINSIDE |
	OLEMISC_RECOMPOSEONRESIZE;

IMPLEMENT_OLECTLTYPE(COcxFileCtrl, IDS_OCXFILE, _dwOcxFileOleMisc)

// ͨú

//
void logForPrj ( char *desc )
{
	HANDLE hFile;
	int writeLen, len;
	SYSTEMTIME st;
	char buf[256];

	GetLocalTime ( &st );
	sprintf ( buf, "C:\\LOG\\%04d%02d%02d.log",
			  st.wYear, st.wMonth, st.wDay );
	hFile = CreateFile(buf, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if(hFile == INVALID_HANDLE_VALUE)
		return;
	SetFilePointer(hFile, 0, NULL, FILE_END);

	sprintf ( buf, "[%04d-%02d-%02d %02d:%02d:%02d] ",
			  st.wYear, st.wMonth, st.wDay,
			  st.wHour, st.wMinute, st.wSecond );
	WriteFile(hFile, buf, strlen ( buf ), (LPDWORD)&writeLen, NULL);

	len = strlen ( desc );
	WriteFile(hFile, desc, len, (LPDWORD)&writeLen, NULL);
	WriteFile(hFile, "\r\n", 2, (LPDWORD)&writeLen, NULL);
	CloseHandle(hFile);
}

void logForPrjEx ( char *format, ... )
{
	char buf[512];
	va_list args;

	va_start ( args, format );
	vsprintf ( buf, format, args );
	va_end ( args );

	logForPrj ( buf );
}

CString Hex2Str(char * buff, DWORD len )
{
	DWORD strlen = len*2;
	char str[3];
	CString ret="";
	for(DWORD i=0; i< len; i++)
	{
		sprintf(str,"%0X",buff[i]);
		ret += str;
	}
	return ret;
}

/////////////////////////////////////////////////////////////////////////////
// COcxFileCtrl::COcxFileCtrlFactory::UpdateRegistry -
// Adds or removes system registry entries for COcxFileCtrl

BOOL COcxFileCtrl::COcxFileCtrlFactory::UpdateRegistry(BOOL bRegister)
{
	// TODO: Verify that your control follows apartment-model threading rules.
	// Refer to MFC TechNote 64 for more information.
	// If your control does not conform to the apartment-model rules, then
	// you must modify the code below, changing the 6th parameter from
	// afxRegApartmentThreading to 0.

	if (bRegister)
		return AfxOleRegisterControlClass(
			AfxGetInstanceHandle(),
			m_clsid,
			m_lpszProgID,
			IDS_OCXFILE,
			IDB_OCXFILE,
			afxRegApartmentThreading,
			_dwOcxFileOleMisc,
			_tlid,
			_wVerMajor,
			_wVerMinor);
	else
		return AfxOleUnregisterClass(m_clsid, m_lpszProgID);
}

/////////////////////////////////////////////////////////////////////////////
// COcxFileCtrl::COcxFileCtrl - Constructor

COcxFileCtrl::COcxFileCtrl()
{
	InitializeIIDs(&IID_DOcxFile, &IID_DOcxFileEvents);

	// TODO: Initialize your control's instance data here.
}

/////////////////////////////////////////////////////////////////////////////
// COcxFileCtrl::~COcxFileCtrl - Destructor

COcxFileCtrl::~COcxFileCtrl()
{
	// TODO: Cleanup your control's instance data here.
}

/////////////////////////////////////////////////////////////////////////////
// COcxFileCtrl::OnDraw - Drawing function

void COcxFileCtrl::OnDraw(
			CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid)
{
	// TODO: Replace the following code with your own drawing code.
	pdc->FillRect(rcBounds, CBrush::FromHandle((HBRUSH)GetStockObject(WHITE_BRUSH)));
	pdc->Ellipse(rcBounds);
}

/////////////////////////////////////////////////////////////////////////////
// COcxFileCtrl::DoPropExchange - Persistence support

void COcxFileCtrl::DoPropExchange(CPropExchange* pPX)
{
	ExchangeVersion(pPX, MAKELONG(_wVerMinor, _wVerMajor));
	COleControl::DoPropExchange(pPX);

	// TODO: Call PX_ functions for each persistent custom property.

}

/////////////////////////////////////////////////////////////////////////////
// COcxFileCtrl::OnResetState - Reset control to default state

void COcxFileCtrl::OnResetState()
{
	COleControl::OnResetState();  // Resets defaults found in DoPropExchange

	// TODO: Reset any other control state here.
}

/////////////////////////////////////////////////////////////////////////////
// COcxFileCtrl::AboutBox - Display an "About" box to the user

void COcxFileCtrl::AboutBox()
{
	CDialog dlgAbout(IDD_ABOUTBOX_OCXFILE);
	dlgAbout.DoModal();
}

/////////////////////////////////////////////////////////////////////////////
// COcxFileCtrl message handlers

BSTR COcxFileCtrl::create(LPCTSTR path)
{
	CString strResult;
	// TODO: Add your dispatch handler code here
	HANDLE hFile;
	CRetMsg ret;
	logForPrjEx("path:%s", path);
	hFile = CreateFile(path, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
	if(hFile == INVALID_HANDLE_VALUE)
		ret.retcode = GetLastError();
		ret.retmsg = "fail";
	CloseHandle(hFile);
	ret.retcode = 0;
	ret.retmsg = "success";
	strResult = ret.toJson();
	return strResult.AllocSysString();
}

BSTR COcxFileCtrl::read(LPCTSTR file)
{
	CString strResult;
	// TODO: Add your dispatch handler code here
    HANDLE pfile;
	CRetMsg ret;
	logForPrjEx("read file:%s", file);
    pfile = ::CreateFile(file, GENERIC_READ, 0, NULL, OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL, NULL);    //OpenFile
    if(pfile == INVALID_HANDLE_VALUE)
    {
		ret.retcode = GetLastError();
		ret.retmsg = "fail";
    }
	else
	{
		// ļݶȡ
		DWORD filesize = GetFileSize(pfile, NULL);
		char *buffer = new char[filesize+1];
		DWORD readsize;
		ReadFile(pfile, buffer, filesize, &readsize, NULL);
		buffer[filesize] = 0;
		logForPrjEx("ݶȡ");

		// ַת
		ret.retmsg = Hex2Str(buffer,filesize);
		ret.retcode = 0;
		logForPrjEx("ת");

		delete[] buffer;
	}

	// ͷԴ
	CloseHandle(pfile);

	strResult = ret.toJson();
	return strResult.AllocSysString();
}
<commit_msg>添加字符串和数据相互转换函数<commit_after>// OcxFileCtl.cpp : Implementation of the COcxFileCtrl ActiveX Control class.

#include "stdafx.h"
#include "OcxFile.h"
#include "OcxFileCtl.h"
#include "OcxFilePpg.h"
#include "RetMsg.h"

#include "string.h"
#include "stdlib.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

IMPLEMENT_DYNCREATE(COcxFileCtrl, COleControl)

/////////////////////////////////////////////////////////////////////////////
// Message map

BEGIN_MESSAGE_MAP(COcxFileCtrl, COleControl)
	//{{AFX_MSG_MAP(COcxFileCtrl)
	// NOTE - ClassWizard will add and remove message map entries
	//    DO NOT EDIT what you see in these blocks of generated code !
	//}}AFX_MSG_MAP
	ON_OLEVERB(AFX_IDS_VERB_PROPERTIES, OnProperties)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// Dispatch map

BEGIN_DISPATCH_MAP(COcxFileCtrl, COleControl)
	//{{AFX_DISPATCH_MAP(COcxFileCtrl)
	DISP_FUNCTION(COcxFileCtrl, "create", create, VT_BSTR, VTS_BSTR)
	DISP_FUNCTION(COcxFileCtrl, "read", read, VT_BSTR, VTS_BSTR)
	//}}AFX_DISPATCH_MAP
	DISP_FUNCTION_ID(COcxFileCtrl, "AboutBox", DISPID_ABOUTBOX, AboutBox, VT_EMPTY, VTS_NONE)
END_DISPATCH_MAP()

/////////////////////////////////////////////////////////////////////////////
// Event map

BEGIN_EVENT_MAP(COcxFileCtrl, COleControl)
	//{{AFX_EVENT_MAP(COcxFileCtrl)
	// NOTE - ClassWizard will add and remove event map entries
	//    DO NOT EDIT what you see in these blocks of generated code !
	//}}AFX_EVENT_MAP
END_EVENT_MAP()

/////////////////////////////////////////////////////////////////////////////
// Property pages

// TODO: Add more property pages as needed.  Remember to increase the count!
BEGIN_PROPPAGEIDS(COcxFileCtrl, 1)
	PROPPAGEID(COcxFilePropPage::guid)
END_PROPPAGEIDS(COcxFileCtrl)

/////////////////////////////////////////////////////////////////////////////
// Initialize class factory and guid

IMPLEMENT_OLECREATE_EX(COcxFileCtrl, "OCXFILE.OcxFileCtrl.1",
	0x3f08c971, 0x449f, 0x4588, 0x85, 0x3f, 0x9e, 0x25, 0xdd, 0x73, 0x87, 0x9b)

/////////////////////////////////////////////////////////////////////////////
// Type library ID and version

IMPLEMENT_OLETYPELIB(COcxFileCtrl, _tlid, _wVerMajor, _wVerMinor)

/////////////////////////////////////////////////////////////////////////////
// Interface IDs

const IID BASED_CODE IID_DOcxFile =
		{ 0xb29222ea, 0x7db7, 0x4f0a, { 0xaf, 0x18, 0x79, 0x3f, 0xcc, 0xf, 0x23, 0x9 } };
const IID BASED_CODE IID_DOcxFileEvents =
		{ 0xf0b787d0, 0x2d92, 0x4fe1, { 0x9d, 0xf3, 0xce, 0x7d, 0xd3, 0xd, 0xf1, 0x8f } };

/////////////////////////////////////////////////////////////////////////////
// Control type information

static const DWORD BASED_CODE _dwOcxFileOleMisc =
	OLEMISC_ACTIVATEWHENVISIBLE |
	OLEMISC_SETCLIENTSITEFIRST |
	OLEMISC_INSIDEOUT |
	OLEMISC_CANTLINKINSIDE |
	OLEMISC_RECOMPOSEONRESIZE;

IMPLEMENT_OLECTLTYPE(COcxFileCtrl, IDS_OCXFILE, _dwOcxFileOleMisc)

// ͨú

//
void logForPrj ( char *desc )
{
	HANDLE hFile;
	int writeLen, len;
	SYSTEMTIME st;
	char buf[256];

	GetLocalTime ( &st );
	sprintf ( buf, "C:\\LOG\\%04d%02d%02d.log",
			  st.wYear, st.wMonth, st.wDay );
	hFile = CreateFile(buf, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if(hFile == INVALID_HANDLE_VALUE)
		return;
	SetFilePointer(hFile, 0, NULL, FILE_END);

	sprintf ( buf, "[%04d-%02d-%02d %02d:%02d:%02d] ",
			  st.wYear, st.wMonth, st.wDay,
			  st.wHour, st.wMinute, st.wSecond );
	WriteFile(hFile, buf, strlen ( buf ), (LPDWORD)&writeLen, NULL);

	len = strlen ( desc );
	WriteFile(hFile, desc, len, (LPDWORD)&writeLen, NULL);
	WriteFile(hFile, "\r\n", 2, (LPDWORD)&writeLen, NULL);
	CloseHandle(hFile);
}

void logForPrjEx ( char *format, ... )
{
	char buf[512];
	va_list args;

	va_start ( args, format );
	vsprintf ( buf, format, args );
	va_end ( args );

	logForPrj ( buf );
}

// תʮַ
// buff -
// len - ݸ
// ַ
CString Array2HexString (char * buff, DWORD len )
{
	DWORD strlen = len*2;
	char str[3];
	CString ret="";
	for(DWORD i=0; i< len; i++)
	{
		sprintf(str,"%0X",buff[i]);
		ret += str;
	}
	return ret;
}

// ʮַת
//
// ַ
// ɹתĸ
int HexString2Array(char *buff,char *str)
{
	int i;
	int len = strlen(str);
	char slice[3];
	if( len % 2 )
	{
		return -1;
	}
	for( i=0 ; i<len ; i+=2 )
	{
		memcpy(slice,str+i,2);
		slice[2] = 0;
		buff[i/2] = 0xFF & strtol(slice, NULL, 16);
	}
	return i/2;
}

/////////////////////////////////////////////////////////////////////////////
// COcxFileCtrl::COcxFileCtrlFactory::UpdateRegistry -
// Adds or removes system registry entries for COcxFileCtrl

BOOL COcxFileCtrl::COcxFileCtrlFactory::UpdateRegistry(BOOL bRegister)
{
	// TODO: Verify that your control follows apartment-model threading rules.
	// Refer to MFC TechNote 64 for more information.
	// If your control does not conform to the apartment-model rules, then
	// you must modify the code below, changing the 6th parameter from
	// afxRegApartmentThreading to 0.

	if (bRegister)
		return AfxOleRegisterControlClass(
			AfxGetInstanceHandle(),
			m_clsid,
			m_lpszProgID,
			IDS_OCXFILE,
			IDB_OCXFILE,
			afxRegApartmentThreading,
			_dwOcxFileOleMisc,
			_tlid,
			_wVerMajor,
			_wVerMinor);
	else
		return AfxOleUnregisterClass(m_clsid, m_lpszProgID);
}

/////////////////////////////////////////////////////////////////////////////
// COcxFileCtrl::COcxFileCtrl - Constructor

COcxFileCtrl::COcxFileCtrl()
{
	InitializeIIDs(&IID_DOcxFile, &IID_DOcxFileEvents);

	// TODO: Initialize your control's instance data here.
}

/////////////////////////////////////////////////////////////////////////////
// COcxFileCtrl::~COcxFileCtrl - Destructor

COcxFileCtrl::~COcxFileCtrl()
{
	// TODO: Cleanup your control's instance data here.
}

/////////////////////////////////////////////////////////////////////////////
// COcxFileCtrl::OnDraw - Drawing function

void COcxFileCtrl::OnDraw(
			CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid)
{
	// TODO: Replace the following code with your own drawing code.
	pdc->FillRect(rcBounds, CBrush::FromHandle((HBRUSH)GetStockObject(WHITE_BRUSH)));
	pdc->Ellipse(rcBounds);
}

/////////////////////////////////////////////////////////////////////////////
// COcxFileCtrl::DoPropExchange - Persistence support

void COcxFileCtrl::DoPropExchange(CPropExchange* pPX)
{
	ExchangeVersion(pPX, MAKELONG(_wVerMinor, _wVerMajor));
	COleControl::DoPropExchange(pPX);

	// TODO: Call PX_ functions for each persistent custom property.

}

/////////////////////////////////////////////////////////////////////////////
// COcxFileCtrl::OnResetState - Reset control to default state

void COcxFileCtrl::OnResetState()
{
	COleControl::OnResetState();  // Resets defaults found in DoPropExchange

	// TODO: Reset any other control state here.
}

/////////////////////////////////////////////////////////////////////////////
// COcxFileCtrl::AboutBox - Display an "About" box to the user

void COcxFileCtrl::AboutBox()
{
	CDialog dlgAbout(IDD_ABOUTBOX_OCXFILE);
	dlgAbout.DoModal();
}

/////////////////////////////////////////////////////////////////////////////
// COcxFileCtrl message handlers

// ļ
BSTR COcxFileCtrl::create(LPCTSTR path)
{
	CString strResult;
	// TODO: Add your dispatch handler code here
	HANDLE hFile;
	CRetMsg ret;
	logForPrjEx("path:%s", path);
	hFile = CreateFile(path, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
	if(hFile == INVALID_HANDLE_VALUE)
		ret.retcode = GetLastError();
		ret.retmsg = "fail";
	CloseHandle(hFile);
	ret.retcode = 0;
	ret.retmsg = "success";
	strResult = ret.toJson();
	return strResult.AllocSysString();
}

// ļݶȡ
BSTR COcxFileCtrl::read(LPCTSTR file)
{
	CString strResult;
	// TODO: Add your dispatch handler code here
    HANDLE pfile;
	CRetMsg ret;
	logForPrjEx("read file:%s", file);
    pfile = ::CreateFile(file, GENERIC_READ, 0, NULL, OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL, NULL);
    if(pfile == INVALID_HANDLE_VALUE)
    {
		ret.retcode = GetLastError();
		ret.retmsg = "fail";
    }
	else
	{
		// ļݶȡ
		DWORD filesize = GetFileSize(pfile, NULL);
		char *buffer = new char[filesize+1];
		DWORD readsize;
		ReadFile(pfile, buffer, filesize, &readsize, NULL);
		buffer[filesize] = 0;
		logForPrjEx("ݶȡ");

		// ַת
		ret.retmsg = Array2HexString (buffer,filesize);
		ret.retcode = 0;
		logForPrjEx("ת");

		delete[] buffer;
	}

	// ͷԴ
	CloseHandle(pfile);

	strResult = ret.toJson();
	return strResult.AllocSysString();
}
<|endoftext|>


<commit_before><commit_msg>[generator] Fixed ordering.<commit_after><|endoftext|>


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

#ifdef _WIN32
#include <windows.h> /* for GetFullPathName */
#endif

#include <boost/filesystem.hpp>

#include <thrift/compiler/platform.h>

namespace apache {
namespace thrift {
namespace compiler {

/**
 * Current compilation stage. One of: arguments, parse, generation
 */
std::string g_stage;

/**
 * Directory containing template files
 */
std::string g_template_dir;

/**
 * Should C++ include statements use path prefixes for other thrift-generated
 * header files
 */
bool g_cpp_use_include_prefix = false;

/**
 * Global debug state
 */
int g_debug = 0;

/**
 * Warning level
 */
int g_warn = 1;

/**
 * Verbose output
 */
int g_verbose = 0;

/**
 * The last parsed doctext comment.
 */
char* g_doctext;

/**
 * The location of the last parsed doctext comment.
 */
int g_doctext_lineno;

std::string compute_absolute_path(const std::string& path) {
  boost::filesystem::path abspath{path};
  try {
    abspath = boost::filesystem::canonical(abspath);
    return abspath.string();
  } catch (const boost::filesystem::filesystem_error& e) {
    failure("Could not find file: %s. Error: %s", path.c_str(), e.what());
  }
}

void pdebug(const char* fmt, ...) {
  if (g_debug == 0) {
    return;
  }
  va_list args;
  printf("[PARSE] ");
  va_start(args, fmt);
  vprintf(fmt, args);
  va_end(args);
  printf("\n");
}

void pverbose(const char* fmt, ...) {
  if (g_verbose == 0) {
    return;
  }
  va_list args;
  va_start(args, fmt);
  vprintf(fmt, args);
  va_end(args);
}

void pwarning(int level, const char* fmt, ...) {
  if (g_warn < level) {
    return;
  }
  va_list args;
  fprintf(stderr, "[WARNING:%s] ", g_stage.c_str());
  va_start(args, fmt);
  vfprintf(stderr, fmt, args);
  va_end(args);
  fprintf(stderr, "\n");
}

[[noreturn]] void failure(const char* fmt, ...) {
  va_list args;
  fprintf(stderr, "[FAILURE:%s] ", g_stage.c_str());
  va_start(args, fmt);
  vfprintf(stderr, fmt, args);
  va_end(args);
  fprintf(stderr, "\n");
  exit(1);
}

void dump_docstrings(t_program* program) {
  std::string progdoc = program->get_doc();
  if (!progdoc.empty()) {
    printf("Whole program doc:\n%s\n", progdoc.c_str());
  }
  const std::vector<t_typedef*>& typedefs = program->get_typedefs();
  std::vector<t_typedef*>::const_iterator t_iter;
  for (t_iter = typedefs.begin(); t_iter != typedefs.end(); ++t_iter) {
    t_typedef* td = *t_iter;
    if (td->has_doc()) {
      printf(
          "typedef %s:\n%s\n", td->get_name().c_str(), td->get_doc().c_str());
    }
  }
  const std::vector<t_enum*>& enums = program->get_enums();
  std::vector<t_enum*>::const_iterator e_iter;
  for (e_iter = enums.begin(); e_iter != enums.end(); ++e_iter) {
    t_enum* en = *e_iter;
    if (en->has_doc()) {
      printf("enum %s:\n%s\n", en->get_name().c_str(), en->get_doc().c_str());
    }
  }
  const std::vector<t_const*>& consts = program->get_consts();
  std::vector<t_const*>::const_iterator c_iter;
  for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
    t_const* co = *c_iter;
    if (co->has_doc()) {
      printf("const %s:\n%s\n", co->get_name().c_str(), co->get_doc().c_str());
    }
  }
  const std::vector<t_struct*>& structs = program->get_structs();
  std::vector<t_struct*>::const_iterator s_iter;
  for (s_iter = structs.begin(); s_iter != structs.end(); ++s_iter) {
    t_struct* st = *s_iter;
    if (st->has_doc()) {
      printf("struct %s:\n%s\n", st->get_name().c_str(), st->get_doc().c_str());
    }
  }
  const std::vector<t_struct*>& xceptions = program->get_xceptions();
  std::vector<t_struct*>::const_iterator x_iter;
  for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
    t_struct* xn = *x_iter;
    if (xn->has_doc()) {
      printf(
          "xception %s:\n%s\n", xn->get_name().c_str(), xn->get_doc().c_str());
    }
  }
  const std::vector<t_service*>& services = program->get_services();
  std::vector<t_service*>::const_iterator v_iter;
  for (v_iter = services.begin(); v_iter != services.end(); ++v_iter) {
    t_service* sv = *v_iter;
    if (sv->has_doc()) {
      printf(
          "service %s:\n%s\n", sv->get_name().c_str(), sv->get_doc().c_str());
    }
  }
}

/**
 * Parse with the given parameters, and dump all the diagnostic messages
 * returned.
 *
 * If the parsing fails, this function will exit(1).
 */
std::unique_ptr<t_program_bundle> parse_and_dump_diagnostics(
    std::string path,
    apache::thrift::parsing_params params) {
  apache::thrift::parsing_driver driver{path, std::move(params)};

  std::vector<apache::thrift::diagnostic_message> diagnostic_messages;
  auto program = driver.parse(diagnostic_messages);

  for (auto const& message : diagnostic_messages) {
    switch (message.level) {
      case apache::thrift::diagnostic_level::YY_ERROR:
        fprintf(
            stderr,
            "[ERROR:%s:%d] (last token was '%s')\n%s\n",
            message.filename.c_str(),
            message.lineno,
            message.last_token.c_str(),
            message.message.c_str());
        break;
      case apache::thrift::diagnostic_level::WARNING:
        fprintf(
            stderr,
            "[WARNING:%s:%d] %s\n",
            message.filename.c_str(),
            message.lineno,
            message.message.c_str());
        break;
      case apache::thrift::diagnostic_level::VERBOSE:
        fprintf(stderr, "%s", message.message.c_str());
        break;
      case apache::thrift::diagnostic_level::DEBUG:
        fprintf(
            stderr, "[PARSE:%d] %s\n", message.lineno, message.message.c_str());
        break;
      case apache::thrift::diagnostic_level::FAILURE:
        fprintf(
            stderr,
            "[FAILURE:%s:%d] %s\n",
            message.filename.c_str(),
            message.lineno,
            message.message.c_str());
        break;
    }
  }

  if (!program) {
    exit(1);
  }

  return program;
}

void mark_file_executable(std::string const& path) {
  namespace fs = boost::filesystem;
  fs::permissions(
      path, fs::add_perms | fs::owner_exe | fs::group_exe | fs::others_exe);
}

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

#include <boost/filesystem.hpp>

#include <thrift/compiler/platform.h>

namespace apache {
namespace thrift {
namespace compiler {

/**
 * Current compilation stage. One of: arguments, parse, generation
 */
std::string g_stage;

/**
 * Directory containing template files
 */
std::string g_template_dir;

/**
 * Should C++ include statements use path prefixes for other thrift-generated
 * header files
 */
bool g_cpp_use_include_prefix = false;

/**
 * Global debug state
 */
int g_debug = 0;

/**
 * Warning level
 */
int g_warn = 1;

/**
 * Verbose output
 */
int g_verbose = 0;

/**
 * The last parsed doctext comment.
 */
char* g_doctext;

/**
 * The location of the last parsed doctext comment.
 */
int g_doctext_lineno;

std::string compute_absolute_path(const std::string& path) {
  boost::filesystem::path abspath{path};
  try {
    abspath = boost::filesystem::canonical(abspath);
    return abspath.string();
  } catch (const boost::filesystem::filesystem_error& e) {
    failure("Could not find file: %s. Error: %s", path.c_str(), e.what());
  }
}

void pdebug(const char* fmt, ...) {
  if (g_debug == 0) {
    return;
  }
  va_list args;
  printf("[PARSE] ");
  va_start(args, fmt);
  vprintf(fmt, args);
  va_end(args);
  printf("\n");
}

void pverbose(const char* fmt, ...) {
  if (g_verbose == 0) {
    return;
  }
  va_list args;
  va_start(args, fmt);
  vprintf(fmt, args);
  va_end(args);
}

void pwarning(int level, const char* fmt, ...) {
  if (g_warn < level) {
    return;
  }
  va_list args;
  fprintf(stderr, "[WARNING:%s] ", g_stage.c_str());
  va_start(args, fmt);
  vfprintf(stderr, fmt, args);
  va_end(args);
  fprintf(stderr, "\n");
}

[[noreturn]] void failure(const char* fmt, ...) {
  va_list args;
  fprintf(stderr, "[FAILURE:%s] ", g_stage.c_str());
  va_start(args, fmt);
  vfprintf(stderr, fmt, args);
  va_end(args);
  fprintf(stderr, "\n");
  exit(1);
}

void dump_docstrings(t_program* program) {
  std::string progdoc = program->get_doc();
  if (!progdoc.empty()) {
    printf("Whole program doc:\n%s\n", progdoc.c_str());
  }
  const std::vector<t_typedef*>& typedefs = program->get_typedefs();
  std::vector<t_typedef*>::const_iterator t_iter;
  for (t_iter = typedefs.begin(); t_iter != typedefs.end(); ++t_iter) {
    t_typedef* td = *t_iter;
    if (td->has_doc()) {
      printf(
          "typedef %s:\n%s\n", td->get_name().c_str(), td->get_doc().c_str());
    }
  }
  const std::vector<t_enum*>& enums = program->get_enums();
  std::vector<t_enum*>::const_iterator e_iter;
  for (e_iter = enums.begin(); e_iter != enums.end(); ++e_iter) {
    t_enum* en = *e_iter;
    if (en->has_doc()) {
      printf("enum %s:\n%s\n", en->get_name().c_str(), en->get_doc().c_str());
    }
  }
  const std::vector<t_const*>& consts = program->get_consts();
  std::vector<t_const*>::const_iterator c_iter;
  for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
    t_const* co = *c_iter;
    if (co->has_doc()) {
      printf("const %s:\n%s\n", co->get_name().c_str(), co->get_doc().c_str());
    }
  }
  const std::vector<t_struct*>& structs = program->get_structs();
  std::vector<t_struct*>::const_iterator s_iter;
  for (s_iter = structs.begin(); s_iter != structs.end(); ++s_iter) {
    t_struct* st = *s_iter;
    if (st->has_doc()) {
      printf("struct %s:\n%s\n", st->get_name().c_str(), st->get_doc().c_str());
    }
  }
  const std::vector<t_struct*>& xceptions = program->get_xceptions();
  std::vector<t_struct*>::const_iterator x_iter;
  for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
    t_struct* xn = *x_iter;
    if (xn->has_doc()) {
      printf(
          "xception %s:\n%s\n", xn->get_name().c_str(), xn->get_doc().c_str());
    }
  }
  const std::vector<t_service*>& services = program->get_services();
  std::vector<t_service*>::const_iterator v_iter;
  for (v_iter = services.begin(); v_iter != services.end(); ++v_iter) {
    t_service* sv = *v_iter;
    if (sv->has_doc()) {
      printf(
          "service %s:\n%s\n", sv->get_name().c_str(), sv->get_doc().c_str());
    }
  }
}

/**
 * Parse with the given parameters, and dump all the diagnostic messages
 * returned.
 *
 * If the parsing fails, this function will exit(1).
 */
std::unique_ptr<t_program_bundle> parse_and_dump_diagnostics(
    std::string path,
    apache::thrift::parsing_params params) {
  apache::thrift::parsing_driver driver{path, std::move(params)};

  std::vector<apache::thrift::diagnostic_message> diagnostic_messages;
  auto program = driver.parse(diagnostic_messages);

  for (auto const& message : diagnostic_messages) {
    switch (message.level) {
      case apache::thrift::diagnostic_level::YY_ERROR:
        fprintf(
            stderr,
            "[ERROR:%s:%d] (last token was '%s')\n%s\n",
            message.filename.c_str(),
            message.lineno,
            message.last_token.c_str(),
            message.message.c_str());
        break;
      case apache::thrift::diagnostic_level::WARNING:
        fprintf(
            stderr,
            "[WARNING:%s:%d] %s\n",
            message.filename.c_str(),
            message.lineno,
            message.message.c_str());
        break;
      case apache::thrift::diagnostic_level::VERBOSE:
        fprintf(stderr, "%s", message.message.c_str());
        break;
      case apache::thrift::diagnostic_level::DEBUG:
        fprintf(
            stderr, "[PARSE:%d] %s\n", message.lineno, message.message.c_str());
        break;
      case apache::thrift::diagnostic_level::FAILURE:
        fprintf(
            stderr,
            "[FAILURE:%s:%d] %s\n",
            message.filename.c_str(),
            message.lineno,
            message.message.c_str());
        break;
    }
  }

  if (!program) {
    exit(1);
  }

  return program;
}

void mark_file_executable(std::string const& path) {
  namespace fs = boost::filesystem;
  fs::permissions(
      path, fs::add_perms | fs::owner_exe | fs::group_exe | fs::others_exe);
}

} // namespace compiler
} // namespace thrift
} // namespace apache
<|endoftext|>