text:
// Copyright 2009-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0

#include "xml_writer.h"

namespace embree
{
  class XMLWriter
  {
  public:

    XMLWriter(Ref<SceneGraph::Node> root, const FileName& fileName, bool embedTextures, bool referenceMaterials, bool binaryFormat);

  public:
    void tab();
    void open(std::string str);
    void open(std::string str, size_t id);
    void close(std::string str);

    void store(const char* name, const char* str);
    void store(const char* name, const float& v);
    void store(const char* name, const Vec3fa& v);

    void store_array_elt(const int& v);
    void store_array_elt(const Vec2f& v);
    void store_array_elt(const Vec3f& v);
    void store_array_elt(const Vec3fa& v);
    void store_array_elt(const Vec3ff& v);
    void store_array_elt(const SceneGraph::TriangleMeshNode::Triangle& v);
    void store_array_elt(const SceneGraph::QuadMeshNode::Quad& v);

    template<typename T> void store_array_text  (const char* name, const std::vector<T>& vec);
    template<typename T> void store_array_binary(const char* name, const std::vector<T>& vec);
    template<typename T> void store             (const char* name, const std::vector<T>& vec);

    void store_array_text  (const char* name, const avector<Vec3fa>& vec);
    void store_array_binary(const char* name, const avector<Vec3fa>& vec);
    void store             (const char* name, const avector<Vec3fa>& vec);

    void store_array_text  (const char* name, const avector<Vec3ff>& vec);
    void store_array_binary(const char* name, const avector<Vec3ff>& vec);
    void store             (const char* name, const avector<Vec3ff>& vec);

    void store_parm(const char* name, const float& v);
    void store_parm(const char* name, const Vec3fa& v);
    void store_parm(const char* name, const std::shared_ptr<Texture> tex);
    void store(const char* name, const AffineSpace3fa& space);

    void store(const SceneGraph::PointLight& light, ssize_t id);
    void store(const SceneGraph::SpotLight& light, ssize_t id);
    void store(const SceneGraph::DirectionalLight& light, ssize_t id);
    void store(const SceneGraph::DistantLight& light, ssize_t id);
    void store(const SceneGraph::AmbientLight& light, ssize_t id);
    void store(const SceneGraph::TriangleLight& light, ssize_t id);
    void store(const SceneGraph::QuadLight& light, ssize_t id);
    void store(Ref<SceneGraph::LightNode> light, ssize_t id);
    void store(Ref<SceneGraph::AnimatedLightNode> light, ssize_t id);

    void store(Ref<MatteMaterial> material, ssize_t id);
    void store(Ref<MirrorMaterial> material, ssize_t id);
    void store(Ref<ThinDielectricMaterial> material, ssize_t id);
    void store(Ref<OBJMaterial> material, ssize_t id);
    void store(Ref<MetalMaterial> material, ssize_t id);
    void store(Ref<VelvetMaterial> material, ssize_t id);
    void store(Ref<DielectricMaterial> material, ssize_t id);
    void store(Ref<MetallicPaintMaterial> material, ssize_t id);
    void store(Ref<HairMaterial> material, ssize_t id);
    void store(Ref<SceneGraph::MaterialNode> material);

    void store(Ref<SceneGraph::TriangleMeshNode> mesh, ssize_t id);
    void store(Ref<SceneGraph::QuadMeshNode> mesh, ssize_t id);
    void store(Ref<SceneGraph::SubdivMeshNode> mesh, ssize_t id);
    void store(Ref<SceneGraph::HairSetNode> hair, ssize_t id);

    void store(Ref<SceneGraph::PerspectiveCameraNode> camera, ssize_t id);
    void store(Ref<SceneGraph::AnimatedPerspectiveCameraNode> camera, ssize_t id);
    void store(Ref<SceneGraph::TransformNode> node, ssize_t id);
    void store(std::vector<Ref<SceneGraph::TransformNode>> nodes);
    void store(Ref<SceneGraph::GroupNode> group, ssize_t id);
    void store(Ref<SceneGraph::Node> node);

  private:
    std::fstream xml;         //!< .xml file for writing XML data
    std::fstream bin;         //!< .bin file for writing binary data

  private:
    size_t ident;
    size_t currentNodeID;
    std::map<Ref<SceneGraph::Node>, size_t> nodeMap;
    std::map<std::shared_ptr<Texture>, size_t> textureMap; // FIXME: use Ref<Texture>
    bool embedTextures;
    bool referenceMaterials;
    bool binaryFormat;
  };

  //////////////////////////////////////////////////////////////////////////////
  //// Storing of objects to XML file
  //////////////////////////////////////////////////////////////////////////////

  void XMLWriter::tab()
  {
    for (size_t i=0; i<ident; i++)
      xml << " ";
  }

  void XMLWriter::open(std::string str)
  {
    tab(); xml << "<" << str << ">" << std::endl;
    ident+=2;
  }

  void XMLWriter::open(std::string str, size_t id)
  {
    tab(); xml << "<" << str << " id=\"" << id << "\">" << std::endl;
    ident+=2;
  }

  void XMLWriter::close(std::string str)
  {
    assert(ident>=2);
    ident-=2;
    tab(); xml << "</" << str << ">" << std::endl;
  }

  void XMLWriter::store(const char* name, const char* str) {
    tab(); xml << "<" << name << ">\"" << str << "\"</" << name << ">" << std::endl;
  }

  void XMLWriter::store(const char* name, const float& v) {
    tab(); xml << "<" << name << ">" << v << "</" << name << ">" << std::endl;
  }

  void XMLWriter::store(const char* name, const Vec3fa& v) {
    tab(); xml << "<" << name << ">" << v.x << " " << v.y << " " << v.z << "</" << name << ">" << std::endl;
  }

  void XMLWriter::store_array_elt(const int& v) {
    xml << v << std::endl;
  }

  void XMLWriter::store_array_elt(const Vec2f& v) {
    xml << v.x << " " << v.y << std::endl;
  }

  void XMLWriter::store_array_elt(const Vec3f& v) {
    xml << v.x << " " << v.y << " " << v.z << std::endl;
  }

  void XMLWriter::store_array_elt(const Vec3fa& v) {
    xml << v.x << " " << v.y << " " << v.z << std::endl;
  }

  void XMLWriter::store_array_elt(const Vec3ff& v) {
    xml << v.x << " " << v.y << " " << v.z << " " << v.w << std::endl;
  }

  void XMLWriter::store_array_elt(const SceneGraph::TriangleMeshNode::Triangle& v) {
    xml << v.v0 << " " << v.v1 << " " << v.v2 << std::endl;
  }

  void XMLWriter::store_array_elt(const SceneGraph::QuadMeshNode::Quad& v) {
    xml << v.v0 << " " << v.v1 << " " << v.v2 << " "  << v.v3 << std::endl;
  }

  template<typename T>
  void XMLWriter::store_array_text(const char* name, const std::vector<T>& vec)
  {
    open(name);
    for (size_t i=0; i<vec.size(); i++) {
      tab(); store_array_elt(vec[i]);
    }
    close(name);
  }

  template<typename T>
  void XMLWriter::store_array_binary(const char* name, const std::vector<T>& vec)
  {
    std::streampos offset = bin.tellg();
    tab(); xml << "<" << name << " ofs=\"" << offset << "\" size=\"" << vec.size() << "\"/>" << std::endl;
    if (vec.size()) bin.write((char*)vec.data(),vec.size()*sizeof(T));
  }

  template<typename T>
  void XMLWriter::store(const char* name, const std::vector<T>& vec)
  {
    if (binaryFormat) store_array_binary(name,vec);
    else              store_array_text  (name,vec);
  }

  void XMLWriter::store_array_text(const char* name, const avector<Vec3fa>& vec)
  {
    open(name);
    for (size_t i=0; i<vec.size(); i++) {
      tab(); store_array_elt(vec[i]);
    }
    close(name);
  }

  void XMLWriter::store_array_binary(const char* name, const avector<Vec3fa>& vec)
  {
    std::streampos offset = bin.tellg();
    tab(); xml << "<" << name << " ofs=\"" << offset << "\" size=\"" << vec.size() << "\"/>" << std::endl;
    for (size_t i=0; i<vec.size(); i++) bin.write((char*)&vec[i],sizeof(Vec3f));
  }

  void XMLWriter::store(const char* name, const avector<Vec3fa>& vec)
  {
    if (binaryFormat) store_array_binary(name,vec);
    else              store_array_text  (name,vec);
  }

  void XMLWriter::store_array_text(const char* name, const avector<Vec3ff>& vec)
  {
    open(name);
    for (size_t i=0; i<vec.size(); i++) {
      tab(); store_array_elt(vec[i]);
    }
    close(name);
  }

  void XMLWriter::store_array_binary(const char* name, const avector<Vec3ff>& vec)
  {
    std::streampos offset = bin.tellg();
    tab(); xml << "<" << name << " ofs=\"" << offset << "\" size=\"" << vec.size() << "\"/>" << std::endl;
    for (size_t i=0; i<vec.size(); i++) bin.write((char*)&vec[i],sizeof(Vec3ff));
  }

  void XMLWriter::store(const char* name, const avector<Vec3ff>& vec)
  {
    if (binaryFormat) store_array_binary(name,vec);
    else              store_array_text  (name,vec);
  }

  void XMLWriter::store_parm(const char* name, const float& v) {
    tab(); xml << "<float name=\"" << name << "\">" << v << "</float>" << std::endl;
  }

  void XMLWriter::store_parm(const char* name, const Vec3fa& v) {
    tab(); xml << "<float3 name=\"" << name << "\">" << v.x << " " << v.y << " " << v.z << "</float3>" << std::endl;
  }

  void XMLWriter::store_parm(const char* name, const std::shared_ptr<Texture> tex)
  {
    if (tex == nullptr) return;

    if (textureMap.find(tex) != textureMap.end()) {
      tab(); xml << "<texture3d name=\"" << name << "\" id=\"" << textureMap[tex] << "\"/>" << std::endl;
    } else if (embedTextures) {
      std::streampos offset = bin.tellg();
      bin.write((char*)tex->data,tex->width*tex->height*tex->bytesPerTexel);
      const size_t id = textureMap[tex] = currentNodeID++;
      tab(); xml << "<texture3d name=\"" << name << "\" id=\"" << id << "\" ofs=\"" << offset
                 << "\" width=\"" << tex->width << "\" height=\"" << tex->height
                 << "\" format=\"" << Texture::format_to_string(tex->format) << "\"/>" << std::endl;
    }
    else {
      const size_t id = textureMap[tex] = currentNodeID++;
      tab(); xml << "<texture3d name=\"" << name << "\" id=\"" << id << "\" src=\"" << tex->fileName << "\"/>" << std::endl;
    }
  }

  void XMLWriter::store(const char* name, const AffineSpace3fa& space)
  {
    tab(); xml << "<" << name << ">" << std::endl;
    tab(); xml << "  " << space.l.vx.x << " " << space.l.vy.x << " " << space.l.vz.x << " " << space.p.x << std::endl;
    tab(); xml << "  " << space.l.vx.y << " " << space.l.vy.y << " " << space.l.vz.y << " " << space.p.y << std::endl;
    tab(); xml << "  " << space.l.vx.z << " " << space.l.vy.z << " " << space.l.vz.z << " " << space.p.z << std::endl;
    tab(); xml << "</" << name << ">" << std::endl;
  }

  void XMLWriter::store(const SceneGraph::PointLight& light, ssize_t id)
  {
    open("PointLight",id);
    store("AffineSpace",AffineSpace3fa::translate(light.P));
    store("I",light.I);
    close("PointLight");
  }

  void XMLWriter::store(const SceneGraph::SpotLight& light, ssize_t id)
  {
    open("SpotLight",id);
    store("AffineSpace",AffineSpace3fa(frame(light.D),light.P));
    store("I",light.I);
    store("angleMin",light.angleMin);
    store("angleMax",light.angleMax);
    close("SpotLight");
  }

  void XMLWriter::store(const SceneGraph::DirectionalLight& light, ssize_t id)
  {
    open("DirectionalLight",id);
    store("AffineSpace",frame(light.D));
    store("E",light.E);
    close("DirectionalLight");
  }

  void XMLWriter::store(const SceneGraph::DistantLight& light, ssize_t id)
  {
    open("DistantLight",id);
    store("AffineSpace",frame(light.D));
    store("L",light.L);
    store("halfAngle",light.halfAngle);
    close("DistantLight");
  }

  void XMLWriter::store(const SceneGraph::AmbientLight& light, ssize_t id)
  {
    open("AmbientLight");
    store("L",light.L);
    close("AmbientLight");
  }

  void XMLWriter::store(const SceneGraph::TriangleLight& light, ssize_t id)
  {
    open("TriangleLight",id);
    const Vec3fa dx = light.v0-light.v2;
    const Vec3fa dy = light.v1-light.v2;
    const Vec3fa dz = cross(dx,dy);
    const Vec3fa p = light.v2;
    store("AffineSpace",AffineSpace3fa(dx,dy,dz,p));
    store("L",light.L);
    close("TriangleLight");
  }

  void XMLWriter::store(const SceneGraph::QuadLight& light, ssize_t id)
  {
    open("QuadLight",id);
    const Vec3fa dx = light.v3-light.v0;
    const Vec3fa dy = light.v1-light.v0;
    const Vec3fa dz = cross(dx,dy);
    const Vec3fa p = light.v2;
    store("AffineSpace",AffineSpace3fa(dx,dy,dz,p));
    store("L",light.L);
    close("QuadLight");
  }

  void XMLWriter::store(Ref<SceneGraph::LightNode> node, ssize_t id)
  {
    if (auto light = node.dynamicCast<SceneGraph::LightNodeImpl<SceneGraph::AmbientLight>>())
      store(light->light,id);
    else if (auto light = node.dynamicCast<SceneGraph::LightNodeImpl<SceneGraph::PointLight>>())
      store(light->light,id);
    else if (auto light = node.dynamicCast<SceneGraph::LightNodeImpl<SceneGraph::DirectionalLight>>())
      store(light->light,id);
    else if (auto light = node.dynamicCast<SceneGraph::LightNodeImpl<SceneGraph::SpotLight>>())
      store(light->light,id);
    else if (auto light = node.dynamicCast<SceneGraph::LightNodeImpl<SceneGraph::DistantLight>>())
      store(light->light,id);
    else if (auto light = node.dynamicCast<SceneGraph::LightNodeImpl<SceneGraph::TriangleLight>>())
      store(light->light,id);
    else if (auto light = node.dynamicCast<SceneGraph::LightNodeImpl<SceneGraph::QuadLight>>())
      store(light->light,id);
    else
      throw std::runtime_error("unsupported light");
  }

  void XMLWriter::store(Ref<SceneGraph::AnimatedLightNode> node, ssize_t id)
  {
    open(std::string("AnimatedLight ")+
         "time_range=\""+std::to_string(node->time_range.lower)+" "+std::to_string(node->time_range.upper)+"\"");

    for (size_t i=0; i<node->lights.size(); i++)
      store(node->lights[i].dynamicCast<SceneGraph::Node>());

    close("AnimatedLight");
  }

  void XMLWriter::store(Ref<MatteMaterial> material, ssize_t id)
  {
    open("material",id);
    store("code","Matte");
    open("parameters");
    store_parm("reflectance",material->reflectance);
    close("parameters");
    close("material");
  }

  void XMLWriter::store(Ref<MirrorMaterial> material, ssize_t id)
  {
    open("material",id);
    store("code","Mirror");
    open("parameters");
    store_parm("reflectance",material->reflectance);
    close("parameters");
    close("material");
  }

  void XMLWriter::store(Ref<ThinDielectricMaterial> material, ssize_t id)
  {
    open("material",id);
    store("code","ThinDielectric");
    open("parameters");
    store_parm("transmission",material->transmission);
    store_parm("eta",material->eta);
    store_parm("thickness",material->thickness);
    close("parameters");
    close("material");
  }

  void XMLWriter::store(Ref<OBJMaterial> material, ssize_t id)
  {
    open("material",id);
    store("code","OBJ");
    open("parameters");
    store_parm("d",material->d);
    store_parm("Kd",material->Kd);
    store_parm("Ks",material->Ks);
    store_parm("Ns",material->Ns);
    store_parm("map_d",material->_map_d);
    store_parm("map_Kd",material->_map_Kd);
    close("parameters");
    close("material");
  }

  void XMLWriter::store(Ref<MetalMaterial> material, ssize_t id)
  {
    open("material",id);
    store("code","Metal");
    open("parameters");
    store_parm("reflectance",material->reflectance);
    store_parm("eta",material->eta);
    store_parm("k",material->k);
    store_parm("roughness",material->roughness);
    close("parameters");
    close("material");
  }

  void XMLWriter::store(Ref<VelvetMaterial> material, ssize_t id)
  {
    open("material",id);
    store("code","Velvet");
    open("parameters");
    store_parm("reflectance",material->reflectance);
    store_parm("backScattering",material->backScattering);
    store_parm("horizonScatteringColor",material->horizonScatteringColor);
    store_parm("horizonScatteringFallOff",material->horizonScatteringFallOff);
    close("parameters");
    close("material");
  }

  void XMLWriter::store(Ref<DielectricMaterial> material, ssize_t id)
  {
    open("material",id);
    store("code","Dielectric");
    open("parameters");
    store_parm("transmissionOutside",material->transmissionOutside);
    store_parm("transmission",material->transmissionInside);
    store_parm("etaOutside",material->etaOutside);
    store_parm("etaInside",material->etaInside);
    close("parameters");
    close("material");
  }

  void XMLWriter::store(Ref<MetallicPaintMaterial> material, ssize_t id)
  {
    open("material",id);
    store("code","MetallicPaint");
    open("parameters");
    store_parm("shadeColor",material->shadeColor);
    store_parm("glitterColor",material->glitterColor);
    store_parm("glitterSpread",material->glitterSpread);
    store_parm("eta",material->eta);
    close("parameters");
    close("material");
  }

  void XMLWriter::store(Ref<HairMaterial> material, ssize_t id)
  {
    open("material",id);
    store("code","Hair");
    open("parameters");
    store_parm("Kr",material->Kr);
    store_parm("Kt",material->Kt);
    store_parm("nx",material->nx);
    store_parm("ny",material->ny);
    close("parameters");
    close("material");
  }

  void XMLWriter::store(Ref<SceneGraph::MaterialNode> mnode)
  {
    /* let materials reference by their name, allows separate bindings of materials */
    if (referenceMaterials) {
      tab(); xml << "<material id=\""+mnode->name+"\"/>" << std::endl;
      return;
    }

    Ref<SceneGraph::Node> node = mnode.dynamicCast<SceneGraph::Node>();
    if (nodeMap.find(node) != nodeMap.end()) {
      tab(); xml << "<material id=\"" << nodeMap[node] << "\"/>" << std::endl;
      return;
    }
    const ssize_t id = nodeMap[node] = currentNodeID++;

    if      (Ref<OBJMaterial> m = mnode.dynamicCast<OBJMaterial>()) store(m,id);
    else if (Ref<ThinDielectricMaterial> m = mnode.dynamicCast<ThinDielectricMaterial>()) store(m,id);
    else if (Ref<MetalMaterial> m = mnode.dynamicCast<MetalMaterial>()) store(m,id);
    else if (Ref<VelvetMaterial> m = mnode.dynamicCast<VelvetMaterial>()) store(m,id);
    else if (Ref<DielectricMaterial> m = mnode.dynamicCast<DielectricMaterial>()) store(m,id);
    else if (Ref<MetallicPaintMaterial> m = mnode.dynamicCast<MetallicPaintMaterial>()) store(m,id);
    else if (Ref<MatteMaterial> m = mnode.dynamicCast<MatteMaterial>()) store(m,id);
    else if (Ref<MirrorMaterial> m = mnode.dynamicCast<MirrorMaterial>()) store(m,id);
    else if (Ref<ReflectiveMetalMaterial> m = mnode.dynamicCast<ReflectiveMetalMaterial>()) store(m,id);
    else if (Ref<HairMaterial> m = mnode.dynamicCast<HairMaterial>()) store(m,id);
    else throw std::runtime_error("unsupported material");
  }

  void XMLWriter::store(Ref<SceneGraph::TriangleMeshNode> mesh, ssize_t id)
  {
    open("TriangleMesh",id);
    store(mesh->material);

    if (mesh->numTimeSteps() != 1) open("animated_positions");
    for (const auto& p : mesh->positions) store("positions",p);
    if (mesh->numTimeSteps() != 1) close("animated_positions");

    if (mesh->numTimeSteps() != 1) open("animated_normals");
    for (const auto& p : mesh->normals) store("normals",p);
    if (mesh->numTimeSteps() != 1) close("animated_normals");

    store("texcoords",mesh->texcoords);
    store("triangles",mesh->triangles);
    close("TriangleMesh");
  }

  void XMLWriter::store(Ref<SceneGraph::QuadMeshNode> mesh, ssize_t id)
  {
    open("QuadMesh",id);
    store(mesh->material);

    if (mesh->numTimeSteps() != 1) open("animated_positions");
    for (const auto& p : mesh->positions) store("positions",p);
    if (mesh->numTimeSteps() != 1) close("animated_positions");

    if (mesh->numTimeSteps() != 1) open("animated_normals");
    for (const auto& p : mesh->normals) store("normals",p);
    if (mesh->numTimeSteps() != 1) close("animated_normals");

    store("texcoords",mesh->texcoords);
    store("indices",mesh->quads);
    close("QuadMesh");
  }

  void XMLWriter::store(Ref<SceneGraph::SubdivMeshNode> mesh, ssize_t id)
  {
    open("SubdivisionMesh",id);
    store(mesh->material);

    if (mesh->numTimeSteps() != 1) open("animated_positions");
    for (const auto& p : mesh->positions) store("positions",p);
    if (mesh->numTimeSteps() != 1) close("animated_positions");

    if (mesh->numTimeSteps() != 1) open("animated_normals");
    for (const auto& p : mesh->normals) store("normals",p);
    if (mesh->numTimeSteps() != 1) close("animated_normals");

    store("texcoords",mesh->texcoords);
    store("position_indices",mesh->position_indices);
    store("normal_indices",mesh->normal_indices);
    store("texcoord_indices",mesh->texcoord_indices);
    store("faces",mesh->verticesPerFace);
    store("holes",mesh->holes);
    store("edge_creases",mesh->edge_creases);
    store("edge_crease_weights",mesh->edge_crease_weights);
    store("vertex_creases",mesh->vertex_creases);
    store("vertex_crease_weights",mesh->vertex_crease_weights);
    close("SubdivisionMesh");
  }

  void XMLWriter::store(Ref<SceneGraph::HairSetNode> mesh, ssize_t id)
  {
    std::string str_type = "";
    std::string str_subtype = "";

    switch (mesh->type) {
    case RTC_GEOMETRY_TYPE_FLAT_LINEAR_CURVE:
      str_type = "linear";
      str_subtype = "flat";
      break;

    case RTC_GEOMETRY_TYPE_ROUND_BEZIER_CURVE:
      str_type = "bezier";
      str_subtype = "round";
      break;

    case RTC_GEOMETRY_TYPE_FLAT_BEZIER_CURVE:
      str_type = "bezier";
      str_subtype = "flat";
      break;

    case RTC_GEOMETRY_TYPE_NORMAL_ORIENTED_BEZIER_CURVE:
      str_type = "bezier";
      str_subtype = "oriented";
      break;

    case RTC_GEOMETRY_TYPE_ROUND_BSPLINE_CURVE:
      str_type = "bspline";
      str_subtype = "round";
      break;

    case RTC_GEOMETRY_TYPE_FLAT_BSPLINE_CURVE:
      str_type = "bspline";
      str_subtype = "flat";
      break;

    case RTC_GEOMETRY_TYPE_NORMAL_ORIENTED_BSPLINE_CURVE:
      str_type = "bspline";
      str_subtype = "oriented";
      break;

    default:
      throw std::runtime_error("invalid curve type");
    }

    std::vector<int> indices(mesh->hairs.size());
    std::vector<int> hairid(mesh->hairs.size());
    for (size_t i=0; i<mesh->hairs.size(); i++) {
      indices[i] = mesh->hairs[i].vertex;
      hairid[i] = mesh->hairs[i].id;
    }

    open("Curves type=\""+str_subtype+"\" basis=\""+str_type+"\"",id);
    store(mesh->material);
    if (mesh->numTimeSteps() != 1) open("animated_positions");
    for (const auto& p : mesh->positions) store("positions",p);
    if (mesh->numTimeSteps() != 1) close("animated_positions");
    if (mesh->normals.size()) {
      if (mesh->numTimeSteps() != 1) open("animated_normals");
      for (const auto& p : mesh->normals) store("normals",p);
      if (mesh->numTimeSteps() != 1) close("animated_normals");
    }
    store("indices",indices);
    store("hairid",hairid);
    close("Curves");
  }

  void XMLWriter::store(Ref<SceneGraph::PerspectiveCameraNode> camera, ssize_t id)
  {
    tab();
    xml << "<PerspectiveCamera " <<
      "id=\"" << id << "\" " <<
      "name=\"" << camera->name << "\" " <<
      "from=\"" << camera->data.from.x << " " << camera->data.from.y << " " << camera->data.from.z << "\" " <<
      "to=\""   << camera->data.to.x   << " " << camera->data.to.y   << " " << camera->data.to.z << "\" " <<
      "up=\""   << camera->data.up.x   << " " << camera->data.up.y   << " " << camera->data.up.z << "\" " <<
      "fov=\""  << camera->data.fov << "\" " << "/>" << std::endl;
  }

  void XMLWriter::store(Ref<SceneGraph::AnimatedPerspectiveCameraNode> camera, ssize_t id)
  {
    open(std::string("AnimatedPerspectiveCamera ")+
         "name=\"" + camera->name + "\" "
         "time_range=\""+std::to_string(camera->time_range.lower)+" "+std::to_string(camera->time_range.upper)+"\"");

    for (size_t i=0; i<camera->size(); i++)
      store(camera->cameras[i].dynamicCast<SceneGraph::Node>());

    close("AnimatedPerspectiveCamera");
  }

  void XMLWriter::store(Ref<SceneGraph::TransformNode> node, ssize_t id)
  {
    if (node->spaces.size() == 1)
    {
      open("Transform",id);
      store("AffineSpace",node->spaces[0]);
      store(node->child);
      close("Transform");
    }
    else
    {
      open("TransformAnimation",id);
      for (size_t i=0; i<node->spaces.size(); i++)
        store("AffineSpace",node->spaces[i]);
      store(node->child);
      close("TransformAnimation");
    }
  }

  void XMLWriter::store(std::vector<Ref<SceneGraph::TransformNode>> nodes)
  {
    if (nodes.size() == 0)
      return;

    if (nodes.size() == 1) {
      store(nodes[0].dynamicCast<SceneGraph::Node>());
      return;
    }

    open("MultiTransform");
    std::streampos offset = bin.tellg();
    tab(); xml << "<AffineSpace3f ofs=\"" << offset << "\" size=\"" << nodes.size() << "\"/>" << std::endl;
    for (size_t i=0; i<nodes.size(); i++) {
      assert(nodes[i]->spaces.size() == 1);
      assert(nodes[i]->child == nodes[0]->child);
      bin.write((char*)&nodes[i]->spaces[0].l.vx,sizeof(Vec3f));
      bin.write((char*)&nodes[i]->spaces[0].l.vy,sizeof(Vec3f));
      bin.write((char*)&nodes[i]->spaces[0].l.vz,sizeof(Vec3f));
      bin.write((char*)&nodes[i]->spaces[0].p,sizeof(Vec3f));
    }
    store(nodes[0]->child);
    close("MultiTransform");
  }

  void XMLWriter::store(Ref<SceneGraph::GroupNode> group, ssize_t id)
  {
    open("Group",id);

    std::map<Ref<SceneGraph::Node>,std::vector<Ref<SceneGraph::TransformNode>>> object_to_transform_map;
    for (size_t i=0; i<group->children.size(); i++)
    {
      /* compress transformation of the same object into MultiTransform nodes if possible */
      if (Ref<SceneGraph::TransformNode> xfmNode = group->children[i].dynamicCast<SceneGraph::TransformNode>())
      {
        /* we can only compress non-animated transform nodes and only ones that are referenced once */
        if (xfmNode->spaces.size() == 1 && xfmNode->indegree == 1)
        {
          Ref<SceneGraph::Node> child = xfmNode->child;
          if (object_to_transform_map.find(child) == object_to_transform_map.end()) {
            object_to_transform_map[child] = std::vector<Ref<SceneGraph::TransformNode>>();
          }
          object_to_transform_map[child].push_back(xfmNode);
          continue;
        }
      }
      store(group->children[i]);
    }

    /* store all compressed transform nodes */
    for (auto i : object_to_transform_map)
      store(i.second);

    close("Group");
  }

  void XMLWriter::store(Ref<SceneGraph::Node> node)
  {
    if (nodeMap.find(node) != nodeMap.end()) {
      tab(); xml << "<ref id=\"" << nodeMap[node] << "\"/>" << std::endl; return;
    }

    const ssize_t id = nodeMap[node] = currentNodeID++;
    if (node->fileName != "") {
      tab(); xml << "<extern id=\"" << id << "\" src=\"" << node->fileName << "\"/>" << std::endl; return;
    }

    if      (Ref<SceneGraph::AnimatedLightNode> cnode = node.dynamicCast<SceneGraph::AnimatedLightNode>()) store(cnode,id);
    else if (Ref<SceneGraph::LightNode> cnode = node.dynamicCast<SceneGraph::LightNode>()) store(cnode,id);
    //else if (Ref<SceneGraph::MaterialNode> cnode = node.dynamicCast<SceneGraph::MaterialNode>()) store(cnode,id);
    else if (Ref<SceneGraph::TriangleMeshNode> cnode = node.dynamicCast<SceneGraph::TriangleMeshNode>()) store(cnode,id);
    else if (Ref<SceneGraph::QuadMeshNode> cnode = node.dynamicCast<SceneGraph::QuadMeshNode>()) store(cnode,id);
    else if (Ref<SceneGraph::SubdivMeshNode> cnode = node.dynamicCast<SceneGraph::SubdivMeshNode>()) store(cnode,id);
    else if (Ref<SceneGraph::HairSetNode> cnode = node.dynamicCast<SceneGraph::HairSetNode>()) store(cnode,id);
    else if (Ref<SceneGraph::AnimatedPerspectiveCameraNode> cnode = node.dynamicCast<SceneGraph::AnimatedPerspectiveCameraNode>()) store(cnode,id);
    else if (Ref<SceneGraph::PerspectiveCameraNode> cnode = node.dynamicCast<SceneGraph::PerspectiveCameraNode>()) store(cnode,id);
    else if (Ref<SceneGraph::TransformNode> cnode = node.dynamicCast<SceneGraph::TransformNode>()) store(cnode,id);
    else if (Ref<SceneGraph::GroupNode> cnode = node.dynamicCast<SceneGraph::GroupNode>()) store(cnode,id);
    else throw std::runtime_error("unknown node type");
  }

  XMLWriter::XMLWriter(Ref<SceneGraph::Node> root, const FileName& fileName, bool embedTextures, bool referenceMaterials, bool binaryFormat)
    : ident(0), currentNodeID(0), embedTextures(embedTextures), referenceMaterials(referenceMaterials), binaryFormat(binaryFormat)
  {
    xml.exceptions (std::fstream::failbit | std::fstream::badbit);
    xml.open (fileName, std::fstream::out);

    if (binaryFormat)
    {
      const FileName binFileName = fileName.addExt(".bin");
      bin.exceptions (std::fstream::failbit | std::fstream::badbit);
      bin.open (binFileName, std::fstream::out | std::fstream::binary);
    }

    xml << "<?xml version=\"1.0\"?>" << std::endl;
    root->calculateInDegree();
    open("scene");
    store(root);
    close("scene");
    root->resetInDegree();
  }

  void SceneGraph::storeXML(Ref<SceneGraph::Node> root, const FileName& fileName, bool embedTextures, bool referenceMaterials, bool binaryFormat) {
    XMLWriter(root,fileName,embedTextures,referenceMaterials,binaryFormat);
  }
}


text:
require 'json'

def evaluate obj,total
  case obj.class.to_s
  when "Hash"
    obj.each do |k,v|
      total = evaluate(k,total)
      total = evaluate(v,total)
    end
  when "Array"
    obj.each { |e| total = evaluate(e,total) }
  when "Fixnum"
    total += obj
  end
  return total
end

data = File.read("input12.txt")
data_hash = JSON.parse(data)
puts evaluate(data_hash,0)

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Reflection;

namespace SimpleFixture.Impl
{
    public interface ITypePopulator
    {
        void Populate(object instance, DataRequest request, ComplexModel model);
    }

    public class TypePopulator : ITypePopulator
    {
        private readonly IPropertySetter _setter;
        private readonly ITypePropertySelector _propertySelector;
        private readonly IConstraintHelper _helper;
        private readonly IFixtureConfiguration _configuration;
        private readonly ITypeFieldSelector _fieldSelector;
        private readonly IFieldSetter _fieldSetter;

        public TypePopulator(IFixtureConfiguration configuration,
                             IConstraintHelper helper,
                             ITypePropertySelector propertySelector,
                             IPropertySetter setter,
                             ITypeFieldSelector fieldSelector,
                             IFieldSetter fieldSetter)
        {
            _configuration = configuration;
            _helper = helper;
            _propertySelector = propertySelector;
            _setter = setter;
            _fieldSelector = fieldSelector;
            _fieldSetter = fieldSetter;
        }

        public virtual void Populate(object instance, DataRequest request, ComplexModel model)
        {
            if (instance == null)
            {
                return;
            }

            if (_configuration.PopulateProperties)
            {
                foreach (var propertyInfo in _propertySelector.SelectProperties(instance, request, model))
                {
                    object propertyValue = null;

                    if (_configuration.CircularReferenceHandling == CircularReferenceHandlingAlgorithm.AutoWire)
                    {
                        var currentRequest = request;
                        var requestTypeInfo = propertyInfo.PropertyType.GetTypeInfo();

                        while (currentRequest != null)
                        {
                            if (requestTypeInfo.IsAssignableFrom(currentRequest.RequestedType.GetTypeInfo()))
                            {
                                propertyValue = currentRequest.Instance;
                                break;
                            }

                            currentRequest = currentRequest.ParentRequest;
                        }
                    }

                    var newRequest = CreateDataRequestForProperty(propertyInfo, request);

                    var foundProperty = false;

                    if (propertyValue == null)
                    {
                        foundProperty = _helper.GetUnTypedValue(out propertyValue, propertyInfo.PropertyType, request.Constraints, null, propertyInfo.Name);

                        if (propertyValue != null)
                        {
                            propertyValue = newRequest.Fixture.Behavior.Apply(newRequest, propertyValue);
                        }
                    }

                    if(!foundProperty && propertyValue == null)
                    {
                        if (!model.GetPropertyValue(newRequest, propertyInfo, out propertyValue))
                        {
                            if (model.SkipProperty(newRequest, propertyInfo))
                            {
                                continue;
                            }

                            propertyValue = newRequest.Fixture.Generate(newRequest);
                        }
                        else
                        {
                            propertyValue = newRequest.Fixture.Behavior.Apply(newRequest, propertyValue);
                        }
                    }

                    if (!foundProperty && propertyValue == null)
                    {
                        throw new Exception("Could not create type " + propertyInfo.PropertyType.FullName);
                    }

                    _setter.SetProperty(propertyInfo, instance, propertyValue);
                }
            }

            if (_configuration.PopulateFields)
            {
                foreach (var fieldInfo in _fieldSelector.SelectFields(instance, request, model))
                {
                    object propertyValue;
                    var foundValue = _helper.GetUnTypedValue(out propertyValue, fieldInfo.FieldType, request.Constraints, null, fieldInfo.Name);

                    var newRequest = CreateDataRequestForField(fieldInfo, request);

                    if (propertyValue != null)
                    {
                        propertyValue = newRequest.Fixture.Behavior.Apply(newRequest, propertyValue);
                    }
                    else if(!foundValue)
                    {
                        propertyValue = newRequest.Fixture.Generate(newRequest);
                    }

                    if (!foundValue && propertyValue == null)
                    {
                        throw new Exception("Could not create type " + fieldInfo.FieldType.FullName);
                    }

                    _fieldSetter.SetField(fieldInfo, instance, propertyValue);
                }
            }
        }

        protected virtual DataRequest CreateDataRequestForProperty(PropertyInfo propertyInfo, DataRequest request)
        {
            return new DataRequest(request,
                                    request.Fixture,
                                    propertyInfo.PropertyType,
                                    DependencyType.PropertyDependency,
                                    propertyInfo.Name,
                                    true,
                                    request.Constraints,
                                    propertyInfo);
        }

        protected virtual DataRequest CreateDataRequestForField(FieldInfo fieldInfo, DataRequest request)
        {
            return new DataRequest(request,
                                    request.Fixture,
                                    fieldInfo.FieldType,
                                    DependencyType.PropertyDependency,
                                    fieldInfo.Name,
                                    true,
                                    request.Constraints,
                                    fieldInfo);
        }
    }
}


text:
package org.andengine.entity.particle.initializer;

import org.andengine.entity.IEntity;

import android.hardware.SensorManager;

/**
 * (c) 2010 Nicolas Gramlich (c) 2011 Zynga Inc.
 *
 * @author Nicolas Gramlich
 * @since 12:04:00 - 15.03.2010
 */
public class GravityParticleInitializer<T extends IEntity> extends AccelerationParticleInitializer<T> {
	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Fields
	// ===========================================================

	// ===========================================================
	// Constructors
	// ===========================================================

	public GravityParticleInitializer() {
		super(0, SensorManager.GRAVITY_EARTH);
	}

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	// ===========================================================
	// Methods
	// ===========================================================

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}


text:
Juliog
===
Open Source Verilog Based Hardware Description Language Written in the Julia Programming Language

LOADING A JULIOG FUNCTION INTO JULIA
---

Juliog functions cannot be directly parsed into the julia command-line or your operating system's command console.
They must first be parsed through a preprocesser to sanitize the syntax and convert the (julia-esque) syntax to genuinely runnable julia code

There are 3 ways to input juliog code for loading

1) Call the parsefile function on a juliog file of interest

   ```julia
   julia> func = parsefile(file_dir)
   ```

   where file_dir is the file location as a string of where the juliog function is found

   ```julia
   julia> file_dir = "C:/Users/Trevor/Documents/full_adder.jl"
   julia> func = parsefile(file_dir)
   ```

2) Through a blocked expression

   ```julia
   julia> func = :(
	   function example(example_input, example_output)
	    	# example implementation
	    end
   )
   ```

3) Through a quoted expression

   ```julia
   julia> func = quote
	   function example(example_input, example_output)
		   # example implementation
	   end
   end
   ```

Then once the Juliog has been entered into Julia as an Expr, run loadJULIOGexpr

```julia
julia> loadJULIOGexpr(func)
```

Where func is the name of the inputted expression

Then, for preprocessing, run @block

```julia
julia> @block example "Arbitrary Block Name" (example_in, example_out)
```

Where `:example` is the name of the hardware function, `"Arbitrary Block Name"` is the arbitary name of the hardware block implementation, and `the Tuple` contains the names of testbench wires and parameters.

JULIOG SYNTAX
---

### How to set parameters

There are 4 ways to set parameters to a hardware design function

1) Setting a local parameter

   Behaves identically to  `localparm` in Verilog
   Just call an assignment within a juliog function.
   This cannot be overwritten at a higher level.

   ```julia
	   julia> this_param = 5
   ```

2) Passing a parameter through function interface

   Behaves identically to `parameter` in Verilog.
   If your hardware function has keywords they can be overwritten.

   ```julia
       julia> function LOGIC(OUT, IN ; passed_param = 8)
		   # LOGIC implementation
	   end
   ```

   This then is called from above by:

   ```julia
	   julia> @block LOGIC "Clever_Name" (OUT_wire, IN_wire ; passed_param = 16)
   ```

   Where for the LOGIC hardware function, the passed_param has been overwritten.

3) Importing a modular parameter

   First create a module of parameters, likely in your command-line or an include file.

   ```julia
   julia> module my_parameters
	   word_length   = 32
	   nibble_length = 4
   end
   ```

   then import the module in your hardware function

   ```julia
   julia> function LOGIC(OUT, IN)
	   import my_parameters
	   # LOGIC implementation
   end
   ```

   Alternatively, individual parameters can be requested

   ```julia
   julia> function LOGIC(OUT, IN)
	   import my_parameters.word_length
	   import my_parameters.nibble_length
   end
   ```

   This follows the Julia Module syntax, see [Julia Stable Modules](https://docs.julialang.org/en/stable/manual/modules/)

4) Create a global parameter

   This behaves similarly to #define in Verilog.

   You can just set a large portion of your design according to a specific global parameter, greatly reducing code complexity.

   ```julia
   julia> function LOGIC(OUT, IN)
	   global global_param
	   # LOGIC implementation
   end
   ```

   Then, somewhere in the testbench, the console command-line, or an include file:

   ```julia
	   julia> global global_param = 16
   ```

   The parameterization step of preprocessing will take care the rest.

### How to create a wire

There are 5(+1) ways to create a wire

1) Create a wire of indeterminate bit length (not yet supported)

   ```julia
   julia> indet_wire = Wire()
   ```

2) Create a wire of bit length 1

   ```julia
   julia> bit_wire = Wire()[a]
   ```

   where a is a non-negative Int

3) Create a wire of bit length 1 or greater

   ```julia
   julia> bus_wire = Wire()[a:b]
   ```

   where a and b are non-negative Ints.

   a and b can be the same number, i.e. bit length of 1.

   both endians accepted:
   Either a or b can be greater than the other.

4) Assign a value to an undefined variable name

   ```julia
   julia> isdefined(:new_wire) # this returns false
   julia> new_wire = A & B # the := can also be used here
   ```

   The bit length of the new_wire will be determined by the bit length of the wire that the right hand side solves to.
   For this example the bit length would be that of A and B

5) Assign a value to an undefined variable name of determinate bit length

   ```julia
   julia> isdefined(:new_wire) # this returns false
   julia> new_wire[7:0] = A & B # the := can also be used here
   ```

6) Maybe a vcat or a tuple (not yet implemented)

   ```julia
   julia> [cout ; sum] := A + B
   julia cout, sum := A + B
   ```

Output and input creation only allows for 1-3 above:

```julia
julia> indet_output = Output()
julia> indet_input  = Input()
julia> bit_output   = Output()[a]
julia> bit_input    = Input()[a]
julia> wire_input    = Input()[a:b]
julia> wire_output   = Output()[a:b]
```

### Higher Dimensionality Wires (in progress, but not yet complete, do not use)

* This section needs fleshing out
* Mention difference between Julia matrix syntax and verilog bus syntax

Just like any other higher-order programming language, Julia supports multidimentional arrays.

Juliog extends this functionality for the creation of multi-dimensional wires.

Multi-dimensional wires are commonly refered to as buses in Verilog parlance.

Buses of indeterminate width are not allowed, but the wires within can still be indeterminate.

```julia
julia> bus_bit_wires   = Wire()[a][c:d]
julia> bus_wires       = Wire()[a:b][c:d]
julia> bus_indet_wires = Wire()[][c:d]
```

The same is also capable for inputs and outputs, using same syntax

```julia
julia> bus_bit_inputs    =  Input()[a][c:d]
julia> bus_inputs        =  Input()[a:b][c:d]
julia> bus_bit_outputs   = Output()[a][c:d]
julia> bus_outputs       = Output()[a:b][c:d]
```

### Wire Assignments

Can be accomplished in 1 of 3 seperate ways

1) using equals operator (=) after wire creation

   ```julia
   julia> created_wire = Wire()
   julia> created_wire = A & B
   ```

2) using colon-equals operator (:=) after wire creation

   ```julia
   julia> created_wire = Wire()
   julia> created_wire := A & B
   ```

    Note that this is functionally equivalent to using the = operator at the gate level

    The = operator is converted to the := operator in preprocessing and the := is ultimately used for assignment once converting to Verilog and Julia

     A reason the designer may choose to use := over = is for ease of code clarity, keeping assignments as := may improve code legibility

3) Using = or := to declare an as of yet undeclared wire

   ```julia
   julia> undeclared_wire = A & B
   # OR
   julia> undeclared_wire := A & B
   ```

A wire can also be assigned to a constant value

But only after it is already created, otherwise the wire will be replaced through out the codebase with your static value

```julia
julia> const_25 = Wire()
julia> const_25 = 25
```

Whereas the following will not create a wire, but will create a parameter:

```julia
julia> const_25 = 25
```

* Add reverse indexing explanation

### Bit indexing

Indexing a wire on the right hand side of = or := is identical to verilog syntax

```julia
julia> word = Input()[7:0]
julia> upper_nibble = word[7:4]
julia> lower_nibble = word[3:0]
julia> one_bit = word[7]
```

Of course, the colon-equals operator is also fine

```julia
julia> word = Input()[7:0]
julia> upper_nibble := word[7:4]
julia> lower_nibble := word[3:0]
julia> one_bit := word[7]
```

### Bit(s) Assignment

The bits of a wire can be assigned on the left hand side

But only for a wire which has already been created

```julia
julia> upper_nibble = Input()[3:0]
julia> lower_nibble = Input()[3:0]
julia> nibbles = Wire()[7:0]
julia> nibbles[7:4] = upper_nibble
julia> nibbles[3:0] = lower_nibble
```

The following two examples would also be accepted:

```julia
julia> upper_nibble = Input()[3:0]
julia> lower_nibble = Input()[3:0]
julia> nibbles = Wire()[7:0]
julia> nibbles[7:4] = upper_nibble[3:0]
julia> nibbles[3:0] = lower_nibble[3:0]
```

```julia
julia> upper_nibble = Input()[3:0]
julia> lower_nibble = Input()[3:0]
julia> nibbles = Wire()[7:0]
julia> nibbles[7:4] := upper_nibble[3:0]
julia> nibbles[3:0] := lower_nibble[3:0]
```

Note that again, the := operator is acceptable for assignment. It is, not, however acceptable to use a := operator for Wire or I/O creation. The = operator is exclusive for that operation.

Note also, that the following is NOT accepted, since nibbles was not previously created:

```julia
julia> upper_nibble = Input()[3:0]
julia> lower_nibble = Input()[3:0]
julia> nibbles[7:4] = upper_nibble # Throws an Error
julia> nibbles[3:0] = lower_nibble # Throws an Error
```

In this example, we are attempting to write to bits which we are not certain actually exist. There is a means by which this could be acceptable, but in the Juliog language, we ban it outright. Writing to specific bits of wires is only allowed if the wire is created *A Priori*.

### Bit Concatentation

The bits of any two or more wires can be concatenated in the following manner

```julia
julia> combined = [a ; b]     # for 2 wires
julia> combined = [a ; b ; c] # for 3 wires
julia> # can be extended for any number of wires
```

The wires of interest can, of course, be the indexed bit(s) of a larger wire

```julia
julia> combined = [a[3:0] ; a[1:0] ; b[5:0]]
```

### Bit Repetition

A wire's bit(s) can be concatenated to itself a set number of times

```julia
julia> bit_repeats = a(repeats)
julia> other_bit_repeats = a[3:0](repeats)
```

Where a is a wire, and repeats is an integer

These can also be concatenated just as above:

```julia
julia> complicated = [ a(repeats) ; a[1:0](8) ; b[1:0] ]
```

### Supported Logic Functions

```
&   - AND
|   - OR
~   - NOT
+   - ADD
-   - SUB
*   - MULT
/   - DIV
%   - REM
==  - Equivalence
!=  - Non-Equivalence
>   - Greater than
<   - Lesser than
>=  - Greater than or equal to
<=  - Lesser than or equal to
<<  - Shift Left
>>  - Logical Shift Right

>>> - Arithmetic Shift Right
	An important note about the shift right operations
	The >>> in Julia is the logical shift right
	The >> in Julia is the arithmetic shift right
	This is opposite in Verilog, and so JG code follows the verilog convention
	Outside of JG, file, they will be in the julia convention
	BE CAREFUL.

^ - XOR
	An important note about the xor operation:
	The xor function in Julia is called by xor(num, other_num)
	The ^ operator is reserved for the power function
		e.g. 2 ^ 5 => 32
	So in preprocessing, the ^ op is replaced by a xor function call
	Outside of JG file, the ^ op will act as a power operator
	BE CAREFUL.

? : - MUX
	An imporant note about the ? : operation
	the ? : op is parsed in julia into an if-else statement
	It is therefore completely indistinguishable from an if-else statement

Latch - through special logic see below
Reg   - through special logic see below
```

Unitary & and | not yet supported, support is in decision

### Instantiating Children Hardware functions

```julia
julia> :(
	function LOGIC(OUT, IN)
	# LOGIC implementation

	@block CHILD_LOGIC "the_child_logic" (ol_output, my_val)

	# More LOGIC implementation
	end
)
```

Strings in block names enable interpolation, which can then be used to dynamically change name at compile time:

```julia
julia> :(
	function LOGIC(OUT, IN)
	# LOGIC implementation

	for i = 1:n
		@block CHILD_LOGIC "child_logic_$(i)" (ol_output[i], my_val)
	end

	# More LOGIC implementation
	end
)
```

### if-else constructs

At the parameterization stage, any variables will be replaced with their constant values.

Any statically defined if conditions will reduce to either `true` or `false` at compile time. If the condition reduces to the static Bool `true` then the contents of the if block will be raised to the level of the if statement, the condition will be removed, and the else block will be removed. For an if statment in the function block, the if block will be raised to function block; for a nested if statement, the nested if will be raised to the parent if statement. If the condition is reduced to a static Bool `false` then the contents of the else block will be raised, the if block will be removed, and the condition will be removed. Should no else condition exist, then nothing will be raised, and the entire if statement will be removed.

```julia
julia> :(
	architecure = "Accumulating"
	if architecture == "Accumulating"
		# Accumulating architecture code
	else
		# Non accumulating architecture code
	end
)
```

When the parameter (can also be referred to as a local variable) :architecture is defined to be "Accumulating" the block will be reduced to the following:

```julia
julia> :(
	if true
		# Accumulating architecture code
	else
		# Non accumulating architecture code
	end
)
```

And, ultimately:

```julia
julia> :(
	# Accumulating architecture code
)
```

For the if statement condition which is not statically defined (i.e. dynamically defined in relation to a wire value) the if statement and all of its constituent parts (the if condition, the if block, and the else block should it exist) will be parameterized, but not raised, nor removed.

If the if statement can't be determined at compilation time
i.e. The if statement is determined by a wire:

```julia
julia> :(
	# nibble_index, out_wire, and value are created as wires
	if nibble_index == 0
		out_wire = value[3:0]
	else
		out_wire = value[7:4]
	end
)
```

Then the if statement will not be block-wise reduced as above.
Constants where applicable, even within the if block, will still be replaced.
And the if-else statement will be turned into a MUX at preprocessing time.

### Case Statements

Aren't supported natively in Julia, and are not supported here, as well.

Case statements are an additional abstraction which may never be necessary.

### for loops

Juliog can unroll for loops.

```julia
julia> :(
	# l is a parameter and equals 3; c, a, b are created as wires
	for i = 0:l
		c[i] = a[i] + b[i]
		# Other assignments
	end
)

```

At compile time, the static for condition will unroll the above to the following code snippet:

```julia
julia> :(
	c[0] = a[0] + b[0]
	# Other assignments
	c[1] = a[1] + b[1]
	# Other assignments
	c[2] = a[2] + b[2]
	# Other assignments
	c[3] = a[3] + b[3]
	# Other assignments
)

```

Supports 4 Syntaxes for the for condition:

```julia
julia> for i = 1:l
julia> for i = [1; 2; 4; 6; 27] # Vertical Concatenation
julia> for i = [1  2  4  6  27] # Horizontal Concatentation
julia> for i = [1, 2, 4, 6, 27] # Vectors
```

### Important Macros

```julia
@reg
```

Can be used to create any kind of register

```julia
@posedge
```

Can be used to create a posedge register (or a synchronously resetteble PR)

```julia
@negedge
```

Can be used to create a negedge register (or a synchronously resetteble NR)

```julia
@async
```

Can be used to quote off specific block of functional asynchronous logic

```julia
@delay
```

Can be used to establish a delay for a specific Juliog assignment or lines of code

```julia
@block
```

Can be used to initialize a submodule

```julia
@verilog
```

Any string following @verilog will be unchanged and spit directly to Verilog

```julia
@julia
```

Any string following @julia will be unchanged and spit directly to Julia

### Creating Registers

The @posedge macro

```julia
julia> :(
	# CLK, D, Q created as wires

	@posedge CLK begin
		Q <= D
	end

	# Alternatively
	@posedge CLK begin
		Q = D
	end
)
```

The @negedge macro

```julia
julia> :(
	# CLK, D, Q created as wires

	@negedge CLK begin
		Q <= D
	end

	# Alternatively
	@negedge CLK begin
		Q = D
	end
)
```

The @reg macro

```julia
julia> :(
	# RST, CLK, D, Q created as wires

	# for a posedge
	@reg begin
		if CLK == 1
			Q = D
		end
	end

	# for a negedge
	@reg begin
		if CLK == 0
			Q = D
		end
	end

	# for a double-edged
	@reg begin
		if     CLK == 1
			Q = D
		elseif CLK == 0
			Q = D
		end
	end

	# for an async-reset posedge
	@reg begin
		if     RST == 1
			Q = 0
		elseif CLK = 1
			Q = D
		end
	end
)
```

### Creating Latches

Use an if-else or a ternary operation to create latches

```julia
julia> :(
	# pass, D, and Q created as wires

	if   pass == 1
		D = Q
	else
		D = D
	end
)
```

Or with the ternary operation:

```julia
julia> :(
	# pass, D, and Q created as wires

	D = (pass == 1) ? Q : D
)
```

Just like Verilog, Juliog supports "accidentally" creating latches:

```julia
julia> :(
	# pass, D, and Q created as wires

	if pass == 1
		D = Q
	end
)
```

Note that the sanitization stage of preprocessing will warn you of the accidental latch. The explicit latch created by the other two examples will NOT warn you.

### Creating Delays

Use the @delay macro

```julia
@delay floating_point assignment
```

The number must be represented as a floating point number.

e.g. for a delay of 5

```julia
julia> :(
	@delay 5.0  A := B[3:0]
	# OR
	@delay 5.0 begin
		A := B[3:0]
	end
)
```

### Difference between logic inside and outside @async call

Logic can be established inside a seperate @async macro

```julia
julia> :(
	@async begin
		A := B[3:0]
	end
)
```

Any logic included inside of an @async block is indistinguishable from logic outside of an @async block. So the following example is logically equivalent to the above example:

```julia
julia> :(
	A := B[3:0]
)

```

However, the reason for its inclusion is

1) Aid in code clarity
2) Has specific impacts on the conversion to verilog

### Inclusion of Don't Cares and High Impedances

They are in here, but at present, are dumb. They only exist to aid in simulation.
They can't be used to certifiably debug code, but their inclusion may help you catch some architecture problems. You should check parity with the testbench for complete debugging.

```julia
julia> A = Wire()[0]
julia> A := 'x'
julia> A := 'z'
```

### Driving the same wire by multiple logic calls

Is possible, will fuck up your shit.
Don't assign to the same bits more than once.
I am in the process of checking for this. But it isn't certain yet.

CONVERSION TO VERILOG
---

Occurs after the parameterization and sanitization steps of preprocessing.

The @async macro does three things:
1) @async macro calls are directly converted into always @* function calls in verilog
2) Any wire assigned within an @async macro will be converted to a reg
3) Any if-else statements inside of and @async will remain an if-else statement inside an always block, whereas if-elses outside @async will be turned into ? : calls

The reason it might be desirable to use or not use @async macros is due to the intended hardware.

+ FPGA compilation tends to improve with explicit ? : Mux calls, due to the poor quality of FPGA compilation software. Therefore, the @async macro may not be desired

+ ASIC compilation is done in Design Compiler, where the existence of always blocks versus ? : Mux calls is fairly insubstantial.

+ The @async macro can be also used as a style choice

CURRENT RELEASE
---

### Noticable Absences from the 0.1 release

+ Julia Simulation only works on 64 bit machines, with the 64 bit installation of Julia. Preprocessing, and conversion to Verilog does not carry this constraint
+ Absence of smart +, -, *, /, remainder
+ Matrix or Bus notation
+ Working ifs, registers of any kind

NEXT UPDATE FUNCTIONALITY
---

+ Tuples and vcats on left hand side of equations

+ Julia Matrix Notation and Verilog Bus Notation

+ Supports writing values to ints, as opposed to vcat with 0s and 1s

+ nonblocking operator <= is less than equal operator in Julia, consider changing

+ if statements support differing left hand side assignments. At present, the lhs side of any statement in an if block has a dumb way of matching.

POTENTIAL FEATURES
---

+ Polymorphic Julia code (Write Once)

+ Combinational Reductions:

  Trace a path of operations e.g. [& & | + - ^] from input to reg, reg to reg, reg to output have a list of combinational reduction equivalences

+ Flatten function:

  Removes any hierarchy from function, unrolls everything into top level

+ Lossless bitlength decisions, Lossy bit length decisions

  Intelligent and Power-saving bitlength decisions. Wires of indeterminate bitlength act as indicators for programming.

+ Instances of algorithmic equivalences

  For a defined set of functions and a finite input set, algorithmic equivalence can be defined. A defined set of equivalent functions can be extrapolated to solve for equivalent algorithm for a defined algorithm.

+ Generalized Hardware Programmability

  Given a "program" to map to hardware, and a complete description of the programmable hardware, a generalized program can be written which tells you: One, if the program can be successfully mapped to the programmable hardware, and two, a generalized--if potentially very inefficient--means to map the program onto the hardware.

+ Reversible logic so simulation can be played forward/backwards
+ Visual graph which shows i.r.t what wire values are

+ CPU emulation running alongside Hardware simulation
+ Multithreaded Simulation
+ Vulkan-accelerated Simulation

+ Synthesis
+ Vulkan-accelerated Synthesis
+ SPICE integration
+ Stochastic delay modelling
+ Easy Monte-Carlo simulations

TEST BENCH CONSTRUCTION
---

W.I.P.


text:
struct fake;

struct pointerele
{
	void * ptr;
	char * type;
	uint32_t typesz;
};

class pointerheap
{
public:
	pointerheap(fake * fk);
	~pointerheap();

	void clear();

	pointerele * allocpointer(void * ptr, const char * type);

	void checkgc(bool force);

	const char * dump();

	force_inline size_t size() const
	{
		return m_shh.size();
	}

private:
	void gc();

private:
	fake * m_fk;
	fkhashmap<void *, pointerele> m_shh;
	String m_dumpstr;
    array<pointerele *> m_todelete;
    size_t m_last_gc_size;
};


text:
import py
from rpython.jit.metainterp.test.test_virtualizable import ImplicitVirtualizableTests
from rpython.jit.backend.ppc.test.support import JitPPCMixin

class TestVirtualizable(JitPPCMixin, ImplicitVirtualizableTests):
    def test_blackhole_should_not_reenter(self):
        py.test.skip("Assertion error & llinterp mess")


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>io.rhiot</groupId>
        <version>0.1.3-SNAPSHOT</version>
        <artifactId>rhiot-bom</artifactId>
        <relativePath>../bom</relativePath>
    </parent>
    <name>Rhiot :: Tooling</name>
    <artifactId>rhiot-tooling</artifactId>
    <packaging>pom</packaging>

    <licenses>
        <license>
            <name>The Apache License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
        </license>
    </licenses>

    <modules>
        <module>shell</module>
        <module>cmd-core</module>
        <module>cmd</module>
    </modules>

</project>


text:
// This file was generated using Parlex's cpp_generator

#include "ASM_EXPRESSION.hpp"

#include "plange_grammar.hpp"

#include "parlex/detail/document.hpp"
#include "ASM_IDENTIFIER.hpp"
#include "ASM_PTR_ARITHMETIC_ATT.hpp"
#include "ASM_PTR_ARITHMETIC_INTEL.hpp"
#include "NON_FRACTIONAL.hpp"

#include "ASM_EXPRESSION.hpp"

namespace plc {

ASM_EXPRESSION ASM_EXPRESSION::build(parlex::detail::ast_node const & n) {
	static auto const * b = state_machine().behavior;
	parlex::detail::document::walk w{ n.children.cbegin(), n.children.cend() };
	return ASM_EXPRESSION(parlex::detail::document::element<ASM_EXPRESSION_base>::build(b, w));
}

} // namespace plc

parlex::detail::state_machine const & plc::ASM_EXPRESSION::state_machine() {
	static auto const & result = *static_cast<parlex::detail::state_machine const *>(&plange_grammar::get().get_recognizer(plange_grammar::get().ASM_EXPRESSION));
	return result;
}


text:
""" Provides access to the /r/thebutton button.
Uses a websocket.WebSocketApp to update the time, total clicks and other relevant data

Based on https://github.com/mfontanini/thebutton
Part of https://github.com/ALPSquid/thebutton-monitor
"""

import websocket
import threading
import re
import urllib.request
import json
import time
import math

class Keys():
    """ Dictionary keys used by /r/thebutton websocket response
    Sample: {"type": "ticking", "payload": {"participants_text": "756,790", "tick_mac": "fca61e446b32ba0c2851d564b413d7c953e92690", "seconds_left": 36.0, "now_str": "2015-04-16-11-33-26"}}
    """
    PAYLOAD = "payload"
    SECONDS = "seconds_left"
    PARTICIPANTS = "participants_text"
    TIME = "now_str"
    MAC = "tick_mac"

class TheButton():
    """ Represents the /r/thebutton button.
    Uses a websocket.WebSocketApp to update the time, total clicks and other relevant data
    """
    ws_re = re.compile('(wss://wss.redditmedia.com/thebutton\?h=[0-9a-f]*&e=[0-9a-f]*)')

    @staticmethod
    def _get_websocket_url():
        """ Get the websocket url from the /r/thebutton source
        :return: websocket url
        """
        req = urllib.request.urlopen("https://www.reddit.com/r/thebutton")
        contents = req.read().decode("utf-8")

        matches = TheButton.ws_re.findall(contents)
        if any(matches):
            return matches[0]
        else:
            raise Exception("Failed to find websocket url")

    def __init__(self):
        self.ws_url = self._get_websocket_url()
        self.wsa = websocket.WebSocketApp(self.ws_url, header=["User-Agent: /r/thebutton python API"],
                                          on_message=self.on_message, on_error=self.on_error)
        self._wsa_proc = None  # WSA run_forever thread

        self.base_time = 60.0  # Current button time (no milliseconds, use current_time for time with millis)
        self.last_time = self.base_time  # Button time prior to each update. Used to determine if a new record was set
        self.lowest_time = 60.0  # Lowest button time this session (no milliseconds)
        self.participants = 0  # Number of button clicks
        self.last_timestamp = ""  # Last update from server
        self._last_tick = time.perf_counter()  # Used by current_time to calculate milliseconds

    @property
    def current_time(self):
        """
        The Reddit websocket sends updated information every second (on each button time change).
        The current time since the last message is used to calculate the current milliseconds.

        :return: Current button time with milliseconds
        """
        time_diff = time.perf_counter() - self._last_tick  # Time since last update
        return self.base_time - (math.ceil((1 - time_diff) * 100) / 100.0)

    @property
    def colour(self):
        """
        :return: Flair colour for current button time
        """
        if self.base_time < 12: return 'e50000'  # red
        if self.base_time < 22: return 'e59500'  # orange
        if self.base_time < 32: return 'e5d900'  # yellow
        if self.base_time < 42: return '02be01'  # green
        if self.base_time < 52: return '0083c7'  # blue
        return '820080'  # purple

    @property
    def hue_colour(self):
        """ Colors configured for Hue Bulb
        :return: Hue flair colour for current button time
        """
        if self.base_time < 12: return [0.65, 0.3]  # red
        if self.base_time < 22: return [0.6, 0.4]  # orange
        if self.base_time < 32: return [0.5, 0.5]  # yellow
        if self.base_time < 42: return [0.2, 0.7]  # green
        if self.base_time < 52: return [0.17, 0.04]  # blue
        return [0.3, 0.1]  # purple

    @property
    def limitless_colour(self):
        """ Colors configured for Limitless LED RGBW Bulns
        :return: Colour for current button time
        """
        if self.base_time < 12: return 'red'  # red
        if self.base_time < 22: return 'orange'  # orange
        if self.base_time < 32: return 'yellow'  # yellow
        if self.base_time < 42: return 'green'  # green
        if self.base_time < 52: return 'royal_blue'  # blue
        return 'lilac'  # purple

    @property
    def simple_colour(self):
        """ Colours configured for certain lights that work best with simple, bright colours, like the PlayBulb Candle
        :return: Flair colour for current button time.
        """
        if self.base_time < 12: return 'ff0000'  # red
        if self.base_time < 22: return 'ff0f00'  # orange
        if self.base_time < 32: return 'ff7700'  # yellow
        if self.base_time < 42: return '00ff00'  # green
        if self.base_time < 52: return '00f0ff'  # blue
        return 'ff00f0'  # purple

    @property
    def ascii_colour(self):
        """ Returns ASCII codes indicating the color rather than actual values.
        For use with devices listening on a serial interface, like an arduino.
        """
        if self.base_time < 12: return 'R'  # red
        if self.base_time < 22: return 'O'  # orange
        if self.base_time < 32: return 'Y'  # yellow
        if self.base_time < 42: return 'G'  # green
        if self.base_time < 52: return 'B'  # blue
        return 'P'  # purple

    def on_message(self, wsa, message):
        """ WebSocketApp message callback
        Update button attributes: base_time, lowest_time, participants, last_timestamp

        :param wsa: WebSocketApp instance
        :param message: message from socket
        """
        payload = json.loads(message)[Keys.PAYLOAD]
        # Update button time
        self.last_time = self.base_time
        self.base_time = payload[Keys.SECONDS]
        if self.base_time == 60.0 and self.last_time < self.lowest_time:
            self.lowest_time = self.last_time

        # Update participants
        participants = payload[Keys.PARTICIPANTS]
        if self.participants != participants:
            self.participants = participants

        # Update timestamp
        self.last_timestamp = payload[Keys.TIME]

        # Used to calculate button milliseconds
        self._last_tick = time.perf_counter()

    def on_error(self, wsa, error):
        """ WebSocketApp error callback
        Print the error message

        :param wsa: WebSocketApp instance
        :param error: error message
        """
        print(error)

    def start(self):
        """ Start the WebSocketApp """
        self._wsa_proc = threading.Thread(target=self.wsa.run_forever)
        self._wsa_proc.start()

    def close(self):
        """ Stop the WebSocketApp """
        self.wsa.close()
        self._wsa_proc.join()
        print("Disconnected from The Button")


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/aop
	 http://www.springframework.org/schema/aop/spring-aop.xsd
	 http://www.springframework.org/schema/tx
	 http://www.springframework.org/schema/tx/spring-tx.xsd
     http://www.springframework.org/schema/data/jpa
     http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

	<jpa:repositories base-package="com.dpz.learn.archetype.dao" />
	<!--事务管理 -->
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>

	<aop:config>
		<aop:pointcut id="daoMethods"
			expression="execution(* com.dpz.learn.archetype.manager..*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="daoMethods" />
	</aop:config>

	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="modify*" propagation="REQUIRED" />
			<tx:method name="batch*" propagation="REQUIRED" />
			<tx:method name="get*" read-only="true" />
			<tx:method name="query*" read-only="true" />
		</tx:attributes>
	</tx:advice>

	<!-- 配置dbcp数据源 -->
	<bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url"
			value="jdbc:mysql://${db}?useUnicode=true&characterEncoding=UTF-8" />
		<property name="username" value="${db.username}" />
		<property name="password" value="${db.password}" />

		<property name="testOnBorrow" value="true" />
		<property name="testOnReturn" value="true" />
		<property name="testWhileIdle" value="true" />
		<property name="validationQuery" value="SELECT NOW() FROM DUAL" />
		<property name="maxIdle" value="30" />
		<property name="maxActive" value="50" />

	</bean>

	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="dataSource" ref="datasource" />
		<property name="persistenceXmlLocation" value="classpath:/persistence.xml" />
		<property name="persistenceProviderClass" value="org.hibernate.ejb.HibernatePersistence" />
		<property name="persistenceUnitName" value="com.dpz.learn.archetype" />
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
		</property>
	</bean>

</beans>


text:
package com.khartec.waltz.model;

public interface EntityKindProvider {

    EntityKind kind();
}


text:
#include "config.h"
#include "AccessibilityScrollbar.h"

#include "AXObjectCache.h"
#include "FrameView.h"
#include "ScrollView.h"
#include "Scrollbar.h"

namespace WebCore {

AccessibilityScrollbar::AccessibilityScrollbar(Scrollbar* scrollbar)
    : m_scrollbar(scrollbar)
{
    ASSERT(scrollbar);
}

Ref<AccessibilityScrollbar> AccessibilityScrollbar::create(Scrollbar* scrollbar)
{
    return adoptRef(*new AccessibilityScrollbar(scrollbar));
}

LayoutRect AccessibilityScrollbar::elementRect() const
{
    if (!m_scrollbar)
        return LayoutRect();

    return m_scrollbar->frameRect();
}

Document* AccessibilityScrollbar::document() const
{
    AccessibilityObject* parent = parentObject();
    if (!parent)
        return nullptr;
    return parent->document();
}

AccessibilityOrientation AccessibilityScrollbar::orientation() const
{
    // ARIA 1.1 Elements with the role scrollbar have an implicit aria-orientation value of vertical.
    if (!m_scrollbar)
        return AccessibilityOrientationVertical;

    if (m_scrollbar->orientation() == HorizontalScrollbar)
        return AccessibilityOrientationHorizontal;
    if (m_scrollbar->orientation() == VerticalScrollbar)
        return AccessibilityOrientationVertical;

    return AccessibilityOrientationVertical;
}

bool AccessibilityScrollbar::isEnabled() const
{
    if (!m_scrollbar)
        return false;
    return m_scrollbar->enabled();
}

float AccessibilityScrollbar::valueForRange() const
{
    if (!m_scrollbar)
        return 0;

    return m_scrollbar->currentPos() / m_scrollbar->maximum();
}

void AccessibilityScrollbar::setValue(float value)
{
    if (!m_scrollbar)
        return;

    float newValue = value * m_scrollbar->maximum();
    m_scrollbar->scrollableArea().scrollToOffsetWithoutAnimation(m_scrollbar->orientation(), newValue);
}

} // namespace WebCore


text:
import fileActions from './fileActions';

describe('redux/actions/fileActions', () => {
  describe('subscribeDirectories', () => {
    it(
      'calls fileRepo.subscribeDirectories and then dispatch with a type @@FIREBASE/update/directories and the directories from the response',
      done => {
        const fileRepo = {
          subscribeDirectories: jest.fn(cb => cb({
            dir: 'some-dir'
          }))
        };
        const dispatch = jest.fn(() => {
          expect(dispatch).toHaveBeenCalledWith({
            type: '@@FIREBASE/update/directories',
            payload: {
              directories: {
                dir: 'some-dir'
              }
            }
          });
          done();
        });
        fileActions({ fileRepo }).subscribeDirectories()(dispatch);
      }
    );
  });

  describe('addDirectory', () => {
    it('calls fileRepo.addDirectory with the name', () => {
      const fileRepo = {
        addDirectory: jest.fn()
      };
      fileActions({ fileRepo }).addDirectory('some-name')();
      expect(fileRepo.addDirectory).toHaveBeenCalledWith({ name: 'some-name' });
    });
  });

  describe('uploadFiles', () => {
    it('calls fileRepo.addFile for every file', () => {
      const mockDispatch = jest.fn();
      const mockOn = jest.fn();
      const fileRepo = {
        addFile: jest.fn(() => ({ on: mockOn }))
      };
      fileActions({ fileRepo }).uploadFiles('some-dir', [
        {
          name: 'file-name'
        },
        {
          name: 'another-file-name'
        }
      ])(mockDispatch);
      expect(fileRepo.addFile).toHaveBeenCalledWith({
        parentDir: 'some-dir',
        file: {
          name: 'file-name'
        },
        fileIndex: 0
      });
      expect(fileRepo.addFile).toHaveBeenCalledWith({
        parentDir: 'some-dir',
        file: {
          name: 'another-file-name'
        },
        fileIndex: 1
      });
    });

    it('calls dispatch with start', () => {
      const mockDispatch = jest.fn();
      const mockOn = jest.fn();
      const fileRepo = {
        addFile: jest.fn(() => ({ on: mockOn }))
      };
      fileActions({ fileRepo }).uploadFiles('some-dir', [
        {
          name: 'file-name'
        },
        {
          name: 'another-file-name'
        }
      ])(mockDispatch);
      expect(mockDispatch).toHaveBeenCalledWith({
        type: '@@FIREBASE/upload/start',
        payload: {
          files: [
            {
              name: 'file-name'
            },
            {
              name: 'another-file-name'
            }
          ]
        }
      });
    });

    it('calls dispatch with progress', done => {
      const mockDispatch = jest.fn();
      const mockOn = jest.fn((str, cb) => {
        cb({
          bytesTransferred: 20,
          totalBytes: 100,
          metadata: 'file-metadata'
        });
        expect(mockDispatch).toHaveBeenCalledWith({
          type: '@@FIREBASE/upload/progress',
          payload: {
            progress: 20,
            file: 'file-metadata'
          }
        });
        done();
      });
      const fileRepo = {
        addFile: jest.fn(() => ({ on: mockOn }))
      };
      fileActions({ fileRepo }).uploadFiles('some-dir', [
        {
          name: 'file-name'
        },
        {
          name: 'another-file-name'
        }
      ])(mockDispatch);
    });

    it('calls dispatch with done', done => {
      const mockDispatch = jest.fn();
      const mockOn = jest.fn((str, cb) => {
        cb({
          bytesTransferred: 100,
          totalBytes: 100,
          metadata: 'file-metadata'
        });
        expect(mockDispatch).toHaveBeenCalledWith({
          type: '@@FIREBASE/upload/done',
          payload: {
            progress: 100,
            file: 'file-metadata'
          }
        });
        done();
      });
      const fileRepo = {
        addFile: jest.fn(() => ({ on: mockOn }))
      };
      fileActions({ fileRepo }).uploadFiles('some-dir', [
        {
          name: 'file-name'
        },
        {
          name: 'another-file-name'
        }
      ])(mockDispatch);
    });
  });
});


text:
[![npm version](https://img.shields.io/npm/v/gulp-dotenv.svg)](https://www.npmjs.com/package/gulp-dotenv)
[![Build Status](https://travis-ci.org/pine/gulp-dotenv.svg?branch=master)](https://travis-ci.org/pine/gulp-dotenv)
[![Dependency Status](https://img.shields.io/david/pine/gulp-dotenv.svg)](https://david-dm.org/pine/gulp-dotenv)
[![devDependency Status](https://img.shields.io/david/dev/pine/gulp-dotenv.svg)](https://david-dm.org/pine/gulp-dotenv#info=devDependencies)

A .env file plugin for gulp:  compiling .env to JSON

## Installation

```
$ npm install gulp-dotenv --save
```

## Usage
`.env` is a `\n` separated key-value configuration file like `KEY=VALUE`.

```js
var dotenv = require('gulp-dotenv');
var rename = require('gulp-rename');

gulp.task('dotenv', function () {
  return gulp.src('.env')
    .pipe(dotenv())
    .pipe(rename('env.json'))
    .pipe(gulp.dest('dist'));
});
```

## License
MIT © Pine Mizune


text:
from __future__ import division, print_function

__all__ = ["HDFBackend", "TempHDFBackend"]

import os
from tempfile import NamedTemporaryFile

import numpy as np

from .. import __version__
from .backend import Backend

try:
    import h5py
except ImportError:
    h5py = None

class HDFBackend(Backend):
    """A backend that stores the chain in an HDF5 file using h5py

    .. note:: You must install `h5py <http://www.h5py.org/>`_ to use this
        backend.

    Args:
        filename (str): The name of the HDF5 file where the chain will be
            saved.
        name (str; optional): The name of the group where the chain will
            be saved.
        read_only (bool; optional): If ``True``, the backend will throw a
            ``RuntimeError`` if the file is opened with write access.

    """
    def __init__(self, filename, name="mcmc", read_only=False, dtype=None):
        if h5py is None:
            raise ImportError("you must install 'h5py' to use the HDFBackend")
        self.filename = filename
        self.name = name
        self.read_only = read_only
        if dtype is None:
            self.dtype_set = False
            self.dtype = np.float64
        else:
            self.dtype_set = True
            self.dtype = dtype

    @property
    def initialized(self):
        if not os.path.exists(self.filename):
            return False
        try:
            with self.open() as f:
                return self.name in f
        except (OSError, IOError):
            return False

    def open(self, mode="r"):
        if self.read_only and mode != "r":
            raise RuntimeError(
                "The backend has been loaded in read-only "
                "mode. Set `read_only = False` to make "
                "changes."
            )
        f = h5py.File(self.filename, mode)
        if not self.dtype_set and self.name in f:
            g = f[self.name]
            if "chain" in g:
                self.dtype = g["chain"].dtype
                self.dtype_set = True
        return f

    def reset(self, nwalkers, ndim):
        """Clear the state of the chain and empty the backend

        Args:
            nwakers (int): The size of the ensemble
            ndim (int): The number of dimensions

        """
        with self.open("a") as f:
            if self.name in f:
                del f[self.name]

            g = f.create_group(self.name)
            g.attrs["version"] = __version__
            g.attrs["nwalkers"] = nwalkers
            g.attrs["ndim"] = ndim
            g.attrs["has_blobs"] = False
            g.attrs["iteration"] = 0
            g.create_dataset("accepted", data=np.zeros(nwalkers))
            g.create_dataset(
                "chain",
                (0, nwalkers, ndim),
                maxshape=(None, nwalkers, ndim),
                dtype=self.dtype,
            )
            g.create_dataset(
                "log_prob",
                (0, nwalkers),
                maxshape=(None, nwalkers),
                dtype=self.dtype,
            )

    def has_blobs(self):
        with self.open() as f:
            return f[self.name].attrs["has_blobs"]

    def get_value(self, name, flat=False, thin=1, discard=0):
        if not self.initialized:
            raise AttributeError(
                "You must run the sampler with "
                "'store == True' before accessing the "
                "results"
            )
        with self.open() as f:
            g = f[self.name]
            iteration = g.attrs["iteration"]
            if iteration <= 0:
                raise AttributeError(
                    "You must run the sampler with "
                    "'store == True' before accessing the "
                    "results"
                )

            if name == "blobs" and not g.attrs["has_blobs"]:
                return None

            v = g[name][discard + thin - 1 : self.iteration : thin]
            if flat:
                s = list(v.shape[1:])
                s[0] = np.prod(v.shape[:2])
                return v.reshape(s)
            return v

    @property
    def shape(self):
        with self.open() as f:
            g = f[self.name]
            return g.attrs["nwalkers"], g.attrs["ndim"]

    @property
    def iteration(self):
        with self.open() as f:
            return f[self.name].attrs["iteration"]

    @property
    def accepted(self):
        with self.open() as f:
            return f[self.name]["accepted"][...]

    @property
    def random_state(self):
        with self.open() as f:
            elements = [
                v
                for k, v in sorted(f[self.name].attrs.items())
                if k.startswith("random_state_")
            ]
        return elements if len(elements) else None

    def grow(self, ngrow, blobs):
        """Expand the storage space by some number of samples

        Args:
            ngrow (int): The number of steps to grow the chain.
            blobs: The current list of blobs. This is used to compute the
                dtype for the blobs array.

        """
        self._check_blobs(blobs)

        with self.open("a") as f:
            g = f[self.name]
            ntot = g.attrs["iteration"] + ngrow
            g["chain"].resize(ntot, axis=0)
            g["log_prob"].resize(ntot, axis=0)
            if blobs is not None:
                has_blobs = g.attrs["has_blobs"]
                if not has_blobs:
                    nwalkers = g.attrs["nwalkers"]
                    dt = np.dtype((blobs[0].dtype, blobs[0].shape))
                    g.create_dataset(
                        "blobs",
                        (ntot, nwalkers),
                        maxshape=(None, nwalkers),
                        dtype=dt,
                    )
                else:
                    g["blobs"].resize(ntot, axis=0)
                g.attrs["has_blobs"] = True

    def save_step(self, state, accepted):
        """Save a step to the backend

        Args:
            state (State): The :class:`State` of the ensemble.
            accepted (ndarray): An array of boolean flags indicating whether
                or not the proposal for each walker was accepted.

        """
        self._check(state, accepted)

        with self.open("a") as f:
            g = f[self.name]
            iteration = g.attrs["iteration"]

            g["chain"][iteration, :, :] = state.coords
            g["log_prob"][iteration, :] = state.log_prob
            if state.blobs is not None:
                g["blobs"][iteration, :] = state.blobs
            g["accepted"][:] += accepted

            for i, v in enumerate(state.random_state):
                g.attrs["random_state_{0}".format(i)] = v

            g.attrs["iteration"] = iteration + 1

class TempHDFBackend(object):

    def __init__(self, dtype=None):
        self.dtype = dtype
        self.filename = None

    def __enter__(self):
        f = NamedTemporaryFile(prefix="emcee-temporary-hdf5",
                               suffix=".hdf5",
                               delete=False)
        f.close()
        self.filename = f.name
        return HDFBackend(f.name, "test", dtype=self.dtype)

    def __exit__(self, exception_type, exception_value, traceback):
        os.remove(self.filename)


text:
import { Component } from '@stencil/core';

@Component({
  tag: 'footer-bar',
  styleUrl: 'footer-bar.scss'
})
export class FooterBar {
  render() {
    return(

              Released under MIT License | Copyright @ {(new Date()).getFullYear()}

            Cheatsheet
            v1
            v2
            v3
            Ionic Framework

    );
  }
}


text:
using UnrealBuildTool;
using System.Collections.Generic;

public class OSVRUnrealEditorTarget : TargetRules
{
	public OSVRUnrealEditorTarget(TargetInfo Target) : base(Target)
	{
		Type = TargetType.Editor;

		ExtraModuleNames.AddRange( new string[] { "OSVRUnreal" } );
	}
}


text:
package org.modelmapper.bugs;

import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;

import org.modelmapper.AbstractTest;
import org.testng.annotations.Test;

/**
 * https://github.com/jhalterman/modelmapper/issues/6
 *
 * @author Jonathan Halterman
 */
@Test
public class GH6 extends AbstractTest {
  public static class Source {
    SourceMessage message;

    public SourceMessage getMessage() {
      return message;
    }

    public void setMessage(SourceMessage message) {
      this.message = message;
    }
  }

  public static class SourceMessage {
    SourceMessageBody body;

    public SourceMessageBody getBody() {
      return body;
    }

    public void setBody(SourceMessageBody body) {
      this.body = body;
    }
  }

  public static class SourceMessageBody {
    String value;

    public String getValue() {
      return value;
    }

    public void setValue(String value) {
      this.value = value;
    }
  }

  public static class Dest {
    DestMessage message;

    public DestMessage getMessage() {
      return message;
    }

    public void setMessage(DestMessage message) {
      this.message = message;
    }
  }

  public static class DestMessage {
    DestMessageBody body;

    public DestMessageBody getBody() {
      return body;
    }

    public void setBody(DestMessageBody body) {
      this.body = body;
    }
  }

  public static class DestMessageBody {
    String value = "originalValue";

    public String getValue() {
      return value;
    }

    public void setValue(String value) {
      this.value = value;
    }
  }

  public void shouldInstantiateIntermediateObjects() {
    Dest dest = modelMapper.map(new Source(), Dest.class);
    assertNull(dest.message);

    Source source = new Source();
    source.message = new SourceMessage();
    dest = modelMapper.map(source, Dest.class);
    assertNotNull(dest.message);
  }

  public void shouldNotInstantiateIntermediateObjectOnProvidedDestination() {
    Source source = new Source();
    Dest dest = new Dest();
    dest.message = new DestMessage();
    modelMapper.map(source, dest);
    assertNull(dest.message.body);

    source.message = new SourceMessage();
    modelMapper.map(source, dest);
    assertNull(dest.message.body);
  }

  public void shouldIgnoreIntermediateDestinationWhenSourceIsNotNull() {
    Source source = new Source();
    source.message = new SourceMessage();
    Dest dest = new Dest();
    dest.message = new DestMessage();
    modelMapper.map(source, dest);
    assertNotNull(dest.message);

    source.message.body = new SourceMessageBody();
    dest.message.body = new DestMessageBody();
    modelMapper.map(source, dest);
    assertNotNull(dest.message.body);
  }

  /**
   * Cannot support this for now due to potentially asymmetric mappings. We don't know for sure that
   * source.message maps to dest.message and therefore can't null dest.message just because
   * source.message is null.
   *
   * TODO enable once better information is captured for asymmetric mappings
   */
  @Test(enabled = false)
  public void shouldNullifyIntermediateDestinationWhenSourceIsNull() {
    Source source = new Source();
    Dest dest = new Dest();
    dest.message = new DestMessage();
    modelMapper.map(source, dest);
    assertNull(dest.message);

    source.message = new SourceMessage();
    dest.message = new DestMessage();
    dest.message.body = new DestMessageBody();
    modelMapper.map(source, dest);
    assertNull(dest.message.body);
  }
}


text:
import _plotly_utils.basevalidators

class TextsrcValidator(_plotly_utils.basevalidators.SrcValidator):
    def __init__(self, plotly_name="textsrc", parent_name="heatmap", **kwargs):
        super(TextsrcValidator, self).__init__(
            plotly_name=plotly_name,
            parent_name=parent_name,
            edit_type=kwargs.pop("edit_type", "none"),
            **kwargs,
        )


text:
package main

import (
	"encoding/xml"
	"io/ioutil"
	"log"
	"net/http"
	"path/filepath"
	"regexp"
	"sync"
)

type svnRoot struct {
	Index svnIndex `xml:"index"`
}

type svnIndex struct {
	Revision string     `xml:"rev,attr"`
	Entries  []svnEntry `xml:"file"`
}

type svnEntry struct {
	Name string `xml:"href,attr"`
}

const maxRequests = 10

// DownloadSvnDir reads an SVN XML directory index and downloads all the listed (filtered) files. It
// returns the SVN revision at which the files were downloaded.
func DownloadSvnDir(svnDirURL string, filter *regexp.Regexp, outDir string) (string, error) {
	response, err := http.Get(svnDirURL)
	if err != nil {
		return "", err
	}
	defer response.Body.Close()

	var root svnRoot
	if err := xml.NewDecoder(response.Body).Decode(&root); err != nil {
		return "", err
	}
	index := root.Index

	var downloadErr error

	wg := new(sync.WaitGroup)
	c := make(chan int, maxRequests)
	for _, e := range index.Entries {
		if filter.MatchString(e.Name) {
			c <- 1
			wg.Add(1)
			url := svnDirURL + "/" + e.Name
			file := filepath.Join(outDir, e.Name)
			go func(url, file string) {
				defer wg.Done()
				if err := downloadFile(url, file); err != nil && downloadErr == nil {
					downloadErr = err
				}
				<-c
			}(url, file)
		}
	}
	wg.Wait()

	return index.Revision, downloadErr
}

func downloadFile(url, file string) error {
	log.Println("Downloading", url)

	response, err := http.Get(url)
	if err != nil {
		return err
	}
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return err
	}

	err = ioutil.WriteFile(file, body, 0644)
	if err != nil {
		return err
	}

	return nil
}


text:
package com.redhat.samples.switchyard;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.switchyard.Context;
import org.switchyard.component.resteasy.composer.RESTEasyBindingData;
import org.switchyard.component.resteasy.composer.RESTEasyContextMapper;

public class CorsRESTEasyContextMapper extends RESTEasyContextMapper {

    @Override
    public void mapTo(Context context, RESTEasyBindingData target) throws Exception {
        super.mapTo(context, target);
        Map<String, List<String>> httpHeaders = target.getHeaders();
        httpHeaders.put("Access-Control-Allow-Origin", Arrays.asList("http://localhost:18080"));
    }

}


text:
namespace BusTickets.Data.Config
{
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Metadata.Builders;
    using BusTickets.Models;

    public class CountryConfig : IEntityTypeConfiguration<Country>
    {
        public void Configure(EntityTypeBuilder<Country> builder)
        {
            builder.HasKey(e => e.Id);

            builder.Property(e => e.Name)
                .IsRequired(true)
                .IsUnicode(true)
                .HasMaxLength(30);
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
		"http://www.w3.org/TR/html4/strict.dtd">

	<title>dijit.form.TextBox size tests</title>

dijit.form.TextBox size tests

			TextBox

			<input dojoType="dijit.form.TextBox" type="text" id="textbox" value="text">

			NumberTextBox

			<input dojoType="dijit.form.NumberTextBox" type="text" id="validation" value="54" required="true">

			FilteringSelect

			<select dojoType="dijit.form.FilteringSelect" id="combobox" required="true">
				<option value="KY">Kentucky</option>
			</select>

			NumberSpinner

			INPUT type=file

			<input dojoType="dijit.form.TextBox" type="file" id="file">

Font family:
	<select dojoType="dijit.form.ComboBox" id="fontFamily" style="font-size:14pt;" value="">

		<option>monospace</option>
		<option selected>Courier</option>
		<option>Helvetica</option>
		<option>Times</option>
		<option>system,fixed</option>
	</select>

Font size:
	<select dojoType="dijit.form.ComboBox" id="fontSize" style="font-size:14pt;" value="">

		<option>small</option>
		<option>medium</option>
		<option>xx-large</option>
		<option>8pt</option>
		<option>21px</option>
		<option>1cm</option>
		<option>1em</option>
		<option>200%</option>
	</select>

Padding:
	<select dojoType="dijit.form.FilteringSelect" id="padding" style="font-size:14pt;" required="false" value="">

		<option value="default">default</option>
		<option value="padded">padded</option>
		<option value="unPadded">unPadded</option>
	</select>

Direction:
	<select dojoType="dijit.form.FilteringSelect" id="direction" style="font-size:14pt;" required="false" value="">

		<option value="ltr">left-to-right</option>
		<option value="rtl">right-to-left</option>
	</select>

Theme:
	<select dojoType="dijit.form.FilteringSelect" id="theme" style="font-size:14pt;" required="false" value="">

		<option value="tundra">tundra</option>
		<option value="soria">soria</option>
		<option value="nihilo">nihilo</option>
		<option value="claro">claro</option>
		<option value="a11y">a11y</option>
	</select>

	<button dojoType="dijit.form.Button" onclick="doh.run()">Run tests</button>


text:
package org.wordcounthbase;

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

public class PdfMapper extends Mapper<LongWritable, Text, Text, LongWritable> {
    private Text word = new Text();
    private final static LongWritable one = new LongWritable(1);

    @Override
    protected void map(LongWritable key, Text value, Context context)
            throws IOException, InterruptedException {

        String line = value.toString().replaceAll("\\.", " ")
                .replaceAll("(?!\")\\p{Punct}", "").replaceAll("\"", "")
                .replaceAll("[0-9]*", "").toLowerCase();
        StringTokenizer tokenizer = new StringTokenizer(line);

        while (tokenizer.hasMoreTokens()) {
            word.set(tokenizer.nextToken());
            context.progress();
            context.write(word, one);
        }
    }
}


text:
<scientilla-backend-layout>

Suggested documents

    <scientilla-filter
        prefix="sg"
        category="suggested-document"
        on-filter="vm.onFilter"
        elements="vm.documents">

        <scientilla-multicheck>
            <buttons>
                <scientilla-multicheck-button
                    subject="Verify document"
                    on-click="vm.verifyDocuments">
                    Verify
                </scientilla-multicheck-button>
                <scientilla-multicheck-button
                    subject="Copy document"
                    on-click="vm.copyDocuments">
                    Copy
                </scientilla-multicheck-button>
                <scientilla-multicheck-button
                    subject="Discard document"
                    on-click="vm.discardDocuments">
                    Discard
                </scientilla-multicheck-button>
            </buttons>
            <item-list>
                <scientilla-checkable
                    ng-repeat="document in vm.documents"
                    item="document"
                    class="scientilla-checkable">

                    <scientilla-document
                        document="document"
                        section="vm.documentListSections.SUGGESTED"
                        class="document-container"></scientilla-document>

                            <button
                                ng-disabled="!document.isValid()"
                                ng-click="vm.verifyDocument(document)"
                                type="button"
                                class="btn btn-primary"
                                ng-if="!document.isComparable">
                                Verify
                            </button>

                            <button
                                ng-click="vm.compareDocuments(document, document.getComparisonDuplicates(), vm.documentCategories.SUGGESTED)"
                                ng-disabled="!document.isValid()"
                                type="button"
                                ng-if="document.isComparable"
                                class="btn btn-warning">
                                Compare
                            </button>

                            <button
                                type="button"
                                class="btn dropdown-toggle only-icon"
                                ng-class="{'btn-warning': document.isComparable, 'btn-primary': !document.isComparable}"
                                uib-dropdown-toggle>
                            </button>

                                    Copy to drafts

                                    Discard

                </scientilla-checkable>
            </item-list>
        </scientilla-multicheck>

    </scientilla-filter>
</scientilla-backend-layout>