<commit_before>#include <osg/Texture2D>
#include <osg/Material>
#include <osg/LightSource>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/ShapeDrawable>
#include <osg/CameraNode>
#include <osg/TexGenNode>
#include <osg/Notify>
#include <osg/io_utils>

#include "CreateShadowedScene.h"

using namespace osg;

class UpdateCameraAndTexGenCallback : public osg::NodeCallback
{
    public:

        UpdateCameraAndTexGenCallback(const osg::Vec3& position, osg::CameraNode* cameraNode, osg::TexGenNode* texgenNode):
            _position(position),
            _cameraNode(cameraNode),
            _texgenNode(texgenNode)
        {
        }

        virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
        {
            // first update subgraph to make sure objects are all moved into postion
            traverse(node,nv);

            // now compute the camera's view and projection matrix to point at the shadower (the camera's children)
            osg::BoundingSphere bs;
            for(unsigned int i=0; i<_cameraNode->getNumChildren(); ++i)
            {
                bs.expandBy(_cameraNode->getChild(i)->getBound());
            }

            if (!bs.valid())
            {
                osg::notify(osg::WARN) << "bb invalid"<<_cameraNode.get()<<std::endl;
                return;
            }

            float centerDistance = (_position-bs.center()).length();

            float znear = centerDistance-bs.radius();
            float zfar  = centerDistance+bs.radius();
            float zNearRatio = 0.001f;
            if (znear<zfar*zNearRatio) znear = zfar*zNearRatio;

            float top   = (bs.radius()/centerDistance)*znear;
            float right = top;

            _cameraNode->setReferenceFrame(osg::CameraNode::ABSOLUTE_RF);
            _cameraNode->setProjectionMatrixAsFrustum(-right,right,-top,top,znear,zfar);
            _cameraNode->setViewMatrixAsLookAt(_position,bs.center(),osg::Vec3(0.0f,1.0f,0.0f));

            // compute the matrix which takes a vertex from local coords into tex coords
            // will use this later to specify osg::TexGen..
            osg::Matrix MVPT = _cameraNode->getViewMatrix() *
                               _cameraNode->getProjectionMatrix() *
                               osg::Matrix::translate(1.0,1.0,1.0) *
                               osg::Matrix::scale(0.5f,0.5f,0.5f);

            _texgenNode->getTexGen()->setMode(osg::TexGen::EYE_LINEAR);
            _texgenNode->getTexGen()->setPlanesFromMatrix(MVPT);

        }

    protected:

        virtual ~UpdateCameraAndTexGenCallback() {}

        osg::Vec3                     _position;
        osg::ref_ptr<osg::CameraNode> _cameraNode;
        osg::ref_ptr<osg::TexGenNode> _texgenNode;

};

osg::Group* createShadowedScene(osg::Node* shadower,osg::Node* shadowed,const osg::Vec3& lightPosition,float radius,unsigned int unit)
{
    osg::Group* group = new osg::Group;

    // add light source
    {
        osg::LightSource* lightSource = new osg::LightSource;
        lightSource->getLight()->setPosition(osg::Vec4(lightPosition,1.0f));
        lightSource->getLight()->setLightNum(0);

        group->addChild(lightSource);

        osg::Geode* lightgeode = new osg::Geode;
        lightgeode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
        lightgeode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(lightPosition,radius)));
        group->addChild(lightgeode);
    }

    osg::Vec4 ambientLightColor(0.2,0.2f,0.2f,1.0f);

    // add the shadower and shadowed.
    group->addChild(shadower);
    group->addChild(shadowed);

    unsigned int tex_width = 512;
    unsigned int tex_height = 512;

    osg::Texture2D* texture = new osg::Texture2D;
    texture->setTextureSize(tex_width, tex_height);
    texture->setInternalFormat(GL_RGB);
    texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
    texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
    texture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::CLAMP_TO_BORDER);
    texture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::CLAMP_TO_BORDER);
    texture->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));

    // set up the render to texture camera.
    {

        // create the camera
        osg::CameraNode* camera = new osg::CameraNode;

        camera->setClearColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));

        // set viewport
// Both of these methods should produce the same result, but they don't.
#if 1
        camera->setViewport(0,tex_height/2,tex_width,tex_height/2);
#else
        camera->setViewport(0,0,tex_width,tex_height);
    osg::Viewport* vp = new osg::Viewport(0,tex_height/2,tex_width,tex_height/2);
    camera->getOrCreateStateSet()->setAttribute(vp);
#endif

        // set the camera to render before the main camera.
        camera->setRenderOrder(osg::CameraNode::PRE_RENDER);

        // tell the camera to use OpenGL frame buffer object where supported.
        camera->setRenderTargetImplementation(osg::CameraNode::FRAME_BUFFER_OBJECT);

        // attach the texture and use it as the color buffer.
        camera->attach(osg::CameraNode::COLOR_BUFFER, texture);

        // add subgraph to render
        camera->addChild(shadower);

        osg::StateSet* stateset = camera->getOrCreateStateSet();

        // make the material black for a shadow.
        osg::Material* material = new osg::Material;
        material->setAmbient(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
        material->setDiffuse(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
        material->setEmission(osg::Material::FRONT_AND_BACK,ambientLightColor);
        material->setShininess(osg::Material::FRONT_AND_BACK,0.0f);
        stateset->setAttribute(material,osg::StateAttribute::OVERRIDE);

        group->addChild(camera);

        // create the texgen node to project the tex coords onto the subgraph
        osg::TexGenNode* texgenNode = new osg::TexGenNode;
        texgenNode->setTextureUnit(unit);
        group->addChild(texgenNode);

        // set an update callback to keep moving the camera and tex gen in the right direction.
        group->setUpdateCallback(new UpdateCameraAndTexGenCallback(lightPosition, camera, texgenNode));
    }

    // set the shadowed subgraph so that it uses the texture and tex gen settings.
    {
        osg::StateSet* stateset = shadowed->getOrCreateStateSet();
        stateset->setTextureAttributeAndModes(unit,texture,osg::StateAttribute::ON);
        stateset->setTextureMode(unit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON);
        stateset->setTextureMode(unit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON);
        stateset->setTextureMode(unit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
        stateset->setTextureMode(unit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON);
    }

    // set hud to render shadow texture, just for interest
    {
        osg::Geode* geode = new osg::Geode;
        osg::Geometry* geom = osg::createTexturedQuadGeometry(osg::Vec3(0,0,0),osg::Vec3(100.0,0.0,0.0),osg::Vec3(0.0,100.0,0.0));
        geom->getOrCreateStateSet()->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
        geom->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
        geode->addDrawable(geom);

        osg::CameraNode* camera = new osg::CameraNode;

        // set the projection matrix
        camera->setProjectionMatrix(osg::Matrix::ortho2D(0,100,0,100));

        // set the view matrix
        camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
        camera->setViewMatrix(osg::Matrix::identity());

        camera->setViewport(50,50,100,100);

        // only clear the depth buffer
        camera->setClearMask(GL_DEPTH_BUFFER_BIT);

        // draw subgraph after main camera view.
        camera->setRenderOrder(osg::CameraNode::POST_RENDER);

        camera->addChild(geode);

        group->addChild(camera);

    }

    return group;
}
<commit_msg>Removed debugging code.<commit_after>#include <osg/Texture2D>
#include <osg/Material>
#include <osg/LightSource>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/ShapeDrawable>
#include <osg/CameraNode>
#include <osg/TexGenNode>
#include <osg/Notify>
#include <osg/io_utils>

#include "CreateShadowedScene.h"

using namespace osg;

class UpdateCameraAndTexGenCallback : public osg::NodeCallback
{
    public:

        UpdateCameraAndTexGenCallback(const osg::Vec3& position, osg::CameraNode* cameraNode, osg::TexGenNode* texgenNode):
            _position(position),
            _cameraNode(cameraNode),
            _texgenNode(texgenNode)
        {
        }

        virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
        {
            // first update subgraph to make sure objects are all moved into postion
            traverse(node,nv);

            // now compute the camera's view and projection matrix to point at the shadower (the camera's children)
            osg::BoundingSphere bs;
            for(unsigned int i=0; i<_cameraNode->getNumChildren(); ++i)
            {
                bs.expandBy(_cameraNode->getChild(i)->getBound());
            }

            if (!bs.valid())
            {
                osg::notify(osg::WARN) << "bb invalid"<<_cameraNode.get()<<std::endl;
                return;
            }

            float centerDistance = (_position-bs.center()).length();

            float znear = centerDistance-bs.radius();
            float zfar  = centerDistance+bs.radius();
            float zNearRatio = 0.001f;
            if (znear<zfar*zNearRatio) znear = zfar*zNearRatio;

            float top   = (bs.radius()/centerDistance)*znear;
            float right = top;

            _cameraNode->setReferenceFrame(osg::CameraNode::ABSOLUTE_RF);
            _cameraNode->setProjectionMatrixAsFrustum(-right,right,-top,top,znear,zfar);
            _cameraNode->setViewMatrixAsLookAt(_position,bs.center(),osg::Vec3(0.0f,1.0f,0.0f));

            // compute the matrix which takes a vertex from local coords into tex coords
            // will use this later to specify osg::TexGen..
            osg::Matrix MVPT = _cameraNode->getViewMatrix() *
                               _cameraNode->getProjectionMatrix() *
                               osg::Matrix::translate(1.0,1.0,1.0) *
                               osg::Matrix::scale(0.5f,0.5f,0.5f);

            _texgenNode->getTexGen()->setMode(osg::TexGen::EYE_LINEAR);
            _texgenNode->getTexGen()->setPlanesFromMatrix(MVPT);

        }

    protected:

        virtual ~UpdateCameraAndTexGenCallback() {}

        osg::Vec3                     _position;
        osg::ref_ptr<osg::CameraNode> _cameraNode;
        osg::ref_ptr<osg::TexGenNode> _texgenNode;

};

osg::Group* createShadowedScene(osg::Node* shadower,osg::Node* shadowed,const osg::Vec3& lightPosition,float radius,unsigned int unit)
{
    osg::Group* group = new osg::Group;

    // add light source
    {
        osg::LightSource* lightSource = new osg::LightSource;
        lightSource->getLight()->setPosition(osg::Vec4(lightPosition,1.0f));
        lightSource->getLight()->setLightNum(0);

        group->addChild(lightSource);

        osg::Geode* lightgeode = new osg::Geode;
        lightgeode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
        lightgeode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(lightPosition,radius)));
        group->addChild(lightgeode);
    }

    osg::Vec4 ambientLightColor(0.2,0.2f,0.2f,1.0f);

    // add the shadower and shadowed.
    group->addChild(shadower);
    group->addChild(shadowed);

    unsigned int tex_width = 512;
    unsigned int tex_height = 512;

    osg::Texture2D* texture = new osg::Texture2D;
    texture->setTextureSize(tex_width, tex_height);
    texture->setInternalFormat(GL_RGB);
    texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
    texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
    texture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::CLAMP_TO_BORDER);
    texture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::CLAMP_TO_BORDER);
    texture->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));

    // set up the render to texture camera.
    {

        // create the camera
        osg::CameraNode* camera = new osg::CameraNode;

        camera->setClearColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));

        // set viewport
        camera->setViewport(0,0,tex_width,tex_height);

        // set the camera to render before the main camera.
        camera->setRenderOrder(osg::CameraNode::PRE_RENDER);

        // tell the camera to use OpenGL frame buffer object where supported.
        camera->setRenderTargetImplementation(osg::CameraNode::FRAME_BUFFER_OBJECT);

        // attach the texture and use it as the color buffer.
        camera->attach(osg::CameraNode::COLOR_BUFFER, texture);

        // add subgraph to render
        camera->addChild(shadower);

        osg::StateSet* stateset = camera->getOrCreateStateSet();

        // make the material black for a shadow.
        osg::Material* material = new osg::Material;
        material->setAmbient(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
        material->setDiffuse(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
        material->setEmission(osg::Material::FRONT_AND_BACK,ambientLightColor);
        material->setShininess(osg::Material::FRONT_AND_BACK,0.0f);
        stateset->setAttribute(material,osg::StateAttribute::OVERRIDE);

        group->addChild(camera);

        // create the texgen node to project the tex coords onto the subgraph
        osg::TexGenNode* texgenNode = new osg::TexGenNode;
        texgenNode->setTextureUnit(unit);
        group->addChild(texgenNode);

        // set an update callback to keep moving the camera and tex gen in the right direction.
        group->setUpdateCallback(new UpdateCameraAndTexGenCallback(lightPosition, camera, texgenNode));
    }

    // set the shadowed subgraph so that it uses the texture and tex gen settings.
    {
        osg::StateSet* stateset = shadowed->getOrCreateStateSet();
        stateset->setTextureAttributeAndModes(unit,texture,osg::StateAttribute::ON);
        stateset->setTextureMode(unit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON);
        stateset->setTextureMode(unit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON);
        stateset->setTextureMode(unit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
        stateset->setTextureMode(unit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON);
    }

    // set hud to render shadow texture, just for interest
    {
        osg::Geode* geode = new osg::Geode;
        osg::Geometry* geom = osg::createTexturedQuadGeometry(osg::Vec3(0,0,0),osg::Vec3(100.0,0.0,0.0),osg::Vec3(0.0,100.0,0.0));
        geom->getOrCreateStateSet()->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
        geom->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
        geode->addDrawable(geom);

        osg::CameraNode* camera = new osg::CameraNode;

        // set the projection matrix
        camera->setProjectionMatrix(osg::Matrix::ortho2D(0,100,0,100));

        // set the view matrix
        camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
        camera->setViewMatrix(osg::Matrix::identity());

        camera->setViewport(50,50,100,100);

        // only clear the depth buffer
        camera->setClearMask(GL_DEPTH_BUFFER_BIT);

        // draw subgraph after main camera view.
        camera->setRenderOrder(osg::CameraNode::POST_RENDER);

        camera->addChild(geode);

        group->addChild(camera);

    }

    return group;
}
<|endoftext|>


<commit_before>#include <cassert>
#include <climits>
#include <cstring>

#include <vector>
#include <algorithm>

#include <omp.h>

#include "../CSR.hpp"

using namespace std;

void getInversePerm(int *inversePerm, const int *perm, int n);

// compute prefix sum of levels
static void prefixSumOfLevels(
  int *prefixSum,
  const CSR *A, const int *levels, int numLevels)
{
  int *local_count = new int[omp_get_max_threads()*numLevels];
  int *local_sum_array = new int[omp_get_max_threads() + 1];

#pragma omp parallel
  {
    int nthreads = omp_get_num_threads();
    int tid = omp_get_thread_num();

    memset(local_count + tid*numLevels, 0, sizeof(int)*numLevels);

#pragma omp for
    for (int i = 0; i < A->m; ++i) {
      ++local_count[tid*numLevels + levels[i]];
    }

    int lPerThread = (numLevels + nthreads - 1)/nthreads;
    int lBegin = min(lPerThread*tid, numLevels);
    int lEnd = min(lBegin + lPerThread, numLevels);

    int local_sum = 0;

    for (int l = lBegin; l < lEnd; ++l) {
      prefixSum[l] = local_sum;
      for (int t = 0; t < nthreads; ++t) {
        local_sum += local_count[t*numLevels + l];
      }
    }

    local_sum_array[tid + 1] = local_sum;

#pragma omp barrier
    if (0 == tid)
    {
      for (int t = 1; t <= nthreads; ++t) {
        local_sum_array[t + 1] += local_sum_array[t];
      }
      assert(local_sum_array[nthreads] == A->m);
      prefixSum[numLevels] = A->m;
    }
#pragma omp barrier

    if (tid > 0) {
      local_sum = local_sum_array[tid];
      for (int l = lBegin; l < lEnd; ++l) {
        prefixSum[l] += local_sum;
      }
    }
  } // omp parallel

  delete[] local_count;
  delete[] local_sum_array;
}

int bfs(const CSR *A, int source, int *levels) {
  int numLevels = 0;
  levels[source] = numLevels;
  numLevels++;

  int *q = new int[A->m];
  int *nextQ = new int[A->m];
  q[0] = source;
  int qTail = 1;
  int nextQTail;

  while (qTail) {
    nextQTail = 0;
    for (int i = 0; i < qTail; ++i) {
      int u = q[i];
      assert(levels[u] == numLevels - 1);

      for (int j = A->rowPtr[u]; j < A->rowPtr[u + 1]; ++j) {
        int v = A->colIdx[j];
        if (levels[v] == INT_MAX) {
          levels[v] = levels[u] + 1;
          nextQ[nextQTail] = v;
          ++nextQTail;
        }
      }
    } // for each u in current level

    swap(q, nextQ);
    qTail = nextQTail;
    ++numLevels;
  } // while q not empty

  delete[] q;
  delete[] nextQ;

  return numLevels;
}

void CSR::getRCMPermutationNew(int *perm, int *inversePerm, int source /*=-1*/) const
{
  // 1. Start vertex
  // TODO: pseudo diameter heuristic
  assert(source >= 0 && source < m);

  // 2. BFS
  int *levels = new int[m];
#pragma omp parallel for
  for (int i = 0; i < m; ++i) {
    levels[i] = INT_MAX;
  }

  int numLevels = bfs(this, source, levels);

  // 3. Reorder
  int *prefixSum = new int[numLevels + 1];
  prefixSumOfLevels(prefixSum, this, levels, numLevels);

  inversePerm[0] = source;
  int read_offset = 0;
  int write_offset = 1;

  for (int l = 0; l < numLevels; ++l) {
    while (read_offset != prefixSum[l + 1]) {
      int u = inversePerm[read_offset];
      ++read_offset;
      vector<int> children;
      for (int j = rowPtr[u]; j < rowPtr[u + 1]; ++j) {
        int v = colIdx[j];
        if (levels[v] == l + 1) {
          children.push_back(v);
          levels[v] = -1;
        }
      }
      sort(children.begin(), children.end());
      for (int c : children) {
        inversePerm[write_offset] = c;
        ++write_offset;
      }
    }
  } // for each level
  delete[] levels;

  int *temp = new int[m];
  reverse_copy(inversePerm, inversePerm + m, temp);
  copy(temp, temp + m, inversePerm);
  delete[] temp;

  getInversePerm(perm, inversePerm, n);
}
<commit_msg>parallel bfs<commit_after>#include <cassert>
#include <climits>
#include <cstring>

#include <vector>
#include <algorithm>

#include <omp.h>

#include "../CSR.hpp"

using namespace std;

void getInversePerm(int *inversePerm, const int *perm, int n);

// compute prefix sum of levels
static void prefixSumOfLevels(
  int *prefixSum,
  const CSR *A, const int *levels, int numLevels)
{
  int *local_count = new int[omp_get_max_threads()*numLevels];
  int *local_sum_array = new int[omp_get_max_threads() + 1];

#pragma omp parallel
  {
    int nthreads = omp_get_num_threads();
    int tid = omp_get_thread_num();

    memset(local_count + tid*numLevels, 0, sizeof(int)*numLevels);

#pragma omp for
    for (int i = 0; i < A->m; ++i) {
      ++local_count[tid*numLevels + levels[i]];
    }

    int lPerThread = (numLevels + nthreads - 1)/nthreads;
    int lBegin = min(lPerThread*tid, numLevels);
    int lEnd = min(lBegin + lPerThread, numLevels);

    int local_sum = 0;

    for (int l = lBegin; l < lEnd; ++l) {
      prefixSum[l] = local_sum;
      for (int t = 0; t < nthreads; ++t) {
        local_sum += local_count[t*numLevels + l];
      }
    }

    local_sum_array[tid + 1] = local_sum;

#pragma omp barrier
    if (0 == tid)
    {
      for (int t = 1; t <= nthreads; ++t) {
        local_sum_array[t + 1] += local_sum_array[t];
      }
      assert(local_sum_array[nthreads] == A->m);
      prefixSum[numLevels] = A->m;
    }
#pragma omp barrier

    if (tid > 0) {
      local_sum = local_sum_array[tid];
      for (int l = lBegin; l < lEnd; ++l) {
        prefixSum[l] += local_sum;
      }
    }
  } // omp parallel

  delete[] local_count;
  delete[] local_sum_array;
}

int bfs(const CSR *A, int source, int *levels) {
  int numLevels = 0;
  levels[source] = numLevels;

  int *q[2];
  q[0] = new int[A->m*omp_get_max_threads()];
  q[1] = new int[A->m*omp_get_max_threads()];
  q[0][0] = source;

  int *qTail = new int[omp_get_max_threads()];
  qTail[0] = 1;

  int *qTailPrefixSum = new int[omp_get_max_threads() + 1];
  qTailPrefixSum[0] = 0;

  int *rowPtrs = new int[omp_get_max_threads()*A->m];
  rowPtrs[0] = 0;
  rowPtrs[1] = A->rowPtr[source + 1] - A->rowPtr[source];

  int *nnzPrefixSum = new int[omp_get_max_threads() + 1];
  nnzPrefixSum[0] = 0;
  nnzPrefixSum[1] = rowPtrs[1];

#pragma omp parallel
  {
  int tid = omp_get_thread_num();
  int nthreads = omp_get_num_threads();

  if (tid > 0) {
    qTail[tid] = 0;
    nnzPrefixSum[tid + 1] = 0;
  }

  while (true) {
#pragma omp barrier
#pragma omp master
    {
      for (int t = 0; t < nthreads; ++t) {
        qTailPrefixSum[t + 1] = qTailPrefixSum[t] + qTail[t];
        nnzPrefixSum[t + 1] += nnzPrefixSum[t];
      }
      ++numLevels;
    }
#pragma omp barrier

    if (qTailPrefixSum[nthreads] == 0) break;

    // partition based on # of nnz
    int nnzPerThread = (nnzPrefixSum[nthreads] + nthreads - 1)/nthreads;
    int tBegin = upper_bound(
        nnzPrefixSum, nnzPrefixSum + nthreads + 1,
        nnzPerThread*tid) -
      nnzPrefixSum - 1;
    int tEnd = upper_bound(
        nnzPrefixSum, nnzPrefixSum + nthreads + 1,
        nnzPerThread*(tid + 1)) -
      nnzPrefixSum - 1;
    assert(tBegin >= 0 && tBegin <= nthreads);
    assert(tEnd >= 0 && tEnd <= nthreads);
    assert(tBegin <= tEnd);

    int iBegin, iEnd;
    if (0 == tid) {
      iBegin = 0;
    }
    else if (tBegin == nthreads) {
      iBegin = qTail[tEnd - 1];
    }
    else {
      iBegin = upper_bound(
          rowPtrs + tBegin*A->m, rowPtrs + tBegin*A->m + qTail[tBegin],
          nnzPerThread*tid - nnzPrefixSum[tBegin]) -
        (rowPtrs + tBegin*A->m) - 1;
    }

    if (tEnd == nthreads) {
      iEnd = 0;
    }
    else {
      iEnd = upper_bound(
          rowPtrs + tEnd*A->m, rowPtrs + tEnd*A->m + qTail[tEnd],
          nnzPerThread*(tid + 1) - nnzPrefixSum[tEnd]) -
        (rowPtrs + tEnd*A->m) - 1;
    }

#pragma omp barrier

    int *tailPtr = q[numLevels%2] + tid*A->m;
    int *rowPtr = rowPtrs + tid*A->m;
    *rowPtr = 0;

    for (int t = tBegin; t <= tEnd; ++t) {
      for (int i = (t == tBegin ? iBegin : 0);
          i < (t == tEnd ? iEnd : qTail[t]);
          ++i) {
        int u = q[1 - numLevels%2][t*A->m + i];
        assert(levels[u] == numLevels - 1);

        for (int j = A->rowPtr[u]; j < A->rowPtr[u + 1]; ++j) {
          int v = A->colIdx[j];
          if (__sync_bool_compare_and_swap(levels + v, INT_MAX, numLevels)) {
            *tailPtr = v;
            *(rowPtr + 1) =
              *rowPtr + A->rowPtr[v + 1] - A->rowPtr[v];

            ++tailPtr;
            ++rowPtr;
          }
        }
      } // for each current node u
    }

#pragma omp barrier

    qTail[tid] = tailPtr - (q[numLevels%2] + tid*A->m);
    nnzPrefixSum[tid + 1] = *rowPtr;
  } // while true
  } // omp parallel

  delete[] q[0];
  delete[] q[1];
  delete[] rowPtrs;
  delete[] qTail;
  delete[] qTailPrefixSum;
  delete[] nnzPrefixSum;

  return numLevels;
}

void CSR::getRCMPermutationNew(int *perm, int *inversePerm, int source /*=-1*/) const
{
  // 1. Start vertex
  // TODO: pseudo diameter heuristic
  assert(source >= 0 && source < m);

  // 2. BFS
  int *levels = new int[m];
#pragma omp parallel for
  for (int i = 0; i < m; ++i) {
    levels[i] = INT_MAX;
  }

  int numLevels = bfs(this, source, levels);
  printf("numLevels = %d\n", numLevels);

  // 3. Reorder
  int *prefixSum = new int[numLevels + 1];
  prefixSumOfLevels(prefixSum, this, levels, numLevels);

  inversePerm[0] = source;
  int read_offset = 0;
  int write_offset = 1;

  for (int l = 0; l < numLevels; ++l) {
    while (read_offset != prefixSum[l + 1]) {
      int u = inversePerm[read_offset];
      ++read_offset;
      vector<int> children;
      for (int j = rowPtr[u]; j < rowPtr[u + 1]; ++j) {
        int v = colIdx[j];
        if (levels[v] == l + 1) {
          children.push_back(v);
          levels[v] = -1;
        }
      }
      sort(children.begin(), children.end());
      for (int c : children) {
        inversePerm[write_offset] = c;
        ++write_offset;
      }
    }
  } // for each level
  delete[] levels;

  int *temp = new int[m];
  reverse_copy(inversePerm, inversePerm + m, temp);
  copy(temp, temp + m, inversePerm);
  delete[] temp;

  getInversePerm(perm, inversePerm, n);
}
<|endoftext|>


<commit_before>/*!
@file

@copyright Edouard Alligand and Joel Falcou 2015-2017
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_BRIGAND_ALGORITHMS_WRAP_HPP
#define BOOST_BRIGAND_ALGORITHMS_WRAP_HPP

namespace brigand
{
  namespace lazy
  {
    template <class A, template<class...> class B> struct wrap;

    template<template<class...> class A, class... T, template<class...> class B>
    struct wrap<A<T...>, B>
    {
      using type = B<T...>;
    };
  }

  template<class A, template<class...> class B>
  using wrap = typename lazy::wrap<A, B>::type;
}
#endif
<commit_msg>Delete wrap.hpp<commit_after><|endoftext|>


<commit_before>#ifndef SERIALIZABLE_H
#define SERIALIZABLE_H

#include <string>

#include "manager.hpp"

#define SERIAL_START void serializer (JsonTree* _json_tree_, bool _json_op_, string _json_path_) {serialize (_json_op_, _json_path_, _json_tree_,
#define SERIAL_END ); }

namespace json {

class Serializable {
public:

  inline void serializeIn (JsonTree& tree, string p) {
    serializer(&tree, false, p);
  }

  inline void serializeOut (JsonTree& tree, string p) {
    serializer(&tree, true, p);
  }

protected:
  virtual void serializer (JsonTree* tree, bool b, string path) = 0;

  template <class... Args>
  static void serialize (bool _json_op_, string _json_path_, JsonTree* _json_tree_, Args... args) {
    if (_json_op_){
      _json_tree_->erase(_json_path_);
      _json_tree_->addVector(_json_path_);
      retribution (_json_tree_, 0, _json_path_, args...);
    } else {
      int i = 0;
      int size = _json_tree_->getSizeAt(_json_path_);
      initialize (_json_tree_, [&] ()
        {
          int aux = i;
          if (i < size - 1)
            i++;
          return _json_path_ + "." + to_string(aux);
        },
      args...);
    }
  }

  // Write
  template <typename t>
  void static retribution (JsonTree* tree, int index, string path, t* element) {
    tree->add(*element, path);
  }

  template <class t, class... Args>
  void static retribution (JsonTree* tree, int index, string path, t element, Args... args) {
    tree->add(*element, path);
    retribution (tree, index+1, path, args...);
  }

  // Vector

  template <class t>
  void static retribution (JsonTree* tree, int index, string path, vector <t>* vect) {

    tree->addVector(path);
    path = path + "." + to_string(index);

    for (int j = 0; j < vect->size(); j++)
      retribution (tree, j, path, &(*vect)[j]);

  }

  template <class t, class... Args>
  void static retribution (JsonTree* tree, int index, string path, vector<t>* vect, Args... args) {

    tree->addVector(path);
    string newPath = path + "." + to_string(index);

    for (int j = 0; j < vect->size(); j++)
      retribution (tree, j, newPath, &(*vect)[j]);

    retribution (tree, index+1, path, args...);
  }

  // Read
  template <typename t, class func>
  void static initialize (JsonTree* tree, func functor, t* element) {
    tree->get(*element, functor());
  }

  template <class t, class func, class... Args>
  void static initialize (JsonTree* tree, func functor, t element, Args... args) {
    tree->get(*element, functor());
    initialize (tree, functor, args...);
  }

  // Vector
  template <class t, class func>
  void static initialize (JsonTree* tree, func functor, vector<vector <t> >* vect) {
    string newPath = functor();
    int size = tree->getSizeAt(newPath);
    vect->resize (size);

    int i = 0;
    for (int j = 0; j < size; j++) {
      initialize (tree, [&] () {
        return newPath + "." + to_string(i);
      }, &(*vect)[j]);
      i++;
    }
  }

  template <class t, class func, class... Args>
  void static initialize (JsonTree* tree, func functor, vector <vector <t> >* vect, Args... args) {
    string newPath = functor();

    int size = tree->getSizeAt(newPath);
    vect->resize (size);

    int i = 0;
    for (int j = 0; j < vect->size(); j++) {
      initialize (tree, [&] () {
        return newPath + "." + to_string(i);
      }, &(*vect)[j]);
      i++;
    }
    initialize (tree, functor, args...);
  }

};

}
#endif // SERIALIZABLE_H

<commit_msg>Añadiendo capacidad de construir con puteros de objetos serializables<commit_after>#ifndef SERIALIZABLE_H
#define SERIALIZABLE_H

#include <string>
#include <type_traits>
#include "manager.hpp"

#define SERIAL_START void serializer (JsonTree* _json_tree_, bool _json_op_, string _json_path_) {serialize (_json_op_, _json_path_, _json_tree_,
#define SERIAL_END ); }

namespace json {

class Serializable {
public:

  inline void serializeIn (JsonTree& tree, string p) {
    serializer(&tree, false, p);
  }

  inline void serializeOut (JsonTree& tree, string p) {
    serializer(&tree, true, p);
  }

protected:
  virtual void serializer (JsonTree* tree, bool b, string path) = 0;

  template <class... Args>
  static void serialize (bool _json_op_, string _json_path_, JsonTree* _json_tree_, Args... args) {
    if (_json_op_){
      _json_tree_->erase(_json_path_);
      _json_tree_->addVector(_json_path_);
      retribution (_json_tree_, 0, _json_path_, args...);
    } else {
      int i = 0;
      int size = _json_tree_->getSizeAt(_json_path_);
      initialize (_json_tree_, [&] ()
        {
          int aux = i;
          if (i < size - 1)
            i++;
          return _json_path_ + "." + to_string(aux);
        },
      args...);
    }
  }

  // Write
  template <typename t>
  void static retribution (JsonTree* tree, int index, string path, t* element) {
    tree->add(*element, path);
  }

  template <class t, class... Args>
  void static retribution (JsonTree* tree, int index, string path, t element, Args... args) {
    tree->add(*element, path);
    retribution (tree, index+1, path, args...);
  }

  // Vector

  template <class t>
  void static retribution (JsonTree* tree, int index, string path, vector <t>* vect) {

    tree->addVector(path);
    path = path + "." + to_string(index);

    for (int j = 0; j < vect->size(); j++)
      retribution (tree, j, path, &(*vect)[j]);

  }

  template <class t, class... Args>
  void static retribution (JsonTree* tree, int index, string path, vector<t>* vect, Args... args) {

    tree->addVector(path);
    string newPath = path + "." + to_string(index);

    for (int j = 0; j < vect->size(); j++)
      retribution (tree, j, newPath, &(*vect)[j]);

    retribution (tree, index+1, path, args...);
  }

  // Read
  template <typename t, class func>
  void static initialize (JsonTree* tree, func functor, t* element) {
    tree->get(*element, functor());
  }

  template <class t, class func, class... Args>
  void static initialize (JsonTree* tree, func functor, t element, Args... args) {
    tree->get(*element, functor());
    initialize (tree, functor, args...);
  }

  // Vector
  template <class t, class func>
  void static initialize (JsonTree* tree, func functor, vector<vector <t> >* vect) {
    string newPath = functor();
    int size = tree->getSizeAt(newPath);
    vect->resize (size);

    int i = 0;
    for (int j = 0; j < size; j++) {
      initialize (tree, [&] () {
        return newPath + "." + to_string(i);
      }, &(*vect)[j]);
      i++;
    }
  }

  template <class t, class func, class... Args>
  void static initialize (JsonTree* tree, func functor, vector <vector <t> >* vect, Args... args) {
    string newPath = functor();

    int size = tree->getSizeAt(newPath);
    vect->resize (size);

    int i = 0;
    for (int j = 0; j < vect->size(); j++) {
      initialize (tree, [&] () {
        return newPath + "." + to_string(i);
      }, &(*vect)[j]);
      i++;
    }
    initialize (tree, functor, args...);
  }

  //Pointers
  template <class t, class func>
  typename std::enable_if<std::is_base_of<Serializable, t>::value, void>::type
  static initialize (JsonTree* tree, func functor, t** element) {
    cout << "puntero" << endl;
    *element = new t ();
    (*element)->serializeIn (*tree, functor());
  }

};

}
#endif // SERIALIZABLE_H

<|endoftext|>


<commit_before>#include "player.h"
#include "json.h"
#include <iostream>

const char* Player::VERSION = "Default C++ player";

int Player::betRequest(json::Value game_state)
{
    try {
        std::cerr<<json::Serialize(game_state)<<std::endl;
        std::string s = json::Serialize(game_state);
        std::string delimiter = "},{";
        std::string token;
        size_t pos = 0;
        while ((pos = s.find(delimiter)) != std::string::npos) {
            token = s.substr(0,pos);
            std::cerr << token << std::endl;
            s.erase(0, pos + delimiter.length());
        }

        if ( game_state.HasKey("minimum_raise") ) {
            int minimum_raise = game_state["minimum_raise"].ToInt();
            std::cerr << "Here is minimum raise" << minimum_raise << std::endl;
        }

        return 1000;
    } catch(const std::exception& e) {
        // in case it crashes
        return 1000;
    }
}

void Player::showdown(json::Value game_state)
{
}
<commit_msg>fold everytime<commit_after>#include "player.h"
#include "json.h"
#include <iostream>

const char* Player::VERSION = "Default C++ player";

int Player::betRequest(json::Value game_state)
{
    try {
        std::cerr<<json::Serialize(game_state)<<std::endl;
        std::string s = json::Serialize(game_state);
        std::string delimiter = "},{";
        std::string token;
        size_t pos = 0;
        while ((pos = s.find(delimiter)) != std::string::npos) {
            token = s.substr(0,pos);
            std::cerr << token << std::endl;
            s.erase(0, pos + delimiter.length());
        }

        if ( game_state.HasKey("minimum_raise") ) {
            int minimum_raise = game_state["minimum_raise"].ToInt();
            std::cerr << "Here is minimum raise" << minimum_raise << std::endl;
        }

        return 0;
    } catch(const std::exception& e) {
        // in case it crashes
        return 0;
    }
}

void Player::showdown(json::Value game_state)
{
}
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation                                    //
//                                                                          //
// 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 "XML.h"
#include <sstream>

namespace ospray {
  namespace xml {

    std::string toString(const float f)
    { std::stringstream ss; ss << f; return ss.str(); }

    std::string toString(const ospcommon::vec3f &v)
    { std::stringstream ss; ss << v.x << " " << v.y << " " << v.z; return ss.str(); }

    /*! checks if given node has given property */
    bool Node::hasProp(const std::string &name) const
    {
      return (properties.find(name) != properties.end());
    }

    /*! return value of property with given name if present, else return 'fallbackValue' */
    std::string Node::getProp(const std::string &name, const std::string &fallbackValue) const
    {
      if (!hasProp(name)) return fallbackValue;
      return properties.find(name)->second;
    }

    /*! return value of property with given name if present; and throw an exception if not */
    std::string Node::getProp(const std::string &name) const
    {
      if (!hasProp(name))
        throw std::runtime_error("given xml::Node does have the queried property '"+name+"'");
      return properties.find(name)->second;
    }

    inline bool isWhite(char s) {
      return
        s == ' ' ||
        s == '\t' ||
        s == '\n' ||
        s == '\r';
    }

    inline void expect(char *&s, const char w)
    {
      if (*s != w) {
        std::stringstream err;
        err << "error reading XML file: expecting '" << w << "', but found '"
            << *s << "'";
        throw std::runtime_error(err.str());
      }
    }
    inline void expect(char *&s, const char w0, const char w1)
    {
      if (*s != w0 && *s != w1) {
        std::stringstream err;
        err << "error reading XML file: expecting '" << w0 << "' or '" << w1
            << "', but found '" << *s << "'";
        throw std::runtime_error(err.str());
      }
    }
    inline void consume(char *&s, const char w)
    {
      expect(s,w);
      ++s;
    }
    inline void consume(char *&s, const char *word)
    {
      const char *in = word;
      while (*word) {
        try {
          consume(s,*word); ++word;
        } catch (...) {
          std::stringstream err;
          err << "error reading XML file: expecting '" << in
              << "', but could not find it";
          throw std::runtime_error(err.str());
        }
      }
    }

    inline std::string makeString(const char *begin, const char *end)
    {
      if (!begin || !end)
        throw std::runtime_error("invalid substring in osp::xml::makeString");
      if (begin == end) return "";
      char *mem = new char[end-begin+1];
      mem[end-begin] = 0;

      memcpy(mem,begin,end-begin);
      std::string s = mem;
      delete [] mem;
      return s;
    }

    void parseString(char *&s, std::string &value)
    {
      if (*s == '"') {
        consume(s,'"');
        char *begin = s;
        while (*s != '"') {
          if (*s == '\\') ++s;
          ++s;
        }
        char *end = s;
        value = makeString(begin,end);
        consume(s,'"');
      } else {
        consume(s,'\'');
        char *begin = s;
        while (*s != '\'') {
          if (*s == '\\') ++s;
          ++s;
        }
        char *end = s;
        value = makeString(begin,end);
        consume(s,'\'');
      }
    }

    bool parseIdentifier(char *&s, std::string &identifier)
    {
      if (isalpha(*s) || *s == '_') {
        char *begin = s;
        ++s;
        while (isalpha(*s) || isdigit(*s) || *s == '_') {
          ++s;
        }
        char *end = s;
        identifier = makeString(begin,end);
        return true;
      }
      return false;
    }

    inline void skipWhites(char *&s)
    {
      while (isWhite(*s)) ++s;
    }

    bool parseProp(char *&s, std::string &name, std::string &value)
    {
      if (!parseIdentifier(s,name))
        return false;
      skipWhites(s);
      consume(s,'=');
      skipWhites(s);
      expect(s,'"','\'');
      parseString(s,value);
      return true;
    }

    std::shared_ptr<Node> parseNode(char *&s, XMLDoc *doc)
    {
      consume(s,'<');
      std::shared_ptr<Node> node = std::make_shared<Node>(doc);

      if (!parseIdentifier(s,node->name))
        throw std::runtime_error("XML error: could not parse node name");

      skipWhites(s);

      std::string name, value;
      while (parseProp(s,name,value)) {
        node->properties[name] = value;
        skipWhites(s);
      }

      if (*s == '/') {
        consume(s,"/>");
        return node;
      }

      consume(s,">");

      while (1) {
        skipWhites(s);
        if (*s == '<' && s[1] == '/') {
          consume(s,"</");
          std::string name = "";
          parseIdentifier(s,name);
          if (name != node->name)
            throw std::runtime_error("invalid XML node - started with'<"
                                     + node->name +
                                     "...'>, but ended with '</"+name+">");
          consume(s,">");
          break;
          // either end of current node
        } else if (*s == '<') {
          // child node
          std::shared_ptr<Node> child = parseNode(s, doc);
          node->child.push_back(child);
        } else if (*s == 0) {
          std::cout << "#osp:xml: warning: xml file ended with still-open"
            " nodes (this typically indicates a partial xml file)"
                    << std::endl;
          return node;
        } else {
          if (node->content != "") {
            throw std::runtime_error("invalid XML node - two different"
                                     " contents!?");
          }
          // content
          char *begin = s;
          while (*s != '<' && *s != 0) ++s;
          char *end = s;
          while (isspace(end[-1])) --end;
          node->content = makeString(begin,end);
        }
      }
      return node;
    }

    bool parseHeader(char *&s)
    {
      consume(s,"<?xml");
      if (*s == '?' && s[1] == '>') {
        consume(s,"?>");
        return true;
      }
      if (!isWhite(*s)) return false; ++s;

      skipWhites(s);

      std::string name, value;
      while (parseProp(s,name,value)) {
        // ignore header prop
        skipWhites(s);
      }

      consume(s,"?>");
      return true;
    }

    void parseXML(std::shared_ptr<XMLDoc> doc, char *s)
    {
      if (s[0] == '<' && s[1] == '?') {
        if (!parseHeader(s))
          throw std::runtime_error("could not parse XML header");
      }
      skipWhites(s);
      while (*s != 0) {
        std::shared_ptr<Node> node = parseNode(s, doc.get());
        doc->child.push_back(node);
        skipWhites(s);
      }

      if (*s != 0)
        throw std::runtime_error("un-parsed junk at end of file");
    }

    void Writer::spaces()
    {
      for (size_t i = 0; i < state.size(); i++)
        fprintf(xml,"  ");
    }

    void Writer::writeProperty(const std::string &name,
                               const std::string &value)
    {
      assert(xml);
      assert(!state.empty());
      State *s = state.top();
      (void)s;
      assert(s);
      assert(!s->hasContent); // content may not be written before properties
      fprintf(xml," %s=\"%s\"",name.c_str(),value.c_str());
    }

    void Writer::openNode(const std::string &type)
    {
      assert(xml);
      spaces(); fprintf(xml,"<%s",type.c_str());
      State *s = new State;
      s->type = type;
      state.push(s);
    }

    void Writer::closeNode()
    {
      assert(xml);
      assert(!state.empty());
      State *s = state.top();
      assert(s);
      if (s->hasContent)
        fprintf(xml,"</%s>",s->type.c_str());
      else
        fprintf(xml,"/>\n");
      delete s;
      state.pop();
    }

    std::shared_ptr<XMLDoc> readXML(const std::string &fn)
    {
      FILE *file = fopen(fn.c_str(),"r");
      if (!file) {
        throw std::runtime_error("ospray::XML error: could not open file '"
                                 + fn +"'");
      }

      fseek(file,0,SEEK_END);
      ssize_t numBytes =
#ifdef _WIN32
        _ftelli64(file);
#else
        ftell(file);
#endif
      fseek(file,0,SEEK_SET);
      char *mem = new char[numBytes+1];
      try {
        mem[numBytes] = 0;
        auto rc = fread(mem,1,numBytes,file);
        (void)rc;
        std::shared_ptr<XMLDoc> doc = std::make_shared<XMLDoc>();
        doc->fileName = fn;
        bool valid = false;
        parseXML(doc,mem);
        delete[] mem;
        fclose(file);
        return doc;
      } catch (std::runtime_error e) {
        delete[] mem;
        fclose(file);
        throw e;
      }
    }

    Writer::Writer(FILE *xml, FILE *bin)
      : xml(xml), bin(bin)
    {}

    /*! write document header, may only be called once */
    void Writer::writeHeader(const std::string &version)
    {
      assert(xml);
      fprintf(xml,"<?xml version=\"%s\"?>\n",version.c_str());
    }

    /*! write document footer. may only be called once, at end of write */
    void Writer::writeFooter()
    {
      assert(xml);
    }

  } // ::ospray::xml
} // ::ospray
<commit_msg>added OSPRAY_XML_INTERFACE's to fix windows dll errors<commit_after>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation                                    //
//                                                                          //
// 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 "XML.h"
#include <sstream>

namespace ospray {
  namespace xml {

    std::string toString(const float f)
    { std::stringstream ss; ss << f; return ss.str(); }

    std::string toString(const ospcommon::vec3f &v)
    { std::stringstream ss; ss << v.x << " " << v.y << " " << v.z; return ss.str(); }

    /*! checks if given node has given property */
    OSPRAY_XML_INTERFACE
    bool Node::hasProp(const std::string &name) const
    {
      return (properties.find(name) != properties.end());
    }

    /*! return value of property with given name if present, else return 'fallbackValue' */
    OSPRAY_XML_INTERFACE
    std::string Node::getProp(const std::string &name, const std::string &fallbackValue) const
    {
      if (!hasProp(name)) return fallbackValue;
      return properties.find(name)->second;
    }

    /*! return value of property with given name if present; and throw an exception if not */
    OSPRAY_XML_INTERFACE
    std::string Node::getProp(const std::string &name) const
    {
      if (!hasProp(name))
        throw std::runtime_error("given xml::Node does have the queried property '"+name+"'");
      return properties.find(name)->second;
    }

    inline bool isWhite(char s) {
      return
        s == ' ' ||
        s == '\t' ||
        s == '\n' ||
        s == '\r';
    }

    inline void expect(char *&s, const char w)
    {
      if (*s != w) {
        std::stringstream err;
        err << "error reading XML file: expecting '" << w << "', but found '"
            << *s << "'";
        throw std::runtime_error(err.str());
      }
    }
    inline void expect(char *&s, const char w0, const char w1)
    {
      if (*s != w0 && *s != w1) {
        std::stringstream err;
        err << "error reading XML file: expecting '" << w0 << "' or '" << w1
            << "', but found '" << *s << "'";
        throw std::runtime_error(err.str());
      }
    }
    inline void consume(char *&s, const char w)
    {
      expect(s,w);
      ++s;
    }
    inline void consume(char *&s, const char *word)
    {
      const char *in = word;
      while (*word) {
        try {
          consume(s,*word); ++word;
        } catch (...) {
          std::stringstream err;
          err << "error reading XML file: expecting '" << in
              << "', but could not find it";
          throw std::runtime_error(err.str());
        }
      }
    }

    inline std::string makeString(const char *begin, const char *end)
    {
      if (!begin || !end)
        throw std::runtime_error("invalid substring in osp::xml::makeString");
      if (begin == end) return "";
      char *mem = new char[end-begin+1];
      mem[end-begin] = 0;

      memcpy(mem,begin,end-begin);
      std::string s = mem;
      delete [] mem;
      return s;
    }

    void parseString(char *&s, std::string &value)
    {
      if (*s == '"') {
        consume(s,'"');
        char *begin = s;
        while (*s != '"') {
          if (*s == '\\') ++s;
          ++s;
        }
        char *end = s;
        value = makeString(begin,end);
        consume(s,'"');
      } else {
        consume(s,'\'');
        char *begin = s;
        while (*s != '\'') {
          if (*s == '\\') ++s;
          ++s;
        }
        char *end = s;
        value = makeString(begin,end);
        consume(s,'\'');
      }
    }

    bool parseIdentifier(char *&s, std::string &identifier)
    {
      if (isalpha(*s) || *s == '_') {
        char *begin = s;
        ++s;
        while (isalpha(*s) || isdigit(*s) || *s == '_') {
          ++s;
        }
        char *end = s;
        identifier = makeString(begin,end);
        return true;
      }
      return false;
    }

    inline void skipWhites(char *&s)
    {
      while (isWhite(*s)) ++s;
    }

    bool parseProp(char *&s, std::string &name, std::string &value)
    {
      if (!parseIdentifier(s,name))
        return false;
      skipWhites(s);
      consume(s,'=');
      skipWhites(s);
      expect(s,'"','\'');
      parseString(s,value);
      return true;
    }

    std::shared_ptr<Node> parseNode(char *&s, XMLDoc *doc)
    {
      consume(s,'<');
      std::shared_ptr<Node> node = std::make_shared<Node>(doc);

      if (!parseIdentifier(s,node->name))
        throw std::runtime_error("XML error: could not parse node name");

      skipWhites(s);

      std::string name, value;
      while (parseProp(s,name,value)) {
        node->properties[name] = value;
        skipWhites(s);
      }

      if (*s == '/') {
        consume(s,"/>");
        return node;
      }

      consume(s,">");

      while (1) {
        skipWhites(s);
        if (*s == '<' && s[1] == '/') {
          consume(s,"</");
          std::string name = "";
          parseIdentifier(s,name);
          if (name != node->name)
            throw std::runtime_error("invalid XML node - started with'<"
                                     + node->name +
                                     "...'>, but ended with '</"+name+">");
          consume(s,">");
          break;
          // either end of current node
        } else if (*s == '<') {
          // child node
          std::shared_ptr<Node> child = parseNode(s, doc);
          node->child.push_back(child);
        } else if (*s == 0) {
          std::cout << "#osp:xml: warning: xml file ended with still-open"
            " nodes (this typically indicates a partial xml file)"
                    << std::endl;
          return node;
        } else {
          if (node->content != "") {
            throw std::runtime_error("invalid XML node - two different"
                                     " contents!?");
          }
          // content
          char *begin = s;
          while (*s != '<' && *s != 0) ++s;
          char *end = s;
          while (isspace(end[-1])) --end;
          node->content = makeString(begin,end);
        }
      }
      return node;
    }

    bool parseHeader(char *&s)
    {
      consume(s,"<?xml");
      if (*s == '?' && s[1] == '>') {
        consume(s,"?>");
        return true;
      }
      if (!isWhite(*s)) return false; ++s;

      skipWhites(s);

      std::string name, value;
      while (parseProp(s,name,value)) {
        // ignore header prop
        skipWhites(s);
      }

      consume(s,"?>");
      return true;
    }

    void parseXML(std::shared_ptr<XMLDoc> doc, char *s)
    {
      if (s[0] == '<' && s[1] == '?') {
        if (!parseHeader(s))
          throw std::runtime_error("could not parse XML header");
      }
      skipWhites(s);
      while (*s != 0) {
        std::shared_ptr<Node> node = parseNode(s, doc.get());
        doc->child.push_back(node);
        skipWhites(s);
      }

      if (*s != 0)
        throw std::runtime_error("un-parsed junk at end of file");
    }

    void Writer::spaces()
    {
      for (size_t i = 0; i < state.size(); i++)
        fprintf(xml,"  ");
    }

    void Writer::writeProperty(const std::string &name,
                               const std::string &value)
    {
      assert(xml);
      assert(!state.empty());
      State *s = state.top();
      (void)s;
      assert(s);
      assert(!s->hasContent); // content may not be written before properties
      fprintf(xml," %s=\"%s\"",name.c_str(),value.c_str());
    }

    void Writer::openNode(const std::string &type)
    {
      assert(xml);
      spaces(); fprintf(xml,"<%s",type.c_str());
      State *s = new State;
      s->type = type;
      state.push(s);
    }

    void Writer::closeNode()
    {
      assert(xml);
      assert(!state.empty());
      State *s = state.top();
      assert(s);
      if (s->hasContent)
        fprintf(xml,"</%s>",s->type.c_str());
      else
        fprintf(xml,"/>\n");
      delete s;
      state.pop();
    }

    std::shared_ptr<XMLDoc> readXML(const std::string &fn)
    {
      FILE *file = fopen(fn.c_str(),"r");
      if (!file) {
        throw std::runtime_error("ospray::XML error: could not open file '"
                                 + fn +"'");
      }

      fseek(file,0,SEEK_END);
      ssize_t numBytes =
#ifdef _WIN32
        _ftelli64(file);
#else
        ftell(file);
#endif
      fseek(file,0,SEEK_SET);
      char *mem = new char[numBytes+1];
      try {
        mem[numBytes] = 0;
        auto rc = fread(mem,1,numBytes,file);
        (void)rc;
        std::shared_ptr<XMLDoc> doc = std::make_shared<XMLDoc>();
        doc->fileName = fn;
        bool valid = false;
        parseXML(doc,mem);
        delete[] mem;
        fclose(file);
        return doc;
      } catch (std::runtime_error e) {
        delete[] mem;
        fclose(file);
        throw e;
      }
    }

    Writer::Writer(FILE *xml, FILE *bin)
      : xml(xml), bin(bin)
    {}

    /*! write document header, may only be called once */
    void Writer::writeHeader(const std::string &version)
    {
      assert(xml);
      fprintf(xml,"<?xml version=\"%s\"?>\n",version.c_str());
    }

    /*! write document footer. may only be called once, at end of write */
    void Writer::writeFooter()
    {
      assert(xml);
    }

  } // ::ospray::xml
} // ::ospray
<|endoftext|>


<commit_before>//============================================================================
// Name        : MediaEval-PlacingTask.cpp
// Author      : Andrés Pérez
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C, Ansi-style
//============================================================================

#include <bitset>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <ctime>
#include <sys/stat.h>
#include <boost/regex.hpp>

#include <opencv2/core/internal.hpp>
#include <opencv2/flann/flann.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/legacy/legacy.hpp>
#include <opencv2/nonfree/nonfree.hpp>

#include <FileUtils.hpp>
#include <FunctionUtils.hpp>
#include <VocabTree.h>

using std::vector;

double mytime;

int main(int argc, char **argv) {

	if (argc < 6 || argc > 7) {
		printf("\nUsage:\n"
				"\tVocabLearn <in.training_images.list> <in.depth>"
				" <in.branch.factor> <in.restarts>"
				" <out.tree> [in.type.binary:1]\n\n");
		return EXIT_FAILURE;
	}

	std::string list_in = argv[1];
	int depth = atoi(argv[2]);
	int branchFactor = atoi(argv[3]);
	int restarts = atoi(argv[4]);
	std::string tree_out = argv[5];
	bool isDescriptorBinary = true;

	if (argc >= 7) {
		isDescriptorBinary = atoi(argv[6]);
	}

	boost::regex expression("^(.+)(\\.)(yaml|xml)(\\.)(gz)$");

	if (boost::regex_match(tree_out, expression) == false) {
		fprintf(stderr,
				"Output tree file must have the extension .yaml.gz or .xml.gz\n");
		return EXIT_FAILURE;
	}

	// Step 1: read list of descriptors files to build the tree
	printf("-- Loading list of descriptors files\n");
	std::vector<std::string> descsFilenames;
	FileUtils::loadList(list_in, descsFilenames);
	printf("   Loaded, got [%lu] entries\n", descsFilenames.size());

	// Step 3: build tree
	printf("-- Initializing dynamic descriptors matrix\n");
	DynamicMat mergedDescriptors(descsFilenames);
	printf("   Initialized, got [%d] descriptors\n", mergedDescriptors.rows);

	// Cluster descriptors using Vocabulary Tree
	bfeat::VocabTreeParams params;
	params["branching"] = branchFactor;
	params["iterations"] = restarts;
	params["depth"] = depth;

	cv::Ptr<bfeat::VocabTreeBase> tree;

	if ((mergedDescriptors.type() == CV_8U) != isDescriptorBinary) {
		fprintf(stderr,
				"Descriptor type doesn't coincide, it is said to be [%s] while it is [%s]\n",
				isDescriptorBinary == true ? "binary" : "non-binary",
				mergedDescriptors.type() == CV_8U ? "binary" : "non-binary");
		return EXIT_FAILURE;
	}

	if (isDescriptorBinary == true) {
		tree = new bfeat::VocabTreeBin(mergedDescriptors, params);
	} else {
		tree = new bfeat::VocabTreeReal(mergedDescriptors, params);
	}

	printf(
			"-- Building vocabulary tree from [%d] feature vectors, branch factor [%d], max iterations [%d], depth [%d], centers initialization algorithm [%s]\n",
			mergedDescriptors.rows, params["branching"].cast<int>(),
			params["iterations"].cast<int>(), params["depth"].cast<int>(),
			params["centers_init"].cast<cvflann::flann_centers_init_t>()
					== cvflann::FLANN_CENTERS_RANDOM ? "random" :
			params["centers_init"].cast<cvflann::flann_centers_init_t>()
					== cvflann::FLANN_CENTERS_GONZALES ? "gonzalez" :
			params["centers_init"].cast<cvflann::flann_centers_init_t>()
					== cvflann::FLANN_CENTERS_KMEANSPP ?
					"k-means++" : "unknown");

	mytime = cv::getTickCount();
	tree->build();
	mytime = ((double) cv::getTickCount() - mytime) / cv::getTickFrequency()
			* 1000;
	printf(
			"   Vocabulary created from [%d] descriptors in [%lf] ms with [%lu] words\n",
			mergedDescriptors.rows, mytime, tree->size());

	printf("-- Saving tree to [%s]\n", tree_out.c_str());

	mytime = cv::getTickCount();
	tree->save(tree_out);
	mytime = ((double) cv::getTickCount() - mytime) / cv::getTickFrequency()
			* 1000;

	printf("   Tree saved in [%lf] ms\n", mytime);

	return EXIT_SUCCESS;
}
<commit_msg>VocabLearn/VocabLearn.cpp * Changed header of comments.<commit_after>/*
 * VocabLearn.cpp
 *
 *  Created on: Oct 6, 2013
 *      Author: andresf
 */

#include <bitset>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <ctime>
#include <sys/stat.h>
#include <boost/regex.hpp>

#include <opencv2/core/internal.hpp>
#include <opencv2/flann/flann.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/legacy/legacy.hpp>
#include <opencv2/nonfree/nonfree.hpp>

#include <FileUtils.hpp>
#include <FunctionUtils.hpp>
#include <VocabTree.h>

using std::vector;

double mytime;

int main(int argc, char **argv) {

	if (argc < 6 || argc > 7) {
		printf("\nUsage:\n"
				"\tVocabLearn <in.training_images.list> <in.depth>"
				" <in.branch.factor> <in.restarts>"
				" <out.tree> [in.type.binary:1]\n\n");
		return EXIT_FAILURE;
	}

	std::string list_in = argv[1];
	int depth = atoi(argv[2]);
	int branchFactor = atoi(argv[3]);
	int restarts = atoi(argv[4]);
	std::string tree_out = argv[5];
	bool isDescriptorBinary = true;

	if (argc >= 7) {
		isDescriptorBinary = atoi(argv[6]);
	}

	boost::regex expression("^(.+)(\\.)(yaml|xml)(\\.)(gz)$");

	if (boost::regex_match(tree_out, expression) == false) {
		fprintf(stderr,
				"Output tree file must have the extension .yaml.gz or .xml.gz\n");
		return EXIT_FAILURE;
	}

	// Step 1: read list of descriptors files to build the tree
	printf("-- Loading list of descriptors files\n");
	std::vector<std::string> descsFilenames;
	FileUtils::loadList(list_in, descsFilenames);
	printf("   Loaded, got [%lu] entries\n", descsFilenames.size());

	// Step 3: build tree
	printf("-- Initializing dynamic descriptors matrix\n");
	DynamicMat mergedDescriptors(descsFilenames);
	printf("   Initialized, got [%d] descriptors\n", mergedDescriptors.rows);

	// Cluster descriptors using Vocabulary Tree
	bfeat::VocabTreeParams params;
	params["branching"] = branchFactor;
	params["iterations"] = restarts;
	params["depth"] = depth;

	cv::Ptr<bfeat::VocabTreeBase> tree;

	if ((mergedDescriptors.type() == CV_8U) != isDescriptorBinary) {
		fprintf(stderr,
				"Descriptor type doesn't coincide, it is said to be [%s] while it is [%s]\n",
				isDescriptorBinary == true ? "binary" : "non-binary",
				mergedDescriptors.type() == CV_8U ? "binary" : "non-binary");
		return EXIT_FAILURE;
	}

	if (isDescriptorBinary == true) {
		tree = new bfeat::VocabTreeBin(mergedDescriptors, params);
	} else {
		tree = new bfeat::VocabTreeReal(mergedDescriptors, params);
	}

	printf(
			"-- Building vocabulary tree from [%d] feature vectors, branch factor [%d], max iterations [%d], depth [%d], centers initialization algorithm [%s]\n",
			mergedDescriptors.rows, params["branching"].cast<int>(),
			params["iterations"].cast<int>(), params["depth"].cast<int>(),
			params["centers_init"].cast<cvflann::flann_centers_init_t>()
					== cvflann::FLANN_CENTERS_RANDOM ? "random" :
			params["centers_init"].cast<cvflann::flann_centers_init_t>()
					== cvflann::FLANN_CENTERS_GONZALES ? "gonzalez" :
			params["centers_init"].cast<cvflann::flann_centers_init_t>()
					== cvflann::FLANN_CENTERS_KMEANSPP ?
					"k-means++" : "unknown");

	mytime = cv::getTickCount();
	tree->build();
	mytime = ((double) cv::getTickCount() - mytime) / cv::getTickFrequency()
			* 1000;
	printf(
			"   Vocabulary created from [%d] descriptors in [%lf] ms with [%lu] words\n",
			mergedDescriptors.rows, mytime, tree->size());

	printf("-- Saving tree to [%s]\n", tree_out.c_str());

	mytime = cv::getTickCount();
	tree->save(tree_out);
	mytime = ((double) cv::getTickCount() - mytime) / cv::getTickFrequency()
			* 1000;

	printf("   Tree saved in [%lf] ms\n", mytime);

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: unodoc.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-25 12:16:02 $
 *
 *  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_starmath.hxx"

// System - Includes -----------------------------------------------------

#include <tools/string.hxx>
#include <sfx2/docfac.hxx>

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#include "smdll.hxx"
#include "document.hxx"

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

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

::rtl::OUString SAL_CALL SmDocument_getImplementationName() throw()
{
    return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.Math.FormulaDocument" ) );
}

uno::Sequence< rtl::OUString > SAL_CALL SmDocument_getSupportedServiceNames() throw()
{
    uno::Sequence< rtl::OUString > aSeq( 1 );
    aSeq[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.formula.FormulaProperties" ));
    return aSeq;
}

uno::Reference< uno::XInterface > SAL_CALL SmDocument_createInstance(
                const uno::Reference< lang::XMultiServiceFactory > & /*rSMgr*/ ) throw( uno::Exception )
{
    ::vos::OGuard aGuard( Application::GetSolarMutex() );
    if ( !SM_MOD() )
        SmDLL::Init();

    SfxObjectShell* pShell = new SmDocShell( SFX_CREATE_MODE_STANDARD );
    if( pShell )
        return uno::Reference< uno::XInterface >( pShell->GetModel() );

    return uno::Reference< uno::XInterface >();
}

<commit_msg>INTEGRATION: CWS odbmacros2 (1.6.60); FILE MERGED 2007/12/22 13:39:56 fs 1.6.60.2: during #i49133#: extended the previous change (per AS' request) so the factory method does not take two booleans, but a 64 bit field instead 2007/12/12 11:22:57 fs 1.6.60.1: #i49133# allow creating documents which do not support scripting.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: unodoc.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-06 18:45:45 $
 *
 *  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_starmath.hxx"

// System - Includes -----------------------------------------------------

#include <tools/string.hxx>
#include <sfx2/docfac.hxx>
#include <sfx2/sfxmodelfactory.hxx>

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#include "smdll.hxx"
#include "document.hxx"

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

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

::rtl::OUString SAL_CALL SmDocument_getImplementationName() throw()
{
    return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.Math.FormulaDocument" ) );
}

uno::Sequence< rtl::OUString > SAL_CALL SmDocument_getSupportedServiceNames() throw()
{
    uno::Sequence< rtl::OUString > aSeq( 1 );
    aSeq[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.formula.FormulaProperties" ));
    return aSeq;
}

uno::Reference< uno::XInterface > SAL_CALL SmDocument_createInstance(
                const uno::Reference< lang::XMultiServiceFactory > & /*rSMgr*/, const sal_uInt64 _nCreationFlags ) throw( uno::Exception )
{
    ::vos::OGuard aGuard( Application::GetSolarMutex() );
    if ( !SM_MOD() )
        SmDLL::Init();

    const SfxObjectCreateMode eCreateMode = ( _nCreationFlags & SFXMODEL_EMBEDDED_OBJECT ) ? SFX_CREATE_MODE_EMBEDDED : SFX_CREATE_MODE_STANDARD;
    const bool bScriptSupport = ( _nCreationFlags & SFXMODEL_DISABLE_EMBEDDED_SCRIPTS ) == 0;

    SfxObjectShell* pShell = new SmDocShell( eCreateMode, bScriptSupport );
    if( pShell )
        return uno::Reference< uno::XInterface >( pShell->GetModel() );

    return uno::Reference< uno::XInterface >();
}

<|endoftext|>


<commit_before>#ifndef _SNARKFRONT_SHA_512_256_HPP_
#define _SNARKFRONT_SHA_512_256_HPP_

#include <array>
#include <cstdint>
#include "Alg.hpp"
#include "Alg_uint.hpp"
#include "AST.hpp"
#include "BitwiseOps.hpp"
#include "Lazy.hpp"
#include "SHA_512.hpp"

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// SHA-512/256
//

template <typename H, typename T, typename MSG, typename U, typename F, typename X>
class SHA_512_256 : public SHA_512<T, MSG, U, F>
{
public:
    typedef T WordType;
    typedef U ByteType;

    typedef std::array<T, 16> MsgType;
    typedef std::array<H, 8> DigType;
    typedef std::array<U, 16 * 8> PreType;

    SHA_512_256()
        : m_setDigest(false)
    {}

    // overrides base class SHA-512
    const std::array<H, 8>& digest() {
        if (m_setDigest) {
            for (std::size_t i = 0; i < 4; ++i) {
                // high 32 bits
                m_Hleft256[2*i] = F::xword(F::SHR(
                                               this->m_H[i],
                                               32),
                                           X());

                // low 32 bits
                m_Hleft256[2*i + 1] = F::xword(F::SHR(
                                                   F::SHL(
                                                       this->m_H[i],
                                                       32),
                                                   32),
                                               X());
            }

            m_setDigest = false;
        }

        return m_Hleft256;
    }

    virtual void afterHash() {
        m_setDigest = true;
    }

protected:
    // overrides base class SHA-512
    void initHashValue() {
        // set initial hash value (NIST FIPS 180-4 section 5.3.6.2)
        const std::array<std::uint64_t, 8> a {
            0x22312194FC2BF72C, 0x9F555FA3C84C64C2,
            0x2393B86B6F53B151, 0x963877195940EABD,

            0x96283EE2A88EFFE3, 0xBE5E1E2553863992,
            0x2B0199FC2C85B8AA, 0x0EB72DDC81C52CA2 };

        for (std::size_t i = 0; i < 8; ++i) {
            this->m_H[i] = F::constant(a[i]);
        }
    }

    // truncated 256-bit message digest
    std::array<H, 8> m_Hleft256;

    bool m_setDigest;
};

////////////////////////////////////////////////////////////////////////////////
// typedefs
//

namespace zk {
    template <typename FR> using
    SHA512_256 = SHA_512_256<AST_Var<Alg_uint32<FR>>,
                             AST_Var<Alg_uint64<FR>>,
                             Lazy<AST_Var<Alg_uint64<FR>>, std::uint64_t>,
                             AST_Var<Alg_uint8<FR>>,
                             SHA_Functions<AST_Node<Alg_uint64<FR>>,
                                           AST_Op<Alg_uint64<FR>>,
                                           BitwiseAST<Alg_uint64<FR>>>,
                             Alg_uint32<FR>>;
} // namespace zk

namespace eval {
    typedef SHA_512_256<std::uint32_t,
                        std::uint64_t,
                        std::uint64_t,
                        std::uint8_t,
                        SHA_Functions<std::uint64_t,
                                      std::uint64_t,
                                      BitwiseINT<std::uint64_t>>,
                        std::uint32_t>
        SHA512_256;
} // namespace eval

} // namespace snarkfront

#endif
<commit_msg>refactor BitwiseOps.hpp<commit_after>#ifndef _SNARKFRONT_SHA_512_256_HPP_
#define _SNARKFRONT_SHA_512_256_HPP_

#include <array>
#include <cstdint>
#include "Alg.hpp"
#include "Alg_uint.hpp"
#include "AST.hpp"
#include "BitwiseAST.hpp"
#include "BitwiseINT.hpp"
#include "Lazy.hpp"
#include "SHA_512.hpp"

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// SHA-512/256
//

template <typename H, typename T, typename MSG, typename U, typename F, typename X>
class SHA_512_256 : public SHA_512<T, MSG, U, F>
{
public:
    typedef T WordType;
    typedef U ByteType;

    typedef std::array<T, 16> MsgType;
    typedef std::array<H, 8> DigType;
    typedef std::array<U, 16 * 8> PreType;

    SHA_512_256()
        : m_setDigest(false)
    {}

    // overrides base class SHA-512
    const std::array<H, 8>& digest() {
        if (m_setDigest) {
            for (std::size_t i = 0; i < 4; ++i) {
                // high 32 bits
                m_Hleft256[2*i] = F::xword(F::SHR(
                                               this->m_H[i],
                                               32),
                                           X());

                // low 32 bits
                m_Hleft256[2*i + 1] = F::xword(F::SHR(
                                                   F::SHL(
                                                       this->m_H[i],
                                                       32),
                                                   32),
                                               X());
            }

            m_setDigest = false;
        }

        return m_Hleft256;
    }

    virtual void afterHash() {
        m_setDigest = true;
    }

protected:
    // overrides base class SHA-512
    void initHashValue() {
        // set initial hash value (NIST FIPS 180-4 section 5.3.6.2)
        const std::array<std::uint64_t, 8> a {
            0x22312194FC2BF72C, 0x9F555FA3C84C64C2,
            0x2393B86B6F53B151, 0x963877195940EABD,

            0x96283EE2A88EFFE3, 0xBE5E1E2553863992,
            0x2B0199FC2C85B8AA, 0x0EB72DDC81C52CA2 };

        for (std::size_t i = 0; i < 8; ++i) {
            this->m_H[i] = F::constant(a[i]);
        }
    }

    // truncated 256-bit message digest
    std::array<H, 8> m_Hleft256;

    bool m_setDigest;
};

////////////////////////////////////////////////////////////////////////////////
// typedefs
//

namespace zk {
    template <typename FR> using
    SHA512_256 = SHA_512_256<AST_Var<Alg_uint32<FR>>,
                             AST_Var<Alg_uint64<FR>>,
                             Lazy<AST_Var<Alg_uint64<FR>>, std::uint64_t>,
                             AST_Var<Alg_uint8<FR>>,
                             SHA_Functions<AST_Node<Alg_uint64<FR>>,
                                           AST_Op<Alg_uint64<FR>>,
                                           BitwiseAST<Alg_uint64<FR>>>,
                             Alg_uint32<FR>>;
} // namespace zk

namespace eval {
    typedef SHA_512_256<std::uint32_t,
                        std::uint64_t,
                        std::uint64_t,
                        std::uint8_t,
                        SHA_Functions<std::uint64_t,
                                      std::uint64_t,
                                      BitwiseINT<std::uint64_t>>,
                        std::uint32_t>
        SHA512_256;
} // namespace eval

} // namespace snarkfront

#endif
<|endoftext|>


<commit_before>/*************************************
** Tsunagari Tile Engine            **
** measure.cpp                      **
** Copyright 2016-2019 Paul Merrill **
*************************************/

// **********
// 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 "core/measure.h"

#include "core/log.h"

#if defined(__APPLE__) && defined(MAKE_MACOS_SIGNPOSTS)
#include "util/hashtable.h"

// sys/kdebug_signpost.h
extern "C" {
int kdebug_signpost_start(uint32_t,
                          uintptr_t,
                          uintptr_t,
                          uintptr_t,
                          uintptr_t) noexcept;
int kdebug_signpost_end(uint32_t,
                        uintptr_t,
                        uintptr_t,
                        uintptr_t,
                        uintptr_t) noexcept;
}

static uint32_t nextSignpost = 0;
static Hashmap<String, uint32_t> signposts;

static uint32_t
getSignpost(String description) noexcept {
    if (signposts.find(description) != signposts.end()) {
        return signposts[description];
    }
    else {
        Log::info("Measure",
                  String() << description << " is signpost " << nextSignpost);
        signposts[move_(description)] = nextSignpost;
        return nextSignpost++;
    }
}
#endif  // defined(__APPLE__) && defined(MAKE_MACOS_SIGNPOSTS)

TimeMeasure::TimeMeasure(String description) noexcept {
    this->description = move_(description);
    start = SteadyClock::now();
#if defined(__APPLE__) && defined(MAKE_MACOS_SIGNPOSTS)
    signpost = getSignpost(description);
    kdebug_signpost_start(signpost, 0, 0, 0, 0);
#endif
}

TimeMeasure::~TimeMeasure() noexcept {
#if defined(__APPLE__) && defined(MAKE_MACOS_SIGNPOSTS)
    kdebug_signpost_end(signpost, 0, 0, 0, 0);
#endif

    TimePoint end = SteadyClock::now();

    Duration elapsed = end - start;
    Log::info("Measure",
              String() << description << " took " << ns_to_s_d(elapsed)
                       << " seconds");
}
<commit_msg>core/measure: Fix bug in macOS signpost IDs<commit_after>/*************************************
** Tsunagari Tile Engine            **
** measure.cpp                      **
** Copyright 2016-2019 Paul Merrill **
*************************************/

// **********
// 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 "core/measure.h"

#include "core/log.h"

#if defined(__APPLE__) && defined(MAKE_MACOS_SIGNPOSTS)
#include "util/hashtable.h"

// sys/kdebug_signpost.h
extern "C" {
int kdebug_signpost_start(uint32_t,
                          uintptr_t,
                          uintptr_t,
                          uintptr_t,
                          uintptr_t) noexcept;
int kdebug_signpost_end(uint32_t,
                        uintptr_t,
                        uintptr_t,
                        uintptr_t,
                        uintptr_t) noexcept;
}

static uint32_t nextSignpost = 0;
static Hashmap<String, uint32_t> signposts;

static uint32_t
getSignpost(String description) noexcept {
    if (signposts.find(description) != signposts.end()) {
        return signposts[description];
    }
    else {
        Log::info("Measure",
                  String() << description << " is signpost " << nextSignpost);
        signposts[move_(description)] = nextSignpost;
        return nextSignpost++;
    }
}
#endif  // defined(__APPLE__) && defined(MAKE_MACOS_SIGNPOSTS)

TimeMeasure::TimeMeasure(String description) noexcept {
    this->description = move_(description);
    start = SteadyClock::now();
#if defined(__APPLE__) && defined(MAKE_MACOS_SIGNPOSTS)
    signpost = getSignpost(this->description);
    kdebug_signpost_start(signpost, 0, 0, 0, 0);
#endif
}

TimeMeasure::~TimeMeasure() noexcept {
#if defined(__APPLE__) && defined(MAKE_MACOS_SIGNPOSTS)
    kdebug_signpost_end(signpost, 0, 0, 0, 0);
#endif

    TimePoint end = SteadyClock::now();

    Duration elapsed = end - start;
    Log::info("Measure",
              String() << description << " took " << ns_to_s_d(elapsed)
                       << " seconds");
}
<|endoftext|>


<commit_before>#include <Python.h>
#include "PyContext.h"
#include "QpyTestObject.h"

static PyMethodDef empty_module_methods[] = {
    {NULL}  /* Sentinel */
};
int main( int argc, char** argv ) {

    if( argc != 2 ) {
        std::cout << "Usage: " << argv[ 0 ] << " <python file>" << std::endl;
        exit( 1 );
    }

    Py_Initialize();
    qpy::PyContext py;
    PyObject* m = Py_InitModule3( "qpy", py.ModuleFunctions(), "Example QPy module" );
    PyObject* mainModule = PyImport_AddModule( "__main__" );
    PyModule_AddObject( mainModule, "qpy", m );
    py.Add< QpyTestObject >( m );

    QpyTestObject* to = new QpyTestObject( 71 );
    py.AddObject( to, mainModule, m, "myqobj" );

    PyRun_SimpleFile( fopen( argv[ 1 ], "r" ), argv[ 1 ] );
    Py_Finalize();
    return 0;
}
<commit_msg>Fixes #16 - segfault on Mac<commit_after>#include <Python.h>
#include "PyContext.h"
#include "QpyTestObject.h"

static PyMethodDef empty_module_methods[] = {
    {NULL}  /* Sentinel */
};
int main( int argc, char** argv ) {

    if( argc != 2 ) {
        std::cout << "Usage: " << argv[ 0 ] << " <python file>" << std::endl;
        exit( 1 );
    }

    Py_Initialize();
    qpy::PyContext py;
    PyObject* m = Py_InitModule3( "qpy", py.ModuleFunctions(), "Example QPy module" );
    Py_INCREF( m );
    PyObject* mainModule = PyImport_AddModule( "__main__" );
    PyModule_AddObject( mainModule, "qpy", m );
    py.Add< QpyTestObject >( m );

    QpyTestObject* to = new QpyTestObject( 71 );
    py.AddObject( to, mainModule, m, "myqobj" );

    PyRun_SimpleFile( fopen( argv[ 1 ], "r" ), argv[ 1 ] );
    Py_Finalize();
    return 0;
}
<|endoftext|>


<commit_before>#include "sparseint.h"

namespace base {

int SparseInt::buf_size(char byte1) {
    if ((byte1 & 0x80) == 0) {
        // binary: 0...
        return 1;
    } else if ((byte1 & 0xC0) == 0x80) {
        // binary: 10...
        return 2;
    } else if ((byte1 & 0xE0) == 0xC0) {
        // binary: 110...
        return 3;
    } else if ((byte1 & 0xF0) == 0xE0) {
        // binary: 1110...
        return 4;
    } else if ((byte1 & 0xF8) == 0xF0) {
        // binary: 11110...
        return 5;
    } else if ((byte1 & 0xFC) == 0xF8) {
        // binary: 111110...
        return 6;
    } else if ((byte1 & 0xFE) == 0xFC) {
        // binary: 1111110...
        return 7;
    } else if ((byte1 & 0xFF) == 0xFE) {
        // binary: 11111110...
        return 8;
    } else {
        return 9;
    }
}

int SparseInt::dump(i32 val, char* buf) {
    char* pv = (char *) &val;
    if (-64 <= val && val <= 63) {
        buf[0] = pv[0];
        buf[0] &= 0x7F;
        return 1;
    } else if (-8192 <= val && val <= 8191) {
        buf[0] = pv[1];
        buf[1] = pv[0];
        buf[0] &= 0x3F;
        buf[0] |= 0x80;
        return 2;
    } else if (-1048576 <= val && val <= 1048575) {
        buf[0] = pv[2];
        buf[1] = pv[1];
        buf[2] = pv[0];
        buf[0] &= 0x1F;
        buf[0] |= 0xC0;
        return 3;
    } else if (-134217728 <= val && val <= 134217727) {
        buf[0] = pv[3];
        buf[1] = pv[2];
        buf[2] = pv[1];
        buf[3] = pv[0];
        buf[0] &= 0x0F;
        buf[0] |= 0xE0;
        return 4;
    } else {
        buf[1] = pv[3];
        buf[2] = pv[2];
        buf[3] = pv[1];
        buf[4] = pv[0];
        if (val < 0) {
            buf[0] = 0xF7;
        } else {
            buf[0] = 0xF0;
        }
        return 5;
    }
}

int SparseInt::dump(i64 val, char* buf) {
    char* pv = (char *) &val;
    if (-64 <= val && val <= 63) {
        buf[0] = pv[0];
        buf[0] &= 0x7F;
        return 1;
    } else if (-8192 <= val && val <= 8191) {
        buf[0] = pv[1];
        buf[1] = pv[0];
        buf[0] &= 0x3F;
        buf[0] |= 0x80;
        return 2;
    } else if (-1048576 <= val && val <= 1048575) {
        buf[0] = pv[2];
        buf[1] = pv[1];
        buf[2] = pv[0];
        buf[0] &= 0x1F;
        buf[0] |= 0xC0;
        return 3;
    } else if (-134217728 <= val && val <= 134217727) {
        buf[0] = pv[3];
        buf[1] = pv[2];
        buf[2] = pv[1];
        buf[3] = pv[0];
        buf[0] &= 0x0F;
        buf[0] |= 0xE0;
        return 4;
    } else if (-17179869184LL <= val && val <= 17179869183LL) {
        buf[0] = pv[4];
        buf[1] = pv[3];
        buf[2] = pv[2];
        buf[3] = pv[1];
        buf[4] = pv[0];
        buf[0] &= 0x07;
        buf[0] |= 0xF0;
        return 5;
    } else if (-2199023255552LL <= val && val <= 2199023255551LL) {
        buf[0] = pv[5];
        buf[1] = pv[4];
        buf[2] = pv[3];
        buf[3] = pv[2];
        buf[4] = pv[1];
        buf[5] = pv[0];
        buf[0] &= 0x03;
        buf[0] |= 0xF8;
        return 6;
    } else if (-281474976710656LL <= val && val <= 281474976710655LL) {
        buf[0] = pv[6];
        buf[1] = pv[5];
        buf[2] = pv[4];
        buf[3] = pv[3];
        buf[4] = pv[2];
        buf[5] = pv[1];
        buf[6] = pv[0];
        buf[0] &= 0x01;
        buf[0] |= 0xFC;
        return 7;
    } else if (-36028797018963968LL <= val && val <= 36028797018963967LL) {
        buf[1] = pv[7];
        buf[2] = pv[6];
        buf[3] = pv[5];
        buf[4] = pv[4];
        buf[5] = pv[3];
        buf[6] = pv[2];
        buf[7] = pv[1];
        buf[8] = pv[0];
        buf[0] = 0xFE;
        return 8;
    } else {
        buf[1] = pv[7];
        buf[2] = pv[6];
        buf[3] = pv[5];
        buf[4] = pv[4];
        buf[5] = pv[3];
        buf[6] = pv[2];
        buf[7] = pv[1];
        buf[8] = pv[0];
        buf[0] = 0xFE;
        buf[0] = 0xFF;
        return 9;
    }
}

i32 SparseInt::load_i32(const char* buf) {
    i32 val = 0;
    char* pv = (char *) &val;
    int bsize = SparseInt::buf_size(buf[0]);
    if (bsize < 5) {
        for (int i = 0; i < bsize; i++) {
            pv[i] = buf[bsize - i - 1];
        }
        pv[bsize - 1] &= 0xFF >> bsize;
        if ((pv[bsize - 1] >> (7 - bsize)) & 0x1) {
            pv[bsize - 1] |= 0xFF << (7 - bsize);
            for (int i = bsize; i < 4; i++) {
                pv[i] = 0xFF;
            }
        }
    } else {
        for (int i = 0; i < 4; i++) {
            pv[i] = buf[4 - i];
        }
    }
    return val;
}

i64 SparseInt::load_i64(const char* buf) {
    i64 val = 0;
    char* pv = (char *) &val;
    int bsize = SparseInt::buf_size(buf[0]);
    if (bsize < 8) {
        for (int i = 0; i < bsize; i++) {
            pv[i] = buf[bsize - i - 1];
        }
        pv[bsize - 1] &= 0xFF >> bsize;
        if ((pv[bsize - 1] >> (7 - bsize)) & 0x1) {
            pv[bsize - 1] |= 0xFF << (7 - bsize);
            for (int i = bsize; i < 8; i++) {
                pv[i] = 0xFF;
            }
        }
    } else {
        for (int i = 0; i < 8; i++) {
            pv[i] = buf[8 - i];
        }
    }
    return val;
}

} // namespace base
<commit_msg>minor fix<commit_after>#include "sparseint.h"

namespace base {

int SparseInt::buf_size(char byte1) {
    if ((byte1 & 0x80) == 0) {
        // binary: 0...
        return 1;
    } else if ((byte1 & 0xC0) == 0x80) {
        // binary: 10...
        return 2;
    } else if ((byte1 & 0xE0) == 0xC0) {
        // binary: 110...
        return 3;
    } else if ((byte1 & 0xF0) == 0xE0) {
        // binary: 1110...
        return 4;
    } else if ((byte1 & 0xF8) == 0xF0) {
        // binary: 11110...
        return 5;
    } else if ((byte1 & 0xFC) == 0xF8) {
        // binary: 111110...
        return 6;
    } else if ((byte1 & 0xFE) == 0xFC) {
        // binary: 1111110...
        return 7;
    } else if ((byte1 & 0xFF) == 0xFE) {
        // binary: 11111110...
        return 8;
    } else {
        return 9;
    }
}

int SparseInt::dump(i32 val, char* buf) {
    char* pv = (char *) &val;
    if (-64 <= val && val <= 63) {
        buf[0] = pv[0];
        buf[0] &= 0x7F;
        return 1;
    } else if (-8192 <= val && val <= 8191) {
        buf[0] = pv[1];
        buf[1] = pv[0];
        buf[0] &= 0x3F;
        buf[0] |= 0x80;
        return 2;
    } else if (-1048576 <= val && val <= 1048575) {
        buf[0] = pv[2];
        buf[1] = pv[1];
        buf[2] = pv[0];
        buf[0] &= 0x1F;
        buf[0] |= 0xC0;
        return 3;
    } else if (-134217728 <= val && val <= 134217727) {
        buf[0] = pv[3];
        buf[1] = pv[2];
        buf[2] = pv[1];
        buf[3] = pv[0];
        buf[0] &= 0x0F;
        buf[0] |= 0xE0;
        return 4;
    } else {
        buf[1] = pv[3];
        buf[2] = pv[2];
        buf[3] = pv[1];
        buf[4] = pv[0];
        if (val < 0) {
            buf[0] = 0xF7;
        } else {
            buf[0] = 0xF0;
        }
        return 5;
    }
}

int SparseInt::dump(i64 val, char* buf) {
    char* pv = (char *) &val;
    if (-64 <= val && val <= 63) {
        buf[0] = pv[0];
        buf[0] &= 0x7F;
        return 1;
    } else if (-8192 <= val && val <= 8191) {
        buf[0] = pv[1];
        buf[1] = pv[0];
        buf[0] &= 0x3F;
        buf[0] |= 0x80;
        return 2;
    } else if (-1048576 <= val && val <= 1048575) {
        buf[0] = pv[2];
        buf[1] = pv[1];
        buf[2] = pv[0];
        buf[0] &= 0x1F;
        buf[0] |= 0xC0;
        return 3;
    } else if (-134217728 <= val && val <= 134217727) {
        buf[0] = pv[3];
        buf[1] = pv[2];
        buf[2] = pv[1];
        buf[3] = pv[0];
        buf[0] &= 0x0F;
        buf[0] |= 0xE0;
        return 4;
    } else if (-17179869184LL <= val && val <= 17179869183LL) {
        buf[0] = pv[4];
        buf[1] = pv[3];
        buf[2] = pv[2];
        buf[3] = pv[1];
        buf[4] = pv[0];
        buf[0] &= 0x07;
        buf[0] |= 0xF0;
        return 5;
    } else if (-2199023255552LL <= val && val <= 2199023255551LL) {
        buf[0] = pv[5];
        buf[1] = pv[4];
        buf[2] = pv[3];
        buf[3] = pv[2];
        buf[4] = pv[1];
        buf[5] = pv[0];
        buf[0] &= 0x03;
        buf[0] |= 0xF8;
        return 6;
    } else if (-281474976710656LL <= val && val <= 281474976710655LL) {
        buf[0] = pv[6];
        buf[1] = pv[5];
        buf[2] = pv[4];
        buf[3] = pv[3];
        buf[4] = pv[2];
        buf[5] = pv[1];
        buf[6] = pv[0];
        buf[0] &= 0x01;
        buf[0] |= 0xFC;
        return 7;
    } else if (-36028797018963968LL <= val && val <= 36028797018963967LL) {
        buf[1] = pv[7];
        buf[2] = pv[6];
        buf[3] = pv[5];
        buf[4] = pv[4];
        buf[5] = pv[3];
        buf[6] = pv[2];
        buf[7] = pv[1];
        buf[8] = pv[0];
        buf[0] = 0xFE;
        return 8;
    } else {
        buf[1] = pv[7];
        buf[2] = pv[6];
        buf[3] = pv[5];
        buf[4] = pv[4];
        buf[5] = pv[3];
        buf[6] = pv[2];
        buf[7] = pv[1];
        buf[8] = pv[0];
        buf[0] = 0xFF;
        return 9;
    }
}

i32 SparseInt::load_i32(const char* buf) {
    i32 val = 0;
    char* pv = (char *) &val;
    int bsize = SparseInt::buf_size(buf[0]);
    if (bsize < 5) {
        for (int i = 0; i < bsize; i++) {
            pv[i] = buf[bsize - i - 1];
        }
        pv[bsize - 1] &= 0xFF >> bsize;
        if ((pv[bsize - 1] >> (7 - bsize)) & 0x1) {
            pv[bsize - 1] |= 0xFF << (7 - bsize);
            for (int i = bsize; i < 4; i++) {
                pv[i] = 0xFF;
            }
        }
    } else {
        for (int i = 0; i < 4; i++) {
            pv[i] = buf[4 - i];
        }
    }
    return val;
}

i64 SparseInt::load_i64(const char* buf) {
    i64 val = 0;
    char* pv = (char *) &val;
    int bsize = SparseInt::buf_size(buf[0]);
    if (bsize < 8) {
        for (int i = 0; i < bsize; i++) {
            pv[i] = buf[bsize - i - 1];
        }
        pv[bsize - 1] &= 0xFF >> bsize;
        if ((pv[bsize - 1] >> (7 - bsize)) & 0x1) {
            pv[bsize - 1] |= 0xFF << (7 - bsize);
            for (int i = bsize; i < 8; i++) {
                pv[i] = 0xFF;
            }
        }
    } else {
        for (int i = 0; i < 8; i++) {
            pv[i] = buf[8 - i];
        }
    }
    return val;
}

} // namespace base
<|endoftext|>


<commit_before>#include "player.hpp"
/* Modification by Josh */
/*
 * Constructor for the player; initialize everything here. The side your AI is
 * on (BLACK or WHITE) is passed in as "side". The constructor must finish
 * within 30 seconds.
 */
Player::Player(Side side) {
    // Will be set to true in test_minimax.cpp.
    testingMinimax = false;

    /*
     * TODO: Do any initialization you need to do here (setting up the board,
     * precalculating things, etc.) However, remember that you will only have
     * 30 seconds.
     */
}

/*
 * Destructor for the player.
 */
Player::~Player() {
}

/*
 * Compute the next move given the opponent's last move. Your AI is
 * expected to keep track of the board on its own. If this is the first move,
 * or if the opponent passed on the last move, then opponentsMove will be
 * nullptr.
 *
 * msLeft represents the time your AI has left for the total game, in
 * milliseconds. doMove() must take no longer than msLeft, or your AI will
 * be disqualified! An msLeft value of -1 indicates no time limit.
 *
 * The move returned must be legal; if there are no valid moves for your side,
 * return nullptr.
 */
Move *Player::doMove(Move *opponentsMove, int msLeft) {
    /*
     * TODO: Implement how moves your AI should play here. You should first
     * process the opponent's opponents move before calculating your own move
     */
    return nullptr;
}
<commit_msg>I said hi josh<commit_after>#include "player.hpp"
/* Modification by Josh */
/*
 * Constructor for the player; initialize everything here. The side your AI is
 * on (BLACK or WHITE) is passed in as "side". The constructor must finish
 * within 30 seconds.
 */
Player::Player(Side side) {
    // Will be set to true in test_minimax.cpp.
    testingMinimax = false;

    /*
     * TODO: Do any initialization you need to do here (setting up the board,
     * precalculating things, etc.) However, remember that you will only have
     * 30 seconds.
     */
    hijosh = true;
}

/*
 * Destructor for the player.
 */
Player::~Player() {
}

/*
 * Compute the next move given the opponent's last move. Your AI is
 * expected to keep track of the board on its own. If this is the first move,
 * or if the opponent passed on the last move, then opponentsMove will be
 * nullptr.
 *
 * msLeft represents the time your AI has left for the total game, in
 * milliseconds. doMove() must take no longer than msLeft, or your AI will
 * be disqualified! An msLeft value of -1 indicates no time limit.
 *
 * The move returned must be legal; if there are no valid moves for your side,
 * return nullptr.
 */
Move *Player::doMove(Move *opponentsMove, int msLeft) {
    /*
     * TODO: Implement how moves your AI should play here. You should first
     * process the opponent's opponents move before calculating your own move
     */
    return nullptr;
}
<|endoftext|>