<commit_before>/*************************************************************************
 *                                                                       *
 * Open Dynamics Engine, Copyright (C) 2001 Russell L. Smith.            *
 *                                                                       *
 * This library is free software; you can redistribute it and/or         *
 * modify it under the terms of the GNU Lesser General Public            *
 * License as published by the Free Software Foundation; either          *
 * version 2.1 of the License, or (at your option) any later version.    *
 *                                                                       *
 * This library is distributed in the hope that it will be useful,       *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      *
 * Lesser General Public License for more details.                       *
 *                                                                       *
 * You should have received a copy of the GNU Lesser General Public      *
 * License along with this library (see the file LICENSE.TXT); if not,   *
 * write to the Free Software Foundation, Inc., 59 Temple Place,         *
 * Suite 330, Boston, MA 02111-1307 USA.                                 *
 *                                                                       *
 *************************************************************************/

#include <stdio.h>
#include "ode/ode.h"
#include "drawstuff/drawstuff.h"

// select correct drawing functions

#ifdef dDOUBLE
#define dsDrawBox dsDrawBoxD
#define dsDrawSphere dsDrawSphereD
#define dsDrawCylinder dsDrawCylinderD
#define dsDrawCappedCylinder dsDrawCappedCylinderD
#endif

// some constants

#define LENGTH 0.7	// chassis length
#define WIDTH 0.5	// chassis width
#define HEIGHT 0.2	// chassis height
#define RADIUS 0.18	// wheel radius
#define STARTZ 0.5	// starting height of chassis
#define CMASS 1		// chassis mass
#define WMASS 0.2	// wheel mass

// dynamics and collision objects (chassis, 3 wheels, environment)

static dWorldID world;
static dSpaceID space;
static dBodyID body[4];
static dJointID joint[3];	// joint[0] is the front wheel
static dJointGroupID contactgroup;
static dGeomID ground;
static dGeomID box[1];
static dGeomID sphere[3];
static dGeomID ground_box;

// things that the user controls

static dReal speed=0,steer=0;	// user commands

// this is called by dSpaceCollide when two objects in space are
// potentially colliding.

static void nearCallback (void *data, dGeomID o1, dGeomID o2)
{
  // only collide things with the ground
  int g1 = (o1 == ground || o1 == ground_box);
  int g2 = (o2 == ground || o2 == ground_box);
  if (!(g1 ^ g2)) return;

  dContact contact;
  contact.surface.mode = dContactSlip1 | dContactSlip2 |
    dContactSoftErp | dContactSoftCfm;
  contact.surface.mu = dInfinity;
  contact.surface.slip1 = 0.1;
  contact.surface.slip2 = 0.1;
  contact.surface.soft_erp = 0.5;
  contact.surface.soft_cfm = 0.3;
  if (dCollide (o1,o2,0,&contact.geom,sizeof(dContactGeom))) {
    //    if (o1==ground_box) printf ("foo 1\n");
    //    if (o2==ground_box) printf ("foo 2\n");

    dJointID c = dJointCreateContact (world,contactgroup,&contact);
    dJointAttach (c,dGeomGetBody(o1),dGeomGetBody(o2));
  }
}

// start simulation - set viewpoint

static void start()
{
  static float xyz[3] = {0.8317,-0.9817,0.8000};
  static float hpr[3] = {121.0000,-27.5000,0.0000};
  dsSetViewpoint (xyz,hpr);
  printf ("Press:\t'a' to increase speed.\n"
	  "\t'z' to decrease speed.\n"
	  "\t',' to steer left.\n"
	  "\t'.' to steer right.\n");
}

// called when a key pressed

static void command (int cmd)
{
  switch (cmd) {
  case 'a': case 'A':
    speed += 0.3;
    break;
  case 'z': case 'Z':
    speed -= 0.3;
    break;
  case ',':
    steer -= 0.5;
    break;
  case '.':
    steer += 0.5;
    break;
  case ' ':
    speed = 0;
    steer = 0;
    break;
  }
}

// simulation loop

static void simLoop (int pause)
{
  int i;
  if (!pause) {
    // motor
    dJointSetHinge2Param (joint[0],dParamVel2,-speed);
    dJointSetHinge2Param (joint[0],dParamFMax2,0.1);

    // steering
    dReal v = steer - dJointGetHinge2Angle1 (joint[0]);
    if (v > 0.1) v = 0.1;
    if (v < -0.1) v = -0.1;
    v *= 10.0;
    dJointSetHinge2Param (joint[0],dParamVel,v);
    dJointSetHinge2Param (joint[0],dParamFMax,0.2);
    dJointSetHinge2Param (joint[0],dParamLoStop,-0.75);
    dJointSetHinge2Param (joint[0],dParamHiStop,0.75);
    dJointSetHinge2Param (joint[0],dParamFudgeFactor,0.1);

    dSpaceCollide (space,0,&nearCallback);
    dWorldStep (world,0.05);

    // remove all contact joints
    dJointGroupEmpty (contactgroup);
  }

  dsSetColor (0,1,1);
  dsSetTexture (DS_WOOD);
  dReal sides[3] = {LENGTH,WIDTH,HEIGHT};
  dsDrawBox (dBodyGetPosition(body[0]),dBodyGetRotation(body[0]),sides);
  dsSetColor (1,1,1);
  for (i=1; i<=3; i++) dsDrawCylinder (dBodyGetPosition(body[i]),
				       dBodyGetRotation(body[i]),0.02,RADIUS);

  /*
  dVector3 ss;
  dGeomBoxGetLengths (ground_box,ss);
  dsDrawBox (dGeomGetPosition(ground_box),dGeomGetRotation(ground_box),ss);
  */

  /*
  printf ("%.10f %.10f %.10f %.10f\n",
	  dJointGetHingeAngle (joint[1]),
	  dJointGetHingeAngle (joint[2]),
	  dJointGetHingeAngleRate (joint[1]),
	  dJointGetHingeAngleRate (joint[2]));
  */
}

int main (int argc, char **argv)
{
  int i;
  dMass m;

  // setup pointers to drawstuff callback functions
  dsFunctions fn;
  fn.version = DS_VERSION;
  fn.start = &start;
  fn.step = &simLoop;
  fn.command = &command;
  fn.stop = 0;
  fn.path_to_textures = "../../drawstuff/textures";

  // create world

  world = dWorldCreate();
  space = dSpaceCreate();
  contactgroup = dJointGroupCreate (1000000);
  dWorldSetGravity (world,0,0,-0.5);
  ground = dCreatePlane (space,0,0,1,0);

  // chassis body
  body[0] = dBodyCreate (world);
  dBodySetPosition (body[0],0,0,STARTZ);
  dMassSetBox (&m,1,LENGTH,WIDTH,HEIGHT);
  dMassAdjust (&m,CMASS);
  dBodySetMass (body[0],&m);
  box[0] = dCreateBox (space,LENGTH,WIDTH,HEIGHT);
  dGeomSetBody (box[0],body[0]);

  // wheel bodies
  for (i=1; i<=3; i++) {
    body[i] = dBodyCreate (world);
    dQuaternion q;
    dQFromAxisAndAngle (q,1,0,0,M_PI*0.5);
    dBodySetQuaternion (body[i],q);
    dMassSetSphere (&m,1,RADIUS);
    dMassAdjust (&m,WMASS);
    dBodySetMass (body[i],&m);
    sphere[i-1] = dCreateSphere (space,RADIUS);
    dGeomSetBody (sphere[i-1],body[i]);
  }
  dBodySetPosition (body[1],0.5*LENGTH,0,STARTZ-HEIGHT*0.5);
  dBodySetPosition (body[2],-0.5*LENGTH, WIDTH*0.5,STARTZ-HEIGHT*0.5);
  dBodySetPosition (body[3],-0.5*LENGTH,-WIDTH*0.5,STARTZ-HEIGHT*0.5);

  // front wheel hinge
  /*
  joint[0] = dJointCreateHinge2 (world,0);
  dJointAttach (joint[0],body[0],body[1]);
  const dReal *a = dBodyGetPosition (body[1]);
  dJointSetHinge2Anchor (joint[0],a[0],a[1],a[2]);
  dJointSetHinge2Axis1 (joint[0],0,0,1);
  dJointSetHinge2Axis2 (joint[0],0,1,0);
  */

  // front and back wheel hinges
  for (i=0; i<3; i++) {
    joint[i] = dJointCreateHinge2 (world,0);
    dJointAttach (joint[i],body[0],body[i+1]);
    const dReal *a = dBodyGetPosition (body[i+1]);
    dJointSetHinge2Anchor (joint[i],a[0],a[1],a[2]);
    dJointSetHinge2Axis1 (joint[i],0,0,1);
    dJointSetHinge2Axis2 (joint[i],0,1,0);
  }

  // set joint suspension
  for (i=0; i<3; i++) {
    dJointSetHinge2Param (joint[i],dParamSuspensionERP,0.4);
    dJointSetHinge2Param (joint[i],dParamSuspensionCFM,0.8);
  }

  // lock back wheels along the steering axis
  for (i=1; i<3; i++) {
    dJointSetHinge2Param (joint[i],dParamVel,0);
    dJointSetHinge2Param (joint[i],dParamFMax,dInfinity);
  }

  // environment
  /*
  ground_box = dCreateBox (space,2,1.5,1);
  dMatrix3 R;
  dRFromAxisAndAngle (R,0,1,0,-0.15);
  dGeomSetPosition (ground_box,2,0,-0.34);
  dGeomSetRotation (ground_box,R);
  */

  // run simulation
  dsSimulationLoop (argc,argv,352,288,&fn);

  dJointGroupDestroy (contactgroup);
  dSpaceDestroy (space);
  dWorldDestroy (world);

  return 0;
}
<commit_msg>hmmmm.<commit_after>/*************************************************************************
 *                                                                       *
 * Open Dynamics Engine, Copyright (C) 2001 Russell L. Smith.            *
 *                                                                       *
 * This library is free software; you can redistribute it and/or         *
 * modify it under the terms of the GNU Lesser General Public            *
 * License as published by the Free Software Foundation; either          *
 * version 2.1 of the License, or (at your option) any later version.    *
 *                                                                       *
 * This library is distributed in the hope that it will be useful,       *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      *
 * Lesser General Public License for more details.                       *
 *                                                                       *
 * You should have received a copy of the GNU Lesser General Public      *
 * License along with this library (see the file LICENSE.TXT); if not,   *
 * write to the Free Software Foundation, Inc., 59 Temple Place,         *
 * Suite 330, Boston, MA 02111-1307 USA.                                 *
 *                                                                       *
 *************************************************************************/

/*

buggy with suspension

*/

#include <stdio.h>
#include "ode/ode.h"
#include "drawstuff/drawstuff.h"

// select correct drawing functions

#ifdef dDOUBLE
#define dsDrawBox dsDrawBoxD
#define dsDrawSphere dsDrawSphereD
#define dsDrawCylinder dsDrawCylinderD
#define dsDrawCappedCylinder dsDrawCappedCylinderD
#endif

// some constants

#define LENGTH 0.7	// chassis length
#define WIDTH 0.5	// chassis width
#define HEIGHT 0.2	// chassis height
#define RADIUS 0.18	// wheel radius
#define STARTZ 0.5	// starting height of chassis
#define CMASS 1		// chassis mass
#define WMASS 0.2	// wheel mass

// dynamics and collision objects (chassis, 3 wheels, environment)

static dWorldID world;
static dSpaceID space;
static dBodyID body[4];
static dJointID joint[3];	// joint[0] is the front wheel
static dJointGroupID contactgroup;
static dGeomID ground;
static dGeomID box[1];
static dGeomID sphere[3];
static dGeomID ground_box;

// things that the user controls

static dReal speed=0,steer=0;	// user commands

// this is called by dSpaceCollide when two objects in space are
// potentially colliding.

static void nearCallback (void *data, dGeomID o1, dGeomID o2)
{
  // only collide things with the ground
  int g1 = (o1 == ground || o1 == ground_box);
  int g2 = (o2 == ground || o2 == ground_box);
  if (!(g1 ^ g2)) return;

  dContact contact;
  contact.surface.mode = dContactSlip1 | dContactSlip2 |
    dContactSoftErp | dContactSoftCfm;
  contact.surface.mu = dInfinity;
  contact.surface.slip1 = 0.1;
  contact.surface.slip2 = 0.1;
  contact.surface.soft_erp = 0.5;
  contact.surface.soft_cfm = 0.3;
  if (dCollide (o1,o2,0,&contact.geom,sizeof(dContactGeom))) {
    //    if (o1==ground_box) printf ("foo 1\n");
    //    if (o2==ground_box) printf ("foo 2\n");

    dJointID c = dJointCreateContact (world,contactgroup,&contact);
    dJointAttach (c,dGeomGetBody(o1),dGeomGetBody(o2));
  }
}

// start simulation - set viewpoint

static void start()
{
  static float xyz[3] = {0.8317,-0.9817,0.8000};
  static float hpr[3] = {121.0000,-27.5000,0.0000};
  dsSetViewpoint (xyz,hpr);
  printf ("Press:\t'a' to increase speed.\n"
	  "\t'z' to decrease speed.\n"
	  "\t',' to steer left.\n"
	  "\t'.' to steer right.\n");
}

// called when a key pressed

static void command (int cmd)
{
  switch (cmd) {
  case 'a': case 'A':
    speed += 0.3;
    break;
  case 'z': case 'Z':
    speed -= 0.3;
    break;
  case ',':
    steer -= 0.5;
    break;
  case '.':
    steer += 0.5;
    break;
  case ' ':
    speed = 0;
    steer = 0;
    break;
  }
}

// simulation loop

static void simLoop (int pause)
{
  int i;
  if (!pause) {
    // motor
    dJointSetHinge2Param (joint[0],dParamVel2,-speed);
    dJointSetHinge2Param (joint[0],dParamFMax2,0.1);

    // steering
    dReal v = steer - dJointGetHinge2Angle1 (joint[0]);
    if (v > 0.1) v = 0.1;
    if (v < -0.1) v = -0.1;
    v *= 10.0;
    dJointSetHinge2Param (joint[0],dParamVel,v);
    dJointSetHinge2Param (joint[0],dParamFMax,0.2);
    dJointSetHinge2Param (joint[0],dParamLoStop,-0.75);
    dJointSetHinge2Param (joint[0],dParamHiStop,0.75);
    dJointSetHinge2Param (joint[0],dParamFudgeFactor,0.1);

    dSpaceCollide (space,0,&nearCallback);
    dWorldStep (world,0.05);

    // remove all contact joints
    dJointGroupEmpty (contactgroup);
  }

  dsSetColor (0,1,1);
  dsSetTexture (DS_WOOD);
  dReal sides[3] = {LENGTH,WIDTH,HEIGHT};
  dsDrawBox (dBodyGetPosition(body[0]),dBodyGetRotation(body[0]),sides);
  dsSetColor (1,1,1);
  for (i=1; i<=3; i++) dsDrawCylinder (dBodyGetPosition(body[i]),
				       dBodyGetRotation(body[i]),0.02,RADIUS);

  dVector3 ss;
  dGeomBoxGetLengths (ground_box,ss);
  dsDrawBox (dGeomGetPosition(ground_box),dGeomGetRotation(ground_box),ss);

  /*
  printf ("%.10f %.10f %.10f %.10f\n",
	  dJointGetHingeAngle (joint[1]),
	  dJointGetHingeAngle (joint[2]),
	  dJointGetHingeAngleRate (joint[1]),
	  dJointGetHingeAngleRate (joint[2]));
  */
}

int main (int argc, char **argv)
{
  int i;
  dMass m;

  // setup pointers to drawstuff callback functions
  dsFunctions fn;
  fn.version = DS_VERSION;
  fn.start = &start;
  fn.step = &simLoop;
  fn.command = &command;
  fn.stop = 0;
  fn.path_to_textures = "../../drawstuff/textures";

  // create world

  world = dWorldCreate();
  space = dSpaceCreate();
  contactgroup = dJointGroupCreate (1000000);
  dWorldSetGravity (world,0,0,-0.5);
  ground = dCreatePlane (space,0,0,1,0);

  // chassis body
  body[0] = dBodyCreate (world);
  dBodySetPosition (body[0],0,0,STARTZ);
  dMassSetBox (&m,1,LENGTH,WIDTH,HEIGHT);
  dMassAdjust (&m,CMASS);
  dBodySetMass (body[0],&m);
  box[0] = dCreateBox (space,LENGTH,WIDTH,HEIGHT);
  dGeomSetBody (box[0],body[0]);

  // wheel bodies
  for (i=1; i<=3; i++) {
    body[i] = dBodyCreate (world);
    dQuaternion q;
    dQFromAxisAndAngle (q,1,0,0,M_PI*0.5);
    dBodySetQuaternion (body[i],q);
    dMassSetSphere (&m,1,RADIUS);
    dMassAdjust (&m,WMASS);
    dBodySetMass (body[i],&m);
    sphere[i-1] = dCreateSphere (space,RADIUS);
    dGeomSetBody (sphere[i-1],body[i]);
  }
  dBodySetPosition (body[1],0.5*LENGTH,0,STARTZ-HEIGHT*0.5);
  dBodySetPosition (body[2],-0.5*LENGTH, WIDTH*0.5,STARTZ-HEIGHT*0.5);
  dBodySetPosition (body[3],-0.5*LENGTH,-WIDTH*0.5,STARTZ-HEIGHT*0.5);

  // front wheel hinge
  /*
  joint[0] = dJointCreateHinge2 (world,0);
  dJointAttach (joint[0],body[0],body[1]);
  const dReal *a = dBodyGetPosition (body[1]);
  dJointSetHinge2Anchor (joint[0],a[0],a[1],a[2]);
  dJointSetHinge2Axis1 (joint[0],0,0,1);
  dJointSetHinge2Axis2 (joint[0],0,1,0);
  */

  // front and back wheel hinges
  for (i=0; i<3; i++) {
    joint[i] = dJointCreateHinge2 (world,0);
    dJointAttach (joint[i],body[0],body[i+1]);
    const dReal *a = dBodyGetPosition (body[i+1]);
    dJointSetHinge2Anchor (joint[i],a[0],a[1],a[2]);
    dJointSetHinge2Axis1 (joint[i],0,0,1);
    dJointSetHinge2Axis2 (joint[i],0,1,0);
  }

  // set joint suspension
  for (i=0; i<3; i++) {
    dJointSetHinge2Param (joint[i],dParamSuspensionERP,0.4);
    dJointSetHinge2Param (joint[i],dParamSuspensionCFM,0.8);
  }

  // lock back wheels along the steering axis
  for (i=1; i<3; i++) {
    dJointSetHinge2Param (joint[i],dParamVel,0);
    dJointSetHinge2Param (joint[i],dParamFMax,dInfinity);
  }

  // environment
  ground_box = dCreateBox (space,2,1.5,1);
  dMatrix3 R;
  dRFromAxisAndAngle (R,0,1,0,-0.15);
  dGeomSetPosition (ground_box,2,0,-0.34);
  dGeomSetRotation (ground_box,R);

  // run simulation
  dsSimulationLoop (argc,argv,352,288,&fn);

  dJointGroupDestroy (contactgroup);
  dSpaceDestroy (space);
  dWorldDestroy (world);

  return 0;
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2579
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1508389 by johtaylo@johtaylo-jtincrementor2-increment on 2018/01/26 03:00:05<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2580
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>// =============================================================================
//
// Copyright (c) 2013-2014 Christopher Baker <http://christopherbaker.net>
//               2014 Brannon Dorsey <http://brannondorsey.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// =============================================================================

#include "Project.h"
#include "ofUtils.h"

namespace of {
namespace Sketch {

Project::~Project()
{
}

Project::Project(const std::string& path):
    _path(path),
    _isLoaded(false)
{
    // this is not efficient at all! I am just keeping these FileTemplate loads in the project
    // constructor because it makes the most sense architecure wise.
    _classFileTemplate = ofBufferFromFile(ofToDataPath("Resources/Templates/SketchTemplates/class.txt")).getText();
    load(_path, getName());
}

void Project::load(const std::string& path, const std::string& name)
{
    _sketchDir = ofDirectory(ofToDataPath(path + "/sketch"));

    _data.clear();

    if (_sketchDir.exists())
    {
        _sketchDir.listDir();

        std::vector<ofFile> files = _sketchDir.getFiles();

        int classCounter = 0;

        for (std::size_t i = 0; i < files.size(); ++i)
        {
            ofFile file = files[i];
            if (file.getBaseName() == name)
            {
                file.open(file.getAbsolutePath());
                _data["projectFile"]["name"] = file.getBaseName();
                _data["projectFile"]["fileName"] = file.getFileName();
                _data["projectFile"]["fileContents"] = file.readToBuffer().getText();
            }
            else if (file.getExtension() == "sketch")
            {
                file.open(file.getAbsolutePath());
                _data["classes"][classCounter]["name"] = file.getBaseName();
                _data["classes"][classCounter]["fileName"] = file.getFileName();
                _data["classes"][classCounter]["fileContents"] = file.readToBuffer().getText();
                classCounter++;
            }
        }

        _isLoaded = true;
    }
}

bool Project::isLoaded() const
{
    return _isLoaded;
}

// saves differences only
void Project::save(const Json::Value& data)
{
    // this is not working for some reason...
    if (_data != data) {

        ofLogVerbose("Project::save") << data.toStyledString();

        if (_data["projectFile"] != data["projectFile"]) {
            _data["projectFile"] = data["projectFile"];
            _saveFile(_data["projectFile"]);
        }

        // uses nested for loop in case classes are not in the same order
        std::vector<Json::Value> newClasses;
        std::vector<Json::Value> deletedClasses;

        for (int i = 0; i < _data["classes"].size(); ++i)
        {
            Json::Value& classFile = _data["classes"][i];
            bool matchFound = false;

            for (int j = 0; j < data.size(); ++j)
            {
                const Json::Value& newClassFile = data["classes"][j];

                if (classFile["fileName"] == newClassFile["fileName"])
                {
                    if (classFile != newClassFile)
                    {
                        classFile = newClassFile;
                        _saveFile(classFile);
                    }

                    matchFound = true;
                    break;
                }
            }

            if (!matchFound) _saveFile(classFile); // class is new
        }
    }
    else
    {
        ofLogNotice("Project::save") << "Project data is the same. Not saving project.";
    }
}

bool Project::create(const std::string& path)
{
    ofDirectory project(ofToDataPath(path));
    if (!project.exists())
    {
        ofDirectory temp(ofToDataPath("Resources/Templates/SimpleTemplate"));
        temp.copyTo(ofToDataPath(path));
        return true;
    }

    return false;
}

bool Project::remove()
{
    ofDirectory projectDir(getPath());
    return projectDir.remove(true);
}

bool Project::rename(const std::string& newName)
{
    if (isLoaded())
    {
        ofLogVerbose("Project::rename") << "renaming project \"" << getName() << "\" to \"" << newName + "\"";
        ofFile projectDir(getPath());
        std::string oldProjectName = getName();
        ofLogVerbose("Project::rename") << "project path: " << getPath();
        ofLogVerbose("Project::rename") << "renamed to: " << projectDir.getEnclosingDirectory() + newName;
        if (!projectDir.renameTo(projectDir.getEnclosingDirectory() + newName)) return false;
        _path = projectDir.getAbsolutePath();
        ofFile projectFile(projectDir.getAbsolutePath() + "/sketch/" + oldProjectName + ".sketch");
        ofLogVerbose("Project::rename") << "projectDir path after rename: " << projectDir.getAbsolutePath();
        ofLogVerbose("Project::rename") << "projectFile path: " << projectFile.getAbsolutePath();
        if (!projectFile.renameTo(projectDir.getAbsolutePath() + "/sketch/" + newName + ".sketch")) return false;
        ofLogVerbose("Project::rename") << "projectFile path after rename: " << projectFile.getAbsolutePath();
        _data["projectFile"]["name"] = newName;
        _data["projectFile"]["fileName"] = newName + ".sketch";
        return true;
    }

    return false;
}

Json::Value Project::createClass(const std::string& className)
{
    std::string fileContents = _classFileTemplate;
    ofStringReplace(fileContents, "<classname>", className);

    ofLogVerbose("Project::createClass") << "fileContents: "<< fileContents;

    Json::Value classFile;
    // TODO: Load extension from settings
    classFile["fileName"] = className + ".sketch";
    classFile["name"] = className;
    classFile["fileContents"] = fileContents;
    _data["classes"][getNumClasses()] = classFile;
    // TODO: re-loading is a terribly slow way to delete. Come back and optimize.
    // Simply need to remove the Json::Value class in _data["classes"]
    _saveFile(classFile);
    return classFile;
}

bool Project::deleteClass(const std::string& className)
{
    if (isLoaded()) {
        ofFile file(_sketchDir.getAbsolutePath() + "/" + className + ".sketch");
        if (file.exists()) {
            file.remove();
            // TODO: re-loading is a terribly slow way to delete. Come back and optimize.
            // Simply need to remove the Json::Value class in _data["classes"]
            load(_path, getName());
            return true;
        }
    }

    return false;
}

bool Project::renameClass(const std::string& currentName, const std::string& newName)
{
    if (isLoaded()) {
        ofLogVerbose("Project::renameClass") << "Renaming class...";

        ofFile file(_sketchDir.getAbsolutePath() + "/" + currentName + ".sketch");
        if (file.exists() && hasClasses())
        {
            for (int i = 0; i < getNumClasses(); ++i)
            {
                if (_data["classes"][i]["name"] == currentName)
                {
                    _data["classes"][i]["name"] = newName;
                    _data["classes"][i]["fileName"] = newName + ".sketch";

                    file.renameTo(_sketchDir.getAbsolutePath() + "/" + newName + ".sketch");
                    return true;
                }
            }
        }
    }

    return false;
}

bool Project::hasClasses() const
{
    return !_data["classes"].empty();
}

bool Project::isClassName(const std::string& className) const
{
    if (hasClasses())
    {
        for (int i = 0; i < getNumClasses(); ++i)
        {
            if (_data["classes"][i]["name"] == className)
            {
                return true;
            }
        }
    }

    return false;
}

int Project::getNumClasses() const
{
    return _data["classes"].size();
}

const std::string& Project::getPath() const
{
    return _path;
}

std::string Project::getName() const
{
    ofFile project(_path);
    return project.getBaseName();
}

const Json::Value& Project::getData() const
{
    return _data;
}

void Project::_saveFile(const Json::Value& fileData)
{
    ofBuffer fileBuffer(fileData["fileContents"].asString());
    ofBufferToFile(getPath() + "/sketch/" + fileData["fileName"].asString(), fileBuffer);
}

} } // namespace of::Sketch
<commit_msg>Formatting and cleanup for easier reading.<commit_after>// =============================================================================
//
// Copyright (c) 2013-2014 Christopher Baker <http://christopherbaker.net>
//               2014 Brannon Dorsey <http://brannondorsey.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// =============================================================================

#include "Project.h"
#include "ofUtils.h"

namespace of {
namespace Sketch {

Project::~Project()
{
}

Project::Project(const std::string& path): _path(path), _isLoaded(false)
{
    // this is not efficient at all! I am just keeping these FileTemplate loads in the project
    // constructor because it makes the most sense architecure wise.
    _classFileTemplate = ofBufferFromFile(ofToDataPath("Resources/Templates/SketchTemplates/class.txt")).getText();
    load(_path, getName());
}

void Project::load(const std::string& path, const std::string& name)
{
    _sketchDir = ofDirectory(ofToDataPath(path + "/sketch"));

    _data.clear();

    if (_sketchDir.exists())
    {
        _sketchDir.listDir();

        std::vector<ofFile> files = _sketchDir.getFiles();

        int classCounter = 0;

        for (std::size_t i = 0; i < files.size(); ++i)
        {
            ofFile file = files[i];
            if (file.getBaseName() == name)
            {
                file.open(file.getAbsolutePath());
                _data["projectFile"]["name"] = file.getBaseName();
                _data["projectFile"]["fileName"] = file.getFileName();
                _data["projectFile"]["fileContents"] = file.readToBuffer().getText();
            }
            else if (file.getExtension() == "sketch")
            {
                file.open(file.getAbsolutePath());
                _data["classes"][classCounter]["name"] = file.getBaseName();
                _data["classes"][classCounter]["fileName"] = file.getFileName();
                _data["classes"][classCounter]["fileContents"] = file.readToBuffer().getText();
                classCounter++;
            }
        }

        _isLoaded = true;
    }
}

bool Project::isLoaded() const
{
    return _isLoaded;
}

// saves differences only
void Project::save(const Json::Value& data)
{
    // this is not working for some reason...
    if (_data != data) {

        ofLogVerbose("Project::save") << data.toStyledString();

        if (_data["projectFile"] != data["projectFile"]) {
            _data["projectFile"] = data["projectFile"];
            _saveFile(_data["projectFile"]);
        }

        // uses nested for loop in case classes are not in the same order
        std::vector<Json::Value> newClasses;
        std::vector<Json::Value> deletedClasses;

        for (int i = 0; i < _data["classes"].size(); ++i)
        {
            Json::Value& classFile = _data["classes"][i];
            bool matchFound = false;

            for (int j = 0; j < data.size(); ++j)
            {
                const Json::Value& newClassFile = data["classes"][j];

                if (classFile["fileName"] == newClassFile["fileName"])
                {
                    if (classFile != newClassFile)
                    {
                        classFile = newClassFile;
                        _saveFile(classFile);
                    }

                    matchFound = true;
                    break;
                }
            }

            if (!matchFound) _saveFile(classFile); // class is new
        }
    }
    else
    {
        ofLogNotice("Project::save") << "Project data is the same. Not saving project.";
    }
}

bool Project::create(const std::string& path)
{
    ofDirectory project(ofToDataPath(path));
    if (!project.exists())
    {
        ofDirectory temp(ofToDataPath("Resources/Templates/SimpleTemplate"));
        temp.copyTo(ofToDataPath(path));
        return true;
    }

    return false;
}

bool Project::remove()
{
    ofDirectory projectDir(getPath());
    return projectDir.remove(true);
}

bool Project::rename(const std::string& newName)
{
    if (isLoaded())
    {
        ofLogVerbose("Project::rename") << "renaming project \"" << getName() << "\" to \"" << newName + "\"";

        ofFile projectDir(getPath());

        std::string oldProjectName = getName();

        ofLogVerbose("Project::rename") << "project path: " << getPath() << " Renamed to: " << projectDir.getEnclosingDirectory() + newName;

        if (!projectDir.renameTo(projectDir.getEnclosingDirectory() + newName)) return false;

        _path = projectDir.getAbsolutePath();

        ofFile projectFile(projectDir.getAbsolutePath() + "/sketch/" + oldProjectName + ".sketch");

        ofLogVerbose("Project::rename") << "projectDir path after rename: " << projectDir.getAbsolutePath();

        ofLogVerbose("Project::rename") << "projectFile path: " << projectFile.getAbsolutePath();

        if (!projectFile.renameTo(projectDir.getAbsolutePath() + "/sketch/" + newName + ".sketch")) return false;

        ofLogVerbose("Project::rename") << "projectFile path after rename: " << projectFile.getAbsolutePath();

        _data["projectFile"]["name"] = newName;

        _data["projectFile"]["fileName"] = newName + ".sketch";

        return true;
    }
    else
    {
        ofLogVerbose("Project::rename") << "Cannot rename project, it is not loaded.";
        return false;
    }

}

Json::Value Project::createClass(const std::string& className)
{
    std::string fileContents = _classFileTemplate;
    ofStringReplace(fileContents, "<classname>", className);

    ofLogVerbose("Project::createClass") << "fileContents: "<< fileContents;

    Json::Value classFile;
    // TODO: Load extension from settings
    classFile["fileName"] = className + ".sketch";
    classFile["name"] = className;
    classFile["fileContents"] = fileContents;
    _data["classes"][getNumClasses()] = classFile;
    // TODO: re-loading is a terribly slow way to delete. Come back and optimize.
    // Simply need to remove the Json::Value class in _data["classes"]
    _saveFile(classFile);
    return classFile;
}

bool Project::deleteClass(const std::string& className)
{
    if (isLoaded())
    {
        ofFile file(_sketchDir.getAbsolutePath() + "/" + className + ".sketch");

        if (file.exists())
        {
            file.remove();
            // TODO: re-loading is a terribly slow way to delete. Come back and optimize.
            // Simply need to remove the Json::Value class in _data["classes"]
            load(_path, getName());
            return true;
        }
    }

    return false;
}

bool Project::renameClass(const std::string& currentName, const std::string& newName)
{
    if (isLoaded())
    {
        ofLogVerbose("Project::renameClass") << "Renaming class...";

        ofFile file(_sketchDir.getAbsolutePath() + "/" + currentName + ".sketch");
        if (file.exists() && hasClasses())
        {
            for (int i = 0; i < getNumClasses(); ++i)
            {
                if (_data["classes"][i]["name"] == currentName)
                {
                    _data["classes"][i]["name"] = newName;
                    _data["classes"][i]["fileName"] = newName + ".sketch";

                    file.renameTo(_sketchDir.getAbsolutePath() + "/" + newName + ".sketch");
                    return true;
                }
            }
        }
    }

    return false;
}

bool Project::hasClasses() const
{
    return !_data["classes"].empty();
}

bool Project::isClassName(const std::string& className) const
{
    if (hasClasses())
    {
        for (int i = 0; i < getNumClasses(); ++i)
        {
            if (_data["classes"][i]["name"] == className)
            {
                return true;
            }
        }
    }

    return false;
}

int Project::getNumClasses() const
{
    return _data["classes"].size();
}

const std::string& Project::getPath() const
{
    return _path;
}

std::string Project::getName() const
{
    ofFile project(_path);
    return project.getBaseName();
}

const Json::Value& Project::getData() const
{
    return _data;
}

void Project::_saveFile(const Json::Value& fileData)
{
    ofBuffer fileBuffer(fileData["fileContents"].asString());
    ofBufferToFile(getPath() + "/sketch/" + fileData["fileName"].asString(), fileBuffer);
}

} } // namespace of::Sketch
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1733
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1122277 by johtaylo@johtaylo-JTBUILDER03-increment on 2015/02/14 03:00:12<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1734
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1684
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1097349 by johtaylo@johtaylo-JTBUILDER03-increment on 2014/11/15 03:00:12<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1685
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2782
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1711540 by chui@ocl-promo-incrementor on 2018/11/25 03:00:13<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2783
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2137
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1277012 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/06/07 03:00:44<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2138
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2529
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1475971 by johtaylo@johtaylo-jtincrementor2-increment on 2017/10/28 03:00:06<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2530
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2031
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1235953 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/02/10 03:00:10<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2032
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2034
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1236970 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/02/13 03:00:12<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2035
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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 "third_party/pe-parse/parser-library/parse.h"

#include "pecodesource.hpp"

PECodeRegion::PECodeRegion(uint8_t* buffer, size_t length, Dyninst::Address
  section_base, const std::string& name) : base_(section_base), size_(length) {
  data_ = static_cast<uint8_t*>(malloc(length));
  memcpy(data_, buffer, length);
  is_code_ = true;
}

PECodeRegion::~PECodeRegion() {
  free(data_);
}

bool PECodeSource::isValidAddress( const Dyninst::Address addr ) const {
  Dyninst::ParseAPI::CodeRegion* region = getRegion(addr);
  if (region != NULL) {
    return true;
  } else {
    return false;
  }
}

PECodeSource::PECodeSource(const std::string& filename) {
  peparse::parsed_pe* parsed_file = peparse::ParsePEFromFile(filename.c_str());

  if (parsed_file == 0) {
    printf("[!] Failure to parse PE file!\n");
    return;
  }
  peparse::iterSec section_callback = [](void* N, peparse::VA section_base,
    std::string& section_name, peparse::image_section_header s,
    peparse::bounded_buffer* data) -> int {

    printf("[!] Adding new code region at address %lx (name %s, size %d)\n",
      section_base, section_name.c_str(), data->bufLen);

    PECodeRegion* new_region =  new PECodeRegion(
      data->buf, data->bufLen, static_cast<Dyninst::Address>(section_base),
      section_name);
    PECodeSource* pe_code_source = static_cast<PECodeSource*>(N);
    // Debug print the new section?
    pe_code_source->_regions.push_back(new_region);
    pe_code_source->_region_tree.insert(new_region);
  };
  peparse::IterSec( parsed_file, section_callback, static_cast<void*>(this) );
  parsed_ = true;
}

Dyninst::ParseAPI::CodeRegion* PECodeSource::getRegion(
  const Dyninst::Address addr) const {
  std::set<Dyninst::ParseAPI::CodeRegion*> regions;
  _region_tree.find(addr, regions);
  for (Dyninst::ParseAPI::CodeRegion* region : regions) {
    return region;
  }
  return NULL;
}

void* PECodeSource::getPtrToInstruction(const Dyninst::Address addr) const {
  return getRegion(addr)->getPtrToInstruction(addr);
}

void* PECodeSource::getPtrToData(const Dyninst::Address addr) const {
  return getPtrToInstruction(addr);
}

unsigned int PECodeSource::getAddressWidth() const {
  return _regions[0]->getArch();
}

bool PECodeSource::isCode(const Dyninst::Address addr) const {
  Dyninst::ParseAPI::CodeRegion* region = getRegion(addr);
  if (region && region->isCode(addr)) {
    return true;
  }
  return false;
}

bool PECodeSource::isData(const Dyninst::Address addr) const {
  Dyninst::ParseAPI::CodeRegion* region = getRegion(addr);
  if (region && region->isData(addr)) {
    return true;
  }
  return false;
}

bool PECodeSource::isReadOnly(const Dyninst::Address addr) const {
  Dyninst::ParseAPI::CodeRegion* region = getRegion(addr);
  if (region && region->isReadOnly(addr)) {
    return true;
  }
  return false;
}

Dyninst::Address PECodeSource::offset() const {
  return 0;
}

Dyninst::Address PECodeSource::length() const {
  return 0;
}
Dyninst::Architecture PECodeSource::getArch() const {
  return _regions[0]->getArch();
}

<commit_msg>Reduced verbosity when parsing PE.<commit_after>// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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 "third_party/pe-parse/parser-library/parse.h"

#include "pecodesource.hpp"

PECodeRegion::PECodeRegion(uint8_t* buffer, size_t length, Dyninst::Address
  section_base, const std::string& name) : base_(section_base), size_(length) {
  data_ = static_cast<uint8_t*>(malloc(length));
  memcpy(data_, buffer, length);
  is_code_ = true;
}

PECodeRegion::~PECodeRegion() {
  free(data_);
}

bool PECodeSource::isValidAddress( const Dyninst::Address addr ) const {
  Dyninst::ParseAPI::CodeRegion* region = getRegion(addr);
  if (region != NULL) {
    return true;
  } else {
    return false;
  }
}

PECodeSource::PECodeSource(const std::string& filename) {
  peparse::parsed_pe* parsed_file = peparse::ParsePEFromFile(filename.c_str());

  if (parsed_file == 0) {
    printf("[!] Failure to parse PE file!\n");
    return;
  }
  peparse::iterSec section_callback = [](void* N, peparse::VA section_base,
    std::string& section_name, peparse::image_section_header s,
    peparse::bounded_buffer* data) -> int {

    PECodeRegion* new_region =  new PECodeRegion(
      data->buf, data->bufLen, static_cast<Dyninst::Address>(section_base),
      section_name);
    PECodeSource* pe_code_source = static_cast<PECodeSource*>(N);
    // Debug print the new section?
    pe_code_source->_regions.push_back(new_region);
    pe_code_source->_region_tree.insert(new_region);
  };
  peparse::IterSec( parsed_file, section_callback, static_cast<void*>(this) );
  parsed_ = true;
}

Dyninst::ParseAPI::CodeRegion* PECodeSource::getRegion(
  const Dyninst::Address addr) const {
  std::set<Dyninst::ParseAPI::CodeRegion*> regions;
  _region_tree.find(addr, regions);
  for (Dyninst::ParseAPI::CodeRegion* region : regions) {
    return region;
  }
  return NULL;
}

void* PECodeSource::getPtrToInstruction(const Dyninst::Address addr) const {
  return getRegion(addr)->getPtrToInstruction(addr);
}

void* PECodeSource::getPtrToData(const Dyninst::Address addr) const {
  return getPtrToInstruction(addr);
}

unsigned int PECodeSource::getAddressWidth() const {
  return _regions[0]->getArch();
}

bool PECodeSource::isCode(const Dyninst::Address addr) const {
  Dyninst::ParseAPI::CodeRegion* region = getRegion(addr);
  if (region && region->isCode(addr)) {
    return true;
  }
  return false;
}

bool PECodeSource::isData(const Dyninst::Address addr) const {
  Dyninst::ParseAPI::CodeRegion* region = getRegion(addr);
  if (region && region->isData(addr)) {
    return true;
  }
  return false;
}

bool PECodeSource::isReadOnly(const Dyninst::Address addr) const {
  Dyninst::ParseAPI::CodeRegion* region = getRegion(addr);
  if (region && region->isReadOnly(addr)) {
    return true;
  }
  return false;
}

Dyninst::Address PECodeSource::offset() const {
  return 0;
}

Dyninst::Address PECodeSource::length() const {
  return 0;
}
Dyninst::Architecture PECodeSource::getArch() const {
  return _regions[0]->getArch();
}

<|endoftext|>


<commit_before>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <stdlib.h>
#include <unistd.h>
#include "fnord-base/application.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/logging.h"
#include "fnord-base/inspect.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/SSTableScan.h"

using namespace fnord;

int main(int argc, const char** argv) {
  fnord::Application::init();
  fnord::Application::logToStderr();

  fnord::cli::FlagParser flags;

  flags.defineFlag(
      "file",
      fnord::cli::FlagParser::T_STRING,
      true,
      "f",
      NULL,
      "input sstable file",
      "<file>");

  flags.defineFlag(
      "limit",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      NULL,
      "limit",
      "<num>");

  flags.defineFlag(
      "offset",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      NULL,
      "offset",
      "<num>");

  flags.defineFlag(
      "order_by",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      NULL,
      "order by",
      "<column>");

  flags.defineFlag(
      "order_fn",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "STRASC",
      "one of: STRASC, STRDSC, NUMASC, NUMDSC",
      "<fn>");

  flags.defineFlag(
      "loglevel",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  /* open input sstable */
  auto input_file = flags.getString("file");
  sstable::SSTableReader reader(File::openFile(input_file, File::O_READ));
  if (reader.bodySize() == 0) {
    fnord::logWarning("fnord.sstablescan", "sstable is unfinished");
  }

  sstable::SSTableColumnSchema schema;
  schema.loadIndex(&reader);

  /* set up scan */
  sstable::SSTableScan scan(&schema);
  if (flags.isSet("limit")) {
    scan.setLimit(flags.getInt("limit"));
  }

  if (flags.isSet("offset")) {
    scan.setOffset(flags.getInt("offset"));
  }

  if (flags.isSet("order_by")) {
    scan.setOrderBy(flags.getString("order_by"), flags.getString("order_fn"));
  }

  /* execute scan */
  auto headers = scan.columnNames();
  fnord::iputs("hdr: $0", headers);

  auto cursor = reader.getCursor();
  scan.execute(cursor.get(), [] (const Vector<String> row) {
    fnord::iputs("row: $0", row);
  });

  return 0;
}

<commit_msg>sstablescan csv output...<commit_after>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <stdlib.h>
#include <unistd.h>
#include "fnord-base/application.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/logging.h"
#include "fnord-base/inspect.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/SSTableScan.h"

using namespace fnord;

int main(int argc, const char** argv) {
  fnord::Application::init();
  fnord::Application::logToStderr();

  fnord::cli::FlagParser flags;

  flags.defineFlag(
      "file",
      fnord::cli::FlagParser::T_STRING,
      true,
      "f",
      NULL,
      "input sstable file",
      "<file>");

  flags.defineFlag(
      "limit",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      NULL,
      "limit",
      "<num>");

  flags.defineFlag(
      "offset",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      NULL,
      "offset",
      "<num>");

  flags.defineFlag(
      "order_by",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      NULL,
      "order by",
      "<column>");

  flags.defineFlag(
      "order_fn",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "STRASC",
      "one of: STRASC, STRDSC, NUMASC, NUMDSC",
      "<fn>");

  flags.defineFlag(
      "loglevel",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  /* open input sstable */
  auto input_file = flags.getString("file");
  sstable::SSTableReader reader(File::openFile(input_file, File::O_READ));
  if (reader.bodySize() == 0) {
    fnord::logWarning("fnord.sstablescan", "sstable is unfinished");
  }

  sstable::SSTableColumnSchema schema;
  schema.loadIndex(&reader);

  /* set up scan */
  sstable::SSTableScan scan(&schema);
  if (flags.isSet("limit")) {
    scan.setLimit(flags.getInt("limit"));
  }

  if (flags.isSet("offset")) {
    scan.setOffset(flags.getInt("offset"));
  }

  if (flags.isSet("order_by")) {
    scan.setOrderBy(flags.getString("order_by"), flags.getString("order_fn"));
  }

  /* execute scan */
  auto headers = scan.columnNames();
  fnord::iputs("$0", StringUtil::join(headers, ";"));

  auto cursor = reader.getCursor();
  scan.execute(cursor.get(), [] (const Vector<String> row) {
    fnord::iputs("$0", StringUtil::join(row, ";"));
  });

  return 0;
}

<|endoftext|>


<commit_before>#ifndef GRAPH_HPP
#define GRAPH_HPP

#include "memory.hpp"
#include <random>

#define BETA_PRECISION 10000

class Graph {
protected:
    std::vector<std::string> nodes_;
    bool **connections_;

public:
    /* Fetch the adjacency list for a particular node */
    std::vector<std::string> adjacencyList( std::string node_name ) {

        unsigned int count = 0;
        for (auto node : nodes_) {
            if (node == node_name) {
                break;
            } else {
                count++;
            }
        }
        if (count == nodes_.size()) {
            std::cerr << "Graph: Invalid fetch request." << std::endl;
            abort();
        }

        std::vector<std::string> adjacency_list;
        for (unsigned int index = 0; index < nodes_.size(); index++) {
            if (connections_[count][index]) {
                adjacency_list.push_back(nodes_[index]);
            }
        }
        return adjacency_list;
    }
};

/* Watts-Strogatz Graph */
class WattsStrogatz : public Graph {
public:
    WattsStrogatz( std::vector<std::string> nodes, unsigned int k, double beta ) {

        /* Initialize the connection matrix */
        nodes_ = nodes;
        unsigned int num_nodes = nodes.size();
        connections_ = new bool*[num_nodes];
        for (unsigned int index_x = 0; index_x < num_nodes; index_x++) {
            connections_[index_x] = new bool[num_nodes];
            for (unsigned int index_y = 0; index_y < num_nodes; index_y++) {
                connections_[index_x][index_y] = false;
            }
        }
        unsigned int left  = k / 2;
        unsigned int right = k - left;
        unsigned precision_beta = (unsigned int) (beta * BETA_PRECISION);

        /* Setup the ring lattice with N nodes, each of degree K */
        for (unsigned int index = 0; index < num_nodes; index++) {
            for (unsigned int node_index = 1; node_index <= left; node_index++) {
                unsigned int left_index = (index + num_nodes - node_index) % num_nodes;
                connections_[index][left_index] = true;
                connections_[left_index][index] = true;
            }
            for (unsigned int node_index = 1; node_index <= right; node_index++) {
                unsigned int right_index = (index + node_index) % num_nodes;
                connections_[index][right_index] = true;
                connections_[right_index][index] = true;
            }
        }

        /* Rewire each edge with probability beta */
        std::default_random_engine generator;
        std::uniform_int_distribution<int> precision_dist(0, BETA_PRECISION-1);
        std::uniform_int_distribution<int> node_dist(0, num_nodes-1);

        for (unsigned int index = 0; index < num_nodes; index++) {
            for (unsigned int node_index = 0; node_index < num_nodes; node_index++) {
                if (!connections_[index][node_index]) continue;
                auto rand_num = (unsigned int) precision_dist(generator);
                if (rand_num >= precision_beta) continue;

                unsigned int new_index = 0;
                while(1) {
                    new_index = (unsigned int) node_dist(generator);
                    if ((new_index != index) && (new_index != node_index)) break;
                }
                connections_[index][node_index] = false;
                connections_[node_index][index] = false;
                connections_[index][new_index] = false;
                connections_[new_index][index] = false;
            }
        }
    }
};

/* Barabasi-Albert Graph */
class BarabasiAlbert : public Graph {
public:
    BarabasiAlbert( std::vector<std::string> nodes, unsigned int m, double a ) {

        /* Create the initial fully connected graph using m+1 nodes */
        nodes_ = nodes;
        unsigned int num_nodes = nodes.size();
        if (m >= num_nodes) {
            std::cerr << "Barabasi-Albert Graph: Input 'm' >= No. of Nodes." << std::endl;
            abort();
        }
        connections_ = new bool*[num_nodes];
        unsigned int *degree = new unsigned int[num_nodes];
        for (unsigned int index_x = 0; index_x < num_nodes; index_x++) {
            connections_[index_x] = new bool[num_nodes];
            degree[index_x] = 0;
            for (unsigned int index_y = 0; index_y <= m; index_y++) {
                if (index_x <= m && index_x != index_y) {
                    connections_[index_x][index_y] = true;
                    degree[index_x]++;
                } else {
                    connections_[index_x][index_y] = false;
                }
            }
            for (unsigned int index_y = m+1; index_y < num_nodes; index_y++) {
                connections_[index_x][index_y] = false;
            }
        }
        unsigned int total_degrees = m*(m+1);

        std::default_random_engine generator;
        std::uniform_real_distribution<double> r_dist(0.0, 1.0);

        /* For each new nodes, create atmost m new edges */
        for (unsigned int new_node_index = m+1; new_node_index < num_nodes; new_node_index++) {

            std::uniform_int_distribution<int> node_dist(0, new_node_index-1);
            for (unsigned int edge_cnt = 0; edge_cnt < m; edge_cnt++) {

                /* Preferential Attachment Growth */
                unsigned int i = (unsigned int) node_dist(generator);
                double p = ((double) degree[i]) / total_degrees;
                p = pow(p, a);
                double r = r_dist(generator);
                if (p >= r) continue; // no new edge is created

                /* New edge is created if it already doesn't exist */
                if (!connections_[new_node_index][i]) {
                    connections_[new_node_index][i] = true;
                    connections_[i][new_node_index] = true;
                    degree[i]++;
                    degree[new_node_index]++;
                    total_degrees += 2;
                }
            }
        }
    }
};

#endif
<commit_msg>moved to networ.hpp<commit_after><|endoftext|>


<commit_before>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved.  Released under a BSD
license as described in the file LICENSE.
 */
#ifdef _WIN32
#include <WinSock2.h>
#else
#include <sys/socket.h>
#include <arpa/inet.h>
#endif
#include <sys/timeb.h>
#include "parse_args.h"
#include "parse_regressor.h"
#include "accumulate.h"
#include "best_constant.h"
#include "vw_exception.h"
#include <fstream>

using namespace std;

vw& setup(int argc, char* argv[])
{ vw& all = parse_args(argc, argv);
  io_buf model;
  parse_regressor_args(all, model);
  parse_modules(all, model);
  parse_sources(all, model);

  all.vw_is_main = true;

  if (!all.quiet && !all.bfgs && !all.searchstr && !all.vm.count("audit_regressor"))
  { std::cerr << std::left
              << std::setw(shared_data::col_avg_loss) << std::left << "average"
              << " "
              << std::setw(shared_data::col_since_last) << std::left << "since"
              << " "
              << std::right
              << std::setw(shared_data::col_example_counter) << "example"
              << " "
              << std::setw(shared_data::col_example_weight) << "example"
              << " "
              << std::setw(shared_data::col_current_label) << "current"
              << " "
              << std::setw(shared_data::col_current_predict) << "current"
              << " "
              << std::setw(shared_data::col_current_features) << "current"
              << std::endl;
    std::cerr << std::left
              << std::setw(shared_data::col_avg_loss) << std::left << "loss"
              << " "
              << std::setw(shared_data::col_since_last) << std::left << "last"
              << " "
              << std::right
              << std::setw(shared_data::col_example_counter) << "counter"
              << " "
              << std::setw(shared_data::col_example_weight) << "weight"
              << " "
              << std::setw(shared_data::col_current_label) << "label"
              << " "
              << std::setw(shared_data::col_current_predict) << "predict"
              << " "
              << std::setw(shared_data::col_current_features) << "features"
              << std::endl;
  }

  return all;
}

int main(int argc, char *argv[])
{ try
  { // support multiple vw instances for training of the same datafile for the same instance
    vector<vw*> alls;
    if (argc == 3 && !strcmp(argv[1], "--args"))
    { std::fstream arg_file(argv[2]);

      int line_count = 1;
      std::string line;
      while (std::getline(arg_file, line))
      { std::stringstream sstr;
        sstr << line << " -f model." << (line_count++);

        std::cout << sstr.str() << endl;
        string str = sstr.str();
        const char* new_args = str.c_str();

        int l_argc;
        char** l_argv = VW::get_argv_from_string(new_args, l_argc);

        alls.push_back(&setup(l_argc, l_argv));
      }
    }
    else
    { alls.push_back(&setup(argc, argv));
    }

    vw& all = *alls[0];

    struct timeb t_start, t_end;
    ftime(&t_start);

    VW::start_parser(all);
    if (alls.size() == 1)
      LEARNER::generic_driver(all);
    else
      LEARNER::generic_driver(alls);

    VW::end_parser(all);

    ftime(&t_end);
    double net_time = (int) (1000.0 * (t_end.time - t_start.time) + (t_end.millitm - t_start.millitm));
    if(!all.quiet && all.all_reduce != nullptr)
      cerr<<"Net time taken by process = "<<net_time/(double)(1000)<<" seconds\n";

    for (vw* v : alls)
    { VW::sync_stats(*v);
      VW::finish(*v);
    }
  }
  catch (VW::vw_exception& e)
  { cerr << "vw (" << e.Filename() << ":" << e.LineNumber() << "): " << e.what() << endl;
  }
  catch (exception& e)
  { // vw is implemented as a library, so we use 'throw runtime_error()'
    // error 'handling' everywhere.  To reduce stderr pollution
    // everything gets caught here & the error message is printed
    // sans the excess exception noise, and core dump.
    cerr << "vw: " << e.what() << endl;
    // cin.ignore();
    exit(1);
  }
  // cin.ignore();
  return 0;
}

<commit_msg>Update main.cc<commit_after>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved.  Released under a BSD
license as described in the file LICENSE.
 */
#ifdef _WIN32
#include <WinSock2.h>
#else
#include <sys/socket.h>
#include <arpa/inet.h>
#endif
#include <sys/timeb.h>
#include "parse_args.h"
#include "parse_regressor.h"
#include "accumulate.h"
#include "best_constant.h"
#include "vw_exception.h"
#include <fstream>

using namespace std;

vw* setup(int argc, char* argv[])
{ vw* all = VW::initialize(argc, argv);

  all->vw_is_main = true;

  if (!all->quiet && !all->bfgs && !all->searchstr)
  { std::cerr << std::left
              << std::setw(shared_data::col_avg_loss) << std::left << "average"
              << " "
              << std::setw(shared_data::col_since_last) << std::left << "since"
              << " "
              << std::right
              << std::setw(shared_data::col_example_counter) << "example"
              << " "
              << std::setw(shared_data::col_example_weight) << "example"
              << " "
              << std::setw(shared_data::col_current_label) << "current"
              << " "
              << std::setw(shared_data::col_current_predict) << "current"
              << " "
              << std::setw(shared_data::col_current_features) << "current"
              << std::endl;
    std::cerr << std::left
              << std::setw(shared_data::col_avg_loss) << std::left << "loss"
              << " "
              << std::setw(shared_data::col_since_last) << std::left << "last"
              << " "
              << std::right
              << std::setw(shared_data::col_example_counter) << "counter"
              << " "
              << std::setw(shared_data::col_example_weight) << "weight"
              << " "
              << std::setw(shared_data::col_current_label) << "label"
              << " "
              << std::setw(shared_data::col_current_predict) << "predict"
              << " "
              << std::setw(shared_data::col_current_features) << "features"
              << std::endl;
  }

  return all;
}

int main(int argc, char *argv[])
{ try
  { // support multiple vw instances for training of the same datafile for the same instance
    vector<vw*> alls;
    if (argc == 3 && !strcmp(argv[1], "--args"))
    { std::fstream arg_file(argv[2]);

      int line_count = 1;
      std::string line;
      while (std::getline(arg_file, line))
      { std::stringstream sstr;
        sstr << line << " -f model." << (line_count++);

        std::cout << sstr.str() << endl;
        string str = sstr.str();
        const char* new_args = str.c_str();

        int l_argc;
        char** l_argv = VW::get_argv_from_string(new_args, l_argc);

        alls.push_back(setup(l_argc, l_argv));
      }
    }
    else
    { alls.push_back(setup(argc, argv));
    }

    vw& all = *alls[0];

    struct timeb t_start, t_end;
    ftime(&t_start);

    VW::start_parser(all);
    if (alls.size() == 1)
      LEARNER::generic_driver(all);
    else
      LEARNER::generic_driver(alls);

    VW::end_parser(all);

    ftime(&t_end);
    double net_time = (int) (1000.0 * (t_end.time - t_start.time) + (t_end.millitm - t_start.millitm));
    if(!all.quiet && all.all_reduce != nullptr)
      cerr<<"Net time taken by process = "<<net_time/(double)(1000)<<" seconds\n";

    for (vw* v : alls)
    { VW::sync_stats(*v);
      VW::finish(*v);
    }
  }
  catch (VW::vw_exception& e)
  { cerr << "vw (" << e.Filename() << ":" << e.LineNumber() << "): " << e.what() << endl;
  }
  catch (exception& e)
  { // vw is implemented as a library, so we use 'throw runtime_error()'
    // error 'handling' everywhere.  To reduce stderr pollution
    // everything gets caught here & the error message is printed
    // sans the excess exception noise, and core dump.
    cerr << "vw: " << e.what() << endl;
    // cin.ignore();
    exit(1);
  }
  // cin.ignore();
  return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: LineProperties.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 13:25:33 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "LineProperties.hxx"
#include "macros.hxx"

#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_
#include <com/sun/star/drawing/LineStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINEDASH_HPP_
#include <com/sun/star/drawing/LineDash.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINEJOINT_HPP_
#include <com/sun/star/drawing/LineJoint.hpp>
#endif
#ifndef _COM_SUN_STAR_STYLE_XSTYLE_HPP_
#include <com/sun/star/style/XStyle.hpp>
#endif

#ifndef _COM_SUN_STAR_CHART2_FILLBITMAP_HPP_
#include <com/sun/star/chart2/FillBitmap.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_TRANSPARENCYSTYLE_HPP_
#include <com/sun/star/chart2/TransparencyStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_NUMBERFORMAT_HPP_
#include <com/sun/star/chart2/NumberFormat.hpp>
#endif

using namespace ::com::sun::star;

using ::com::sun::star::beans::Property;

namespace chart
{

void LineProperties::AddPropertiesToVector(
    ::std::vector< Property > & rOutProperties,
    bool bIncludeStyleProperties /* = false */ )
{
    // Line Properties
    // ---------------
    rOutProperties.push_back(
        Property( C2U( "LineStyle" ),
                  PROP_LINE_STYLE,
                  ::getCppuType( reinterpret_cast< const drawing::LineStyle * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));
    rOutProperties.push_back(
        Property( C2U( "LineWidth" ),
                  PROP_LINE_WIDTH,
                  ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));
    rOutProperties.push_back(
        Property( C2U( "LineDash" ),
                  PROP_LINE_DASH,
                  ::getCppuType( reinterpret_cast< const drawing::LineDash * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEVOID ));
    rOutProperties.push_back(
        Property( C2U( "LineColor" ),
                  PROP_LINE_COLOR,
                  ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));
    rOutProperties.push_back(
        Property( C2U( "LineTransparence" ),
                  PROP_LINE_TRANSPARENCE,
                  ::getCppuType( reinterpret_cast< const sal_Int16 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));
    rOutProperties.push_back(
        Property( C2U( "LineJoint" ),
                  PROP_LINE_JOINT,
                  ::getCppuType( reinterpret_cast< const drawing::LineJoint * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));
}

void LineProperties::AddDefaultsToMap(
    ::chart::helper::tPropertyValueMap & rOutMap,
    bool bIncludeStyleProperties /* = false */ )
{
    OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINE_STYLE ));
    rOutMap[ PROP_LINE_STYLE ] =
        uno::makeAny( drawing::LineStyle_SOLID );
    OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINE_WIDTH ));
    rOutMap[ PROP_LINE_WIDTH ] =
        uno::makeAny( sal_Int32( 0 ) );
    OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINE_COLOR ));
    rOutMap[ PROP_LINE_COLOR ] =
        uno::makeAny( sal_Int32( 0x000000 ) );  // black
    OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINE_TRANSPARENCE ));
    rOutMap[ PROP_LINE_TRANSPARENCE ] =
        uno::makeAny( sal_Int16( 0 ) );
    OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINE_JOINT ));
    rOutMap[ PROP_LINE_JOINT ] =
        uno::makeAny( drawing::LineJoint_NONE );
}

} //  namespace chart
<commit_msg>INTEGRATION: CWS chart2mst3 (1.2.4); FILE MERGED 2006/10/18 17:17:23 bm 1.2.4.10: RESYNC: (1.3-1.4); FILE MERGED 2006/04/10 12:25:15 iha 1.2.4.9: api restructure axis, grids, scales and increments 2006/03/12 01:03:02 iha 1.2.4.8: offer LineDash property 2005/10/07 12:09:23 bm 1.2.4.7: RESYNC: (1.2-1.3); FILE MERGED 2005/07/14 12:33:02 iha 1.2.4.6: remove unused parameter 'bIncludeStyleProperties' 2005/07/14 11:33:54 iha 1.2.4.5: use identical fast-property-IDs for lineproperties everywhere 2005/07/12 12:57:09 bm 1.2.4.4: use named properties for gradients etc. in chart model 2005/06/15 18:20:27 iha 1.2.4.3: cleanup 2005/04/13 11:29:15 iha 1.2.4.2: removed unused include 2004/02/13 16:51:52 bm 1.2.4.1: join from changes on branch bm_post_chart01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: LineProperties.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 19:00:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "LineProperties.hxx"
#include "macros.hxx"

#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_
#include <com/sun/star/drawing/LineStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINEDASH_HPP_
#include <com/sun/star/drawing/LineDash.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINEJOINT_HPP_
#include <com/sun/star/drawing/LineJoint.hpp>
#endif

using namespace ::com::sun::star;

using ::com::sun::star::beans::Property;

namespace chart
{

void LineProperties::AddPropertiesToVector(
    ::std::vector< Property > & rOutProperties )
{
    // Line Properties see service drawing::LineProperties
    // ---------------
    rOutProperties.push_back(
        Property( C2U( "LineStyle" ),
                  PROP_LINE_STYLE,
                  ::getCppuType( reinterpret_cast< const drawing::LineStyle * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

     rOutProperties.push_back(
         Property( C2U( "LineDash" ),
                   PROP_LINE_DASH,
                   ::getCppuType( reinterpret_cast< const drawing::LineDash * >(0)),
                   beans::PropertyAttribute::BOUND
                   | beans::PropertyAttribute::MAYBEVOID ));

//not in service description
    rOutProperties.push_back(
        Property( C2U( "LineDashName" ),
                  PROP_LINE_DASH_NAME,
                  ::getCppuType( reinterpret_cast< const ::rtl::OUString * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT
                  | beans::PropertyAttribute::MAYBEVOID ));

    rOutProperties.push_back(
        Property( C2U( "LineColor" ),
                  PROP_LINE_COLOR,
                  ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "LineTransparence" ),
                  PROP_LINE_TRANSPARENCE,
                  ::getCppuType( reinterpret_cast< const sal_Int16 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "LineWidth" ),
                  PROP_LINE_WIDTH,
                  ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "LineJoint" ),
                  PROP_LINE_JOINT,
                  ::getCppuType( reinterpret_cast< const drawing::LineJoint * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));
}

void LineProperties::AddDefaultsToMap(
    ::chart::tPropertyValueMap & rOutMap )
{
    OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINE_STYLE ));
    rOutMap[ PROP_LINE_STYLE ] =
        uno::makeAny( drawing::LineStyle_SOLID );
    OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINE_WIDTH ));
    rOutMap[ PROP_LINE_WIDTH ] =
        uno::makeAny( sal_Int32( 0 ) );
    OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINE_COLOR ));
    rOutMap[ PROP_LINE_COLOR ] =
        uno::makeAny( sal_Int32( 0x000000 ) );  // black
    OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINE_TRANSPARENCE ));
    rOutMap[ PROP_LINE_TRANSPARENCE ] =
        uno::makeAny( sal_Int16( 0 ) );
    OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LINE_JOINT ));
    rOutMap[ PROP_LINE_JOINT ] =
        uno::makeAny( drawing::LineJoint_NONE );
}

//static
bool LineProperties::IsLineVisible( const ::com::sun::star::uno::Reference<
        ::com::sun::star::beans::XPropertySet >& xLineProperties )
{
    bool bRet = false;
    try
    {
        if( xLineProperties.is() )
        {
            drawing::LineStyle aLineStyle(drawing::LineStyle_SOLID);
            xLineProperties->getPropertyValue( C2U( "LineStyle" ) ) >>= aLineStyle;
            if( aLineStyle != drawing::LineStyle_NONE )
            {
                sal_Int16 nLineTransparence=0;
                xLineProperties->getPropertyValue( C2U( "LineTransparence" ) ) >>= nLineTransparence;
                if(100!=nLineTransparence)
                {
                    bRet = true;
                }
            }
        }
    }
    catch( const uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }
    return bRet;
}

//static
void LineProperties::SetLineVisible( const ::com::sun::star::uno::Reference<
    ::com::sun::star::beans::XPropertySet >& xLineProperties )
{
    try
    {
        if( xLineProperties.is() )
        {
            drawing::LineStyle aLineStyle(drawing::LineStyle_SOLID);
            xLineProperties->getPropertyValue( C2U( "LineStyle" ) ) >>= aLineStyle;
            if( aLineStyle == drawing::LineStyle_NONE )
                xLineProperties->setPropertyValue( C2U( "LineStyle" ), uno::makeAny( drawing::LineStyle_SOLID ) );

            sal_Int16 nLineTransparence=0;
            xLineProperties->getPropertyValue( C2U( "LineTransparence" ) ) >>= nLineTransparence;
            if(100==nLineTransparence)
                xLineProperties->setPropertyValue( C2U( "LineTransparence" ), uno::makeAny( sal_Int16(0) ) );
        }
    }
    catch( const uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }
}

//static
void LineProperties::SetLineInvisible( const ::com::sun::star::uno::Reference<
    ::com::sun::star::beans::XPropertySet >& xLineProperties )
{
    try
    {
        if( xLineProperties.is() )
        {
            drawing::LineStyle aLineStyle(drawing::LineStyle_SOLID);
            xLineProperties->getPropertyValue( C2U( "LineStyle" ) ) >>= aLineStyle;
            if( aLineStyle != drawing::LineStyle_NONE )
                xLineProperties->setPropertyValue( C2U( "LineStyle" ), uno::makeAny( drawing::LineStyle_NONE ) );
        }
    }
    catch( const uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }
}

} //  namespace chart
<|endoftext|>