text:
namespace chrono {
namespace vehicle {

ChTrackAssembly::ChTrackAssembly(const std::string& name, VehicleSide side)
    : ChPart(name),
      m_side(side),
      m_idler_as_cylinder(true),
      m_roller_as_cylinder(true),
      m_roadwheel_as_cylinder(true) {}

// -----------------------------------------------------------------------------
// Get the complete state for the specified track shoe.
// -----------------------------------------------------------------------------
BodyState ChTrackAssembly::GetTrackShoeState(size_t id) const {
    BodyState state;

    state.pos = GetTrackShoePos(id);
    state.rot = GetTrackShoeRot(id);
    state.lin_vel = GetTrackShoeLinVel(id);
    state.ang_vel = GetTrackShoeAngVel(id);

    return state;
}

// -----------------------------------------------------------------------------
// Get the complete states for all track shoes.
// -----------------------------------------------------------------------------
void ChTrackAssembly::GetTrackShoeStates(BodyStates& states) const {
    size_t num_shoes = GetNumTrackShoes();
    assert(states.size() == num_shoes);

    for (size_t i = 0; i < num_shoes; ++i)
        states[i] = GetTrackShoeState(i);
}

// -----------------------------------------------------------------------------
// Initialize this track assembly subsystem.
// -----------------------------------------------------------------------------
void ChTrackAssembly::Initialize(std::shared_ptr<ChChassis> chassis, const ChVector<>& location, bool create_shoes) {
    m_parent = chassis;
    m_rel_loc = location;

    // Initialize the sprocket, idler, and brake
    GetSprocket()->Initialize(chassis, location + GetSprocketLocation(), this);
    m_brake->Initialize(chassis, GetSprocket());

    // Initialize the suspension subsystems
    for (size_t i = 0; i < m_suspensions.size(); ++i) {
        m_suspensions[i]->Initialize(chassis, location + GetRoadWhelAssemblyLocation(static_cast<int>(i)), this);
    }

    // Initialize the idler subsystem (after supspension, for idler templates that attach to a suspension arm)
    m_idler->Initialize(chassis, location + GetIdlerLocation(), this);

    // Initialize the roller subsystems (always attached to chassis body)
    for (size_t i = 0; i < m_rollers.size(); ++i) {
        m_rollers[i]->Initialize(chassis, chassis->GetBody(), location + GetRollerLocation(static_cast<int>(i)), this);
    }

    if (!create_shoes) {
        RemoveTrackShoes();
        return;
    }

    // Assemble the track. This positions all track shoes around the sprocket, road wheels, and idler
    // (implemented by derived classes)
    bool ccw = Assemble(chassis->GetBody());

    // Loop over all track shoes and allow them to connect themselves to their neighbor
    size_t num_shoes = GetNumTrackShoes();
    std::shared_ptr<ChTrackShoe> next;
    for (size_t i = 0; i < num_shoes; ++i) {
        next = (i == num_shoes - 1) ? GetTrackShoe(0) : GetTrackShoe(i + 1);
        GetTrackShoe(i)->Connect(next, this, chassis.get(), ccw);
    }
}

// -----------------------------------------------------------------------------

void ChTrackAssembly::InitializeInertiaProperties() {
    m_mass = 0;

    GetSprocket()->AddMass(m_mass);

    m_idler->AddMass(m_mass);

    for (auto& suspension : m_suspensions)
        suspension->AddMass(m_mass);

    for (auto& roller : m_rollers)
        roller->AddMass(m_mass);

    for (size_t i = 0; i < GetNumTrackShoes(); ++i)
        GetTrackShoe(i)->AddMass(m_mass);
}

void ChTrackAssembly::UpdateInertiaProperties() {
    m_parent->GetTransform().TransformLocalToParent(ChFrame<>(m_rel_loc, QUNIT), m_xform);

    ChVector<> com(0);
    ChMatrix33<> inertia(0);

    GetSprocket()->AddInertiaProperties(com, inertia);

    m_idler->AddInertiaProperties(com, inertia);

    for (auto& suspension : m_suspensions)
        suspension->AddInertiaProperties(com, inertia);

    for (auto& roller : m_rollers)
        roller->AddInertiaProperties(com, inertia);

    for (size_t i = 0; i < GetNumTrackShoes(); ++i)
        GetTrackShoe(i)->AddInertiaProperties(com, inertia);

    m_com.coord.pos = GetTransform().TransformPointParentToLocal(com / GetMass());
    m_com.coord.rot = GetTransform().GetRot();

    const ChMatrix33<>& A = GetTransform().GetA();
    m_inertia = A.transpose() * (inertia - utils::CompositeInertia::InertiaShiftMatrix(com)) * A;
}

// -----------------------------------------------------------------------------
ChTrackSuspension::ForceTorque ChTrackAssembly::ReportSuspensionForce(size_t id) const {
    return m_suspensions[id]->ReportSuspensionForce();
}

double ChTrackAssembly::ReportTrackLength() const {
    if (GetTrackShoe(0))
        return GetTrackShoe(0)->GetPitch() * GetNumTrackShoes();
    return 0;
}

// -----------------------------------------------------------------------------
void ChTrackAssembly::SetSprocketVisualizationType(VisualizationType vis) {
    GetSprocket()->SetVisualizationType(vis);
}

void ChTrackAssembly::SetIdlerVisualizationType(VisualizationType vis) {
    GetIdler()->SetVisualizationType(vis);
}

void ChTrackAssembly::SetIdlerWheelVisualizationType(VisualizationType vis) {
    GetIdler()->GetIdlerWheel()->SetVisualizationType(vis);
}

void ChTrackAssembly::SetSuspensionVisualizationType(VisualizationType vis) {
    for (size_t i = 0; i < m_suspensions.size(); ++i) {
        m_suspensions[i]->SetVisualizationType(vis);
    }
}

void ChTrackAssembly::SetRoadWheelVisualizationType(VisualizationType vis) {
    for (size_t i = 0; i < m_suspensions.size(); ++i) {
        m_suspensions[i]->GetRoadWheel()->SetVisualizationType(vis);
    }
}

void ChTrackAssembly::SetRollerVisualizationType(VisualizationType vis) {
    for (size_t i = 0; i < m_rollers.size(); ++i) {
        m_rollers[i]->SetVisualizationType(vis);
    }
}

void ChTrackAssembly::SetTrackShoeVisualizationType(VisualizationType vis) {
    SetVisualizationType(vis);
    for (size_t i = 0; i < GetNumTrackShoes(); ++i) {
        GetTrackShoe(i)->SetVisualizationType(vis);
    }
}

// -----------------------------------------------------------------------------

void ChTrackAssembly::SetWheelCollisionType(bool roadwheel_as_cylinder,
                                            bool idler_as_cylinder,
                                            bool roller_as_cylinder) {
    m_roadwheel_as_cylinder = roadwheel_as_cylinder;
    m_idler_as_cylinder = idler_as_cylinder;
    m_roller_as_cylinder = roller_as_cylinder;
}

// -----------------------------------------------------------------------------
// Update the state of this track assembly at the current time.
// -----------------------------------------------------------------------------
void ChTrackAssembly::Synchronize(double time, double braking, const TerrainForces& shoe_forces) {
    // Zero out applied torque on sprocket axle
    GetSprocket()->m_axle->SetAppliedTorque(0.0);

    // Apply track shoe forces
    for (size_t i = 0; i < GetNumTrackShoes(); ++i) {
        GetTrackShoe(i)->m_shoe->Empty_forces_accumulators();
        GetTrackShoe(i)->m_shoe->Accumulate_force(shoe_forces[i].force, shoe_forces[i].point, false);
        GetTrackShoe(i)->m_shoe->Accumulate_torque(shoe_forces[i].moment, false);
    }

    // Apply braking input
    m_brake->Synchronize(braking);
}

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ChTrackAssembly::SetOutput(bool state) {
    m_output = state;
    GetSprocket()->SetOutput(state);
    m_brake->SetOutput(state);
    m_idler->SetOutput(state);
    for (auto suspension : m_suspensions)
        suspension->SetOutput(state);
    for (auto roller : m_rollers)
        roller->SetOutput(state);
    if (GetNumTrackShoes() > 0)
        GetTrackShoe(0)->SetOutput(state);
}

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ChTrackAssembly::ExportComponentList(rapidjson::Document& jsonDocument) const {
    ChPart::ExportComponentList(jsonDocument);

    jsonDocument.AddMember("number shoes", static_cast<int>(GetNumTrackShoes()), jsonDocument.GetAllocator());

    {
        rapidjson::Document jsonSubDocument(&jsonDocument.GetAllocator());
        jsonSubDocument.SetObject();
        GetSprocket()->ExportComponentList(jsonSubDocument);
        jsonDocument.AddMember("sprocket", jsonSubDocument, jsonDocument.GetAllocator());
    }

    {
        rapidjson::Document jsonSubDocument(&jsonDocument.GetAllocator());
        jsonSubDocument.SetObject();
        m_brake->ExportComponentList(jsonSubDocument);
        jsonDocument.AddMember("brake", jsonSubDocument, jsonDocument.GetAllocator());
    }

    {
        rapidjson::Document jsonSubDocument(&jsonDocument.GetAllocator());
        jsonSubDocument.SetObject();
        m_idler->ExportComponentList(jsonSubDocument);
        jsonDocument.AddMember("idler", jsonSubDocument, jsonDocument.GetAllocator());
    }

    rapidjson::Value suspArray(rapidjson::kArrayType);
    for (auto suspension : m_suspensions) {
        rapidjson::Document jsonSubDocument(&jsonDocument.GetAllocator());
        jsonSubDocument.SetObject();
        suspension->ExportComponentList(jsonSubDocument);
        suspArray.PushBack(jsonSubDocument, jsonDocument.GetAllocator());
    }
    jsonDocument.AddMember("suspensions", suspArray, jsonDocument.GetAllocator());

    rapidjson::Value rollerArray(rapidjson::kArrayType);
    for (auto roller : m_rollers) {
        rapidjson::Document jsonSubDocument(&jsonDocument.GetAllocator());
        jsonSubDocument.SetObject();
        roller->ExportComponentList(jsonSubDocument);
        rollerArray.PushBack(jsonSubDocument, jsonDocument.GetAllocator());
    }
    jsonDocument.AddMember("rollers", rollerArray, jsonDocument.GetAllocator());

    if (GetNumTrackShoes() > 0) {
        rapidjson::Document jsonSubDocument(&jsonDocument.GetAllocator());
        jsonSubDocument.SetObject();
        GetTrackShoe(0)->ExportComponentList(jsonSubDocument);
        jsonDocument.AddMember("shoe 0", jsonSubDocument, jsonDocument.GetAllocator());
    }
}

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ChTrackAssembly::Output(ChVehicleOutput& database) const {
    if (!m_output)
        return;

    database.WriteSection(GetSprocket()->GetName());
    GetSprocket()->Output(database);

    database.WriteSection(m_brake->GetName());
    m_brake->Output(database);

    database.WriteSection(m_idler->GetName());
    m_idler->Output(database);

    for (auto suspension : m_suspensions) {
        database.WriteSection(suspension->GetName());
        suspension->Output(database);
        database.WriteSection(suspension->GetRoadWheel()->GetName());
        suspension->GetRoadWheel()->Output(database);
    }

    for (auto roller : m_rollers) {
        database.WriteSection(roller->GetName());
        roller->Output(database);
    }

    if (GetNumTrackShoes() > 0) {
        database.WriteSection(GetTrackShoe(0)->GetName());
        GetTrackShoe(0)->Output(database);
    }
}

// -----------------------------------------------------------------------------
// Log constraint violations
// -----------------------------------------------------------------------------
void ChTrackAssembly::LogConstraintViolations() {
    GetLog() << "SPROCKET constraint violations\n";
    GetSprocket()->LogConstraintViolations();
    GetLog() << "IDLER constraint violations\n";
    m_idler->LogConstraintViolations();
    for (size_t i = 0; i < m_suspensions.size(); i++) {
        GetLog() << "SUSPENSION #" << i << " constraint violations\n";
        m_suspensions[i]->LogConstraintViolations();
    }
    for (size_t i = 0; i < m_rollers.size(); i++) {
        GetLog() << "ROLLER #" << i << " constraint violations\n";
        m_rollers[i]->LogConstraintViolations();
    }
}

}  // end namespace vehicle
}  // end namespace chrono


text:
#pragma once

#include <string>
#include <vector>

#include "Dentry.hpp"

class DentryCache
{
public:
	static Dentry* findDentry(Dentry* parent, std::vector<std::string> pathname, size_t index);

};

/*class DentryCache {

	dget: open a new handle for an existing dentry (this just increments
			the usage count)

	dput: close a handle for a dentry (decrements the usage count). If
	the usage count drops to 0, and the dentry is still in its
	parent's hash, the "d_delete" method is called to check whether
	it should be cached. If it should not be cached, or if the dentry
	is not hashed, it is deleted. Otherwise cached dentries are put
	into an LRU list to be reclaimed on memory shortage.

	d_drop: this unhashes a dentry from its parents hash list. A
	subsequent call to dput() will deallocate the dentry if its
	usage count drops to 0

	d_delete: delete a dentry. If there are no other open references to
	the dentry then the dentry is turned into a negative dentry
	(the d_iput() method is called). If there are other
	references, then d_drop() is called instead

	d_add: add a dentry to its parents hash list and then calls
	d_instantiate()

	d_instantiate: add a dentry to the alias hash list for the inode and
	updates the "d_inode" member. The "i_count" member in the
	inode structure should be set/incremented. If the inode
	pointer is NULL, the dentry is called a "negative
	dentry". This function is commonly called when an inode is
	created for an existing negative dentry

	d_lookup: look up a dentry given its parent and path name component
	It looks up the child of that given name from the dcache
	hash table. If it is found, the reference count is incremented
	and the dentry is returned. The caller must use dput()
	to free the dentry when it finishes using it.
};*/

redpajama_set_name: RedPajamaGithub


text:
title: "Use homebrew services to manage services on MacOS"
layout: post
date: 2019-12-25 22:06
guid: urn:uuid:f766abd4-c95b-4439-8174-1cdce2c43bfd
author: "Lixiang"
tags:
  - Tool
---

[Homebrew Services](https://github.com/Homebrew/homebrew-services). It integrates Homebrew formulae with macOS' launchctl manager.

With homebrew services, we can manage the services so simplify.

#### Start

`brew services start service_name`

e.g.
Start the MySQL service at login with:

```shell
brew services start mysql
```

#### Stop

`brew services stop service_name`

e.g.
Stop the MySQL service with:

```shell
brew services stop mysql
```

#### Restart
`brew services restart service_name`

e.g.
Restart the MySQL service with:

```shell
brew services restart mysql
```

#### List
List all services managed by brew services with:

```shell
brew services list
```

#### Cleanup
Remove all unused services with:

```shell
brew services cleanup
```


text:
title: Blog 2
layout: post
author: tom.vicary
permalink: /blog-2/
source-id: 1-V7ElK-mfvLuNEtKItUAjJ5eGmbQZvKn8NA_zULgkIA
published: true
---
In this lesson we created n online shop were we could decide what clothes and prices we sold.

We were challenged to create a online shop were you could type in any item in a box and any quantity in another ad be given a price without having to do any multiplying.

In my shop I created a buy 1 get one free offer by using if statements and equal to starlets I completed this but I was unable to complete the original challenge due to the time given to us.


text:
package com.thinkbiganalytics.spark.config;

import com.thinkbiganalytics.kylo.catalog.KyloCatalog;
import com.thinkbiganalytics.kylo.catalog.api.KyloCatalogClientBuilder;
import com.thinkbiganalytics.spark.metadata.TransformScript;
import com.thinkbiganalytics.spark.metadata.TransformScript16;
import com.thinkbiganalytics.spark.service.DataSetConverterService;
import com.thinkbiganalytics.spark.service.DataSetConverterServiceV1;
import com.thinkbiganalytics.spark.service.SparkListenerService;
import com.thinkbiganalytics.spark.service.SparkListenerService16;

import org.apache.spark.SparkContext;
import org.apache.spark.sql.SQLContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Nonnull;

/**
 * Configures the Kylo Spark Shell for Spark 1.6.
 */
@Configuration
public class SparkShellConfig16 {

    @Bean
    public DataSetConverterService converterService() {
        return new DataSetConverterServiceV1();
    }

    /**
     * Creates a Spark listener service.
     */
    @Bean
    public SparkListenerService sparkListenerService(@Nonnull final SparkContext sparkContext) {
        return new SparkListenerService16(sparkContext);
    }

    /**
     * Gets the class for transform scripts.
     */
    @Bean
    public Class<? extends TransformScript> transformScriptClass() {
        return TransformScript16.class;
    }

    /**
     * Gets the class for transform scripts.
     */
    @Bean
    public KyloCatalogClientBuilder kyloCatalogClientBuilder(final SQLContext sqlContext) {
        return KyloCatalog.builder(sqlContext);
    }
}


text:
    <button class="btn btn-clean" ng-click="openFieldPopover()"></button>
    <button class="btn btn-clean" ng-click="removeFormElement(formElement)"></button>

      {{formElement.name}}*
      <input type="text" class="form-control" style="cursor:default;background-color:#fff;" value="Text" disabled>

      {{formElement.name}}*
      <textarea rows="4" class="form-control" style="cursor:default;background-color:#fff;" value="Text" disabled></textarea>

       {{formElement.name}} *
      <input type="text" class="form-control" name="date" disabled>

          <input type="checkbox" class="checkbox-inline" disabled>{{formElement.name}} *

      {{formElement.name}} *

 0" class="radio" ng-repeat="option in formElement.options">

              <input type="radio" name="optionsRadios" id="optionsRadios{{$index}}" value="option{{$index}}" ng-checked="formElement.value == option.name" disabled>{{option.name}}</input>

              <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" disabled>
              Option 1

      {{formElement.name}} *
      <input type="number" class="form-control" style="cursor:default;background-color:#fff;" value="123" disabled>

      {{formElement.name}} *
      <input type="number" class="form-control" style="cursor:default;background-color:#fff;" value="123.12" disabled>

    {{formElement.name}} *
    <select class="form-control" style="cursor:default;" disabled>
          <option>Select...</option>
    </select>

    {{formElement.name}} *

      <input type="text" class="form-control" style="cursor:default;background-color:#fff;" placeholder="{{'FORM-BUILDER.LABEL.PERSON' | translate}}" value="{{formElement.placeholder}}" disabled>

    {{formElement.name}} *

      <input type="text" class="form-control" style="cursor:default;background-color:#fff;" placeholder="{{'FORM-BUILDER.LABEL.FUNCTIONAL-GROUP' | translate}}" value="{{formElement.placeholder}}" >

    {{formElement.name}} *

      <input type="text" class="form-control" style="cursor:default;background-color:#fff;" value="Upload or import content..." disabled>

    {{formElement.name}}*

{{formElement.params.hyperlinkUrl}}

 0">
        {{formElement.expression}}

      	{{'FORM-BUILDER.MESSAGE.EMPTY-EXPRESSION' | translate}}

{{formElement.name}}


text:
#include "RobotCSpace.h"
#include "Modeling/Interpolate.h"
#include <KrisLibrary/math/angle.h>
#include <KrisLibrary/math/random.h>
#include <KrisLibrary/math3d/rotation.h>
#include <KrisLibrary/math3d/random.h>
#include <KrisLibrary/math3d/interpolate.h>
#include <KrisLibrary/robotics/Rotation.h>
#include <KrisLibrary/planning/EdgePlanner.h>
#include <KrisLibrary/planning/EdgePlannerHelpers.h>
#include <KrisLibrary/planning/CSetHelpers.h>
#include <KrisLibrary/planning/CSpaceHelpers.h>
#include <KrisLibrary/Timer.h>
#include <boost/functional.hpp>
#include <sstream>

Real RandLaplacian()
{
  Real v = Rand();
  if(v==0) v = Epsilon;
  return -Log(v);
}

Real RandTwoSidedLaplacian()
{
  if(RandBool(0.5)) return RandLaplacian();
  else return -RandLaplacian();
}

Real SafeRand(Real a,Real b)
{
  if(IsInf(a) && IsInf(b)) return RandTwoSidedLaplacian();
  else if(IsInf(a)) return b-RandLaplacian();
  else if(IsInf(b)) return a+RandLaplacian();
  else return Rand(a,b);
}

RobotCSpace::RobotCSpace(Robot& _robot)
  :robot(_robot),norm(2.0)
{
  floatingRotationWeight=1;
  floatingRotationRadiusScale=1;

  for(int i=0;i<_robot.q.n;i++) {
    if(IsInf(_robot.qMin[i])!= -1 || IsInf(_robot.qMax[i]) != 1)
      AddConstraint(robot.LinkName(i)+"_joint_limit",new AxisRangeSet(i,_robot.qMin[i],_robot.qMax[i]));
  }
}

RobotCSpace::RobotCSpace(const RobotCSpace& space)
:robot(space.robot),norm(space.norm),
jointWeights(space.jointWeights),floatingRotationWeight(space.floatingRotationWeight),
jointRadiusScale(space.jointRadiusScale),floatingRotationRadiusScale(space.floatingRotationRadiusScale)
{
  CopyConstraints(&space);
}

int RobotCSpace::NumDimensions()
{
  return robot.q.n;
}

string RobotCSpace::VariableName(int i)
{
  return robot.LinkName(i);
}

void RobotCSpace::Sample(Config& q)
{
  for(size_t i=0;i<robot.joints.size();i++) {
    int link = robot.joints[i].linkIndex;
    switch(robot.joints[i].type) {
    case RobotJoint::Weld:
      break;
    case RobotJoint::Normal:
      robot.q(link) = Rand(robot.qMin(link),robot.qMax(link));
      break;
    case RobotJoint::Spin:
      robot.q(link) = Rand(0,TwoPi);
      break;
    case RobotJoint::FloatingPlanar:
      {
      int p = robot.parents[link];
      assert(p>=0);
      int pp = robot.parents[p];
      assert(pp>=0);
      robot.q(link) = Rand(0,TwoPi);
      robot.q(p) = SafeRand(robot.qMin(p),robot.qMax(p));
      robot.q(pp) = SafeRand(robot.qMin(pp),robot.qMax(pp));
      break;
      }
    case RobotJoint::Floating:
    case RobotJoint::BallAndSocket:
      {
	RigidTransform T;
  T.t.x = RandTwoSidedLaplacian();
  T.t.y = RandTwoSidedLaplacian();
  T.t.z = RandTwoSidedLaplacian();
	QuaternionRotation qr;
	RandRotation(qr);
	qr.getMatrix(T.R);
	robot.SetJointByTransform(i,robot.joints[i].linkIndex,T);
      }
      break;
    default:
      break;
    }
  }
  for(size_t i=0;i<robot.drivers.size();i++) {
    if(robot.drivers[i].type != RobotJointDriver::Normal) {
      Real val = Rand(robot.drivers[i].qmin,robot.drivers[i].qmax);
      robot.SetDriverValue(i,val);
    }
  }
  q = robot.q;
  return;
}

void RobotCSpace::SampleNeighborhood(const Config& c,Real r,Config& q)
{
  robot.q=c;
  for(size_t i=0;i<robot.joints.size();i++) {
    Real ri;
    if(jointRadiusScale.empty()) {
      if(jointWeights.empty()) ri = r;
      else ri = r / jointWeights[i];
    }
    else ri = r / jointRadiusScale[i];
    int link = robot.joints[i].linkIndex;
    switch(robot.joints[i].type) {
    case RobotJoint::Weld:
      break;
    case RobotJoint::Normal:
      robot.q(link) += Rand(-ri,ri);
      break;
    case RobotJoint::Spin:
      robot.q(link) += Rand(-ri,ri);
      break;
    case RobotJoint::Floating:
    case RobotJoint::BallAndSocket:
      {
	RigidTransform T = robot.links[link].T_World;
	T.t.x += Rand(-ri,ri);
	T.t.y += Rand(-ri,ri);
	T.t.z += Rand(-ri,ri);
	AngleAxisRotation aa;
	SampleSphere(1.0,aa.axis);
	aa.angle = Rand(-ri/floatingRotationRadiusScale,ri/floatingRotationRadiusScale);
	Matrix3 Rperturb;
	aa.getMatrix(Rperturb);
	T.R = Rperturb*T.R;
	robot.SetJointByTransform(i,robot.joints[i].linkIndex,T);
      }
      break;
    default:
      break;
    }
  }
  for(size_t i=0;i<robot.drivers.size();i++) {
    if(robot.drivers[i].type != RobotJointDriver::Normal) {
      Real val = robot.GetDriverValue(i);
      Real scale = 1.0;
      //TODO: figure out the proper scale factor
      robot.SetDriverValue(i,val + Rand(-r,r));
    }
  }
  q = robot.q;
  robot.NormalizeAngles(q);
}

void RobotCSpace::Interpolate(const Config& x,const Config& y,Real u,Config& out)
{
  ::Interpolate(robot,x,y,u,out);
}

Real RobotCSpace::Distance(const Config& a,const Config& b)
{
  if(jointWeights.empty())
    return ::Distance(robot,a,b,norm,floatingRotationWeight);
  else
    return ::Distance(robot,a,b,norm,jointWeights,floatingRotationWeight);
}

void RobotCSpace::Properties(PropertyMap& map) const
{
  int euclidean = 1;
  Real v = 1;
  int dim = robot.q.n;
  Vector vmin(robot.qMin),vmax(robot.qMax);
  vector<Real> weights;
  if(jointWeights.empty()) weights.resize(robot.q.n,1.0);
  else weights = jointWeights;
  for(size_t i=0;i<robot.joints.size();i++) {
    int link = robot.joints[i].linkIndex;
    switch(robot.joints[i].type) {
    case RobotJoint::Normal:
      v*=robot.qMax(link)-robot.qMin(link);
      break;
    case RobotJoint::Weld:
      dim--;
      break;
    case RobotJoint::Spin:
      v*=TwoPi;
      vmin(link) = 0;
      vmax(link) = TwoPi;
      euclidean = 0;
      break;
    case RobotJoint::Floating:
    case RobotJoint::BallAndSocket:
      v*= Pi*4.0/3.0;
      weights[link] = weights[link-1] = weights[link-2] = floatingRotationWeight;
      euclidean = 0;
      break;
    case RobotJoint::FloatingPlanar:
      vmin(link) = 0;
      vmax(link) = TwoPi;
      v*= TwoPi;
      weights[link] = floatingRotationWeight;
      euclidean = 0;
      break;
    default:
      euclidean = 0;
      break;
    }
  }

  map.set("euclidean",euclidean);
  map.set("geodesic",1);
  if(dim < robot.q.n) {
    map.set("submanifold",1);
    map.set("intrinsicDimension",dim);
  }
  map.setArray("minimum",vector<Real>(vmin));
  map.setArray("maximum",vector<Real>(vmax));
  map.set("volume",v);
  if(norm == 2)
    map.set("metric","weighted euclidean");
  else if(norm == 1)
    map.set("metric","weighted manhattan");
  else if(IsInf(norm))
    map.set("metric","weighted Linf");
  map.setArray("metricWeights",weights);
}

void RobotCSpace::InterpolateDeriv(const Config& a,const Config& b,Real u,Vector& dx)
{
  ::InterpolateDerivative(robot,a,b,u,dx);
}

void RobotCSpace::InterpolateDerivA(const Config& a,const Config& b,Real u,const Vector& da,Vector& dx)
{
  dx.mul(da,1-u);
  for(size_t i=0;i<robot.joints.size();i++) {
    int k=robot.joints[i].linkIndex;
    if(robot.joints[i].type == RobotJoint::Floating) {
      vector<int> indices;
      robot.GetJointIndices(i,indices);
      Vector3 oldrot(a(indices[3]),a(indices[4]),a(indices[5]));
      Vector3 newrot(b(indices[3]),b(indices[4]),b(indices[5]));
      Vector3 drot(da(indices[3]),da(indices[4]),da(indices[5]));
      assert(robot.links[indices[3]].w == Vector3(0,0,1));
      assert(robot.links[indices[4]].w == Vector3(0,1,0));
      assert(robot.links[indices[5]].w == Vector3(1,0,0));

      EulerAngleRotation ex(oldrot),ey(newrot),eu;
      Matrix3 Rx,Ry,Ru;
      ex.getMatrixZYX(Rx);
      ey.getMatrixZYX(Ry);
      interpolateRotation(Rx,Ry,u,Ru);
      eu.setMatrixZYX(Ru);

      Vector3 dw;
      AngularVelocityEulerAngle(oldrot,drot,2,1,0,dw);
      Vector3 dtheta;
      bool res=EulerAngleDerivative(eu,dw,2,1,0,dtheta);
      dtheta *= (1-u);
      dtheta.get(dx(indices[3]),dx(indices[4]),dx(indices[5]));
    }
    else if(robot.joints[i].type == RobotJoint::BallAndSocket) {
      vector<int> indices;
      robot.GetJointIndices(i,indices);
      Vector3 oldrot(a(indices[0]),a(indices[1]),a(indices[2]));
      Vector3 newrot(b(indices[0]),b(indices[1]),b(indices[2]));
      Vector3 drot(da(indices[0]),da(indices[1]),da(indices[2]));
      assert(robot.links[indices[0]].w == Vector3(0,0,1));
      assert(robot.links[indices[1]].w == Vector3(0,1,0));
      assert(robot.links[indices[2]].w == Vector3(1,0,0));

      EulerAngleRotation ex(oldrot),ey(newrot),eu;
      Matrix3 Rx,Ry,Ru;
      ex.getMatrixZYX(Rx);
      ey.getMatrixZYX(Ry);
      interpolateRotation(Rx,Ry,u,Ru);
      eu.setMatrixZYX(Ru);

      Vector3 dw;
      AngularVelocityEulerAngle(oldrot,drot,2,1,0,dw);
      Vector3 dtheta;
      bool res=EulerAngleDerivative(eu,dw,2,1,0,dtheta);
      dtheta *= (1-u);
      dtheta.get(dx(indices[0]),dx(indices[1]),dx(indices[2]));
    }
  }
}
void RobotCSpace::InterpolateDerivB(const Config& a,const Config& b,Real u,const Vector& db,Vector& dx)
{
  dx.mul(db,u);
  for(size_t i=0;i<robot.joints.size();i++) {
    //int k=robot.joints[i].linkIndex;
    if(robot.joints[i].type == RobotJoint::Floating) {
      vector<int> indices;
      robot.GetJointIndices(i,indices);
      Vector3 oldrot(a(indices[3]),a(indices[4]),a(indices[5]));
      Vector3 newrot(b(indices[3]),b(indices[4]),b(indices[5]));
      Vector3 drot(db(indices[3]),db(indices[4]),db(indices[5]));
      assert(robot.links[indices[3]].w == Vector3(0,0,1));
      assert(robot.links[indices[4]].w == Vector3(0,1,0));
      assert(robot.links[indices[5]].w == Vector3(1,0,0));

      EulerAngleRotation ex(oldrot),ey(newrot),eu;
      Matrix3 Rx,Ry,Ru;
      ex.getMatrixZYX(Rx);
      ey.getMatrixZYX(Ry);
      interpolateRotation(Rx,Ry,u,Ru);
      eu.setMatrixZYX(Ru);

      Vector3 dw;
      AngularVelocityEulerAngle(newrot,drot,2,1,0,dw);
      Vector3 dtheta;
      bool res=EulerAngleDerivative(eu,dw,2,1,0,dtheta);
      dtheta *= u;
      dtheta.get(dx(indices[3]),dx(indices[4]),dx(indices[5]));
    }
    else if(robot.joints[i].type == RobotJoint::BallAndSocket) {
      vector<int> indices;
      robot.GetJointIndices(i,indices);
      Vector3 oldrot(a(indices[0]),a(indices[1]),a(indices[2]));
      Vector3 newrot(b(indices[0]),b(indices[1]),b(indices[2]));
      Vector3 drot(db(indices[0]),db(indices[1]),db(indices[2]));
      assert(robot.links[indices[0]].w == Vector3(0,0,1));
      assert(robot.links[indices[1]].w == Vector3(0,1,0));
      assert(robot.links[indices[2]].w == Vector3(1,0,0));

      EulerAngleRotation ex(oldrot),ey(newrot),eu;
      Matrix3 Rx,Ry,Ru;
      ex.getMatrixZYX(Rx);
      ey.getMatrixZYX(Ry);
      interpolateRotation(Rx,Ry,u,Ru);
      eu.setMatrixZYX(Ru);

      Vector3 dw;
      AngularVelocityEulerAngle(newrot,drot,2,1,0,dw);
      Vector3 dtheta;
      bool res=EulerAngleDerivative(eu,dw,2,1,0,dtheta);
      dtheta *= u;
      dtheta.get(dx(indices[0]),dx(indices[1]),dx(indices[2]));
    }
  }
}

void RobotCSpace::InterpolateDeriv2(const Config& a,const Config& b,Real u,Vector& ddx) { FatalError("Not implemented"); }

void RobotCSpace::Integrate(const Config& a,const Vector& da,Config& b)
{
  ::Integrate(robot,a,da,b);
}

ActiveRobotCSpace::ActiveRobotCSpace(Robot& _robot,const ArrayMapping& _dofs)
  :robot(_robot),dofs(_dofs)
{
  xq=yq=tempq=robot.q;
  invMap.resize(robot.q.n,-1);
  Assert(!dofs.IsOffset());
  for(size_t i=0;i<dofs.mapping.size();i++)
    invMap[dofs.mapping[i]] = int(i);
  for(size_t i=0;i<robot.joints.size();i++)
    if(invMap[robot.joints[i].linkIndex] >= 0)
      if(robot.joints[i].type == RobotJoint::Floating || robot.joints[i].type == RobotJoint::Spin || robot.joints[i].type == RobotJoint::FloatingPlanar || robot.joints[i].type == RobotJoint::BallAndSocket)
  joints.push_back(i);

  for(size_t i=0;i<dofs.mapping.size();i++) {
    if(IsInf(robot.qMin[dofs.mapping[i]]) != -1 || IsInf(robot.qMax[dofs.mapping[i]]) != 1)
      AddConstraint(robot.LinkName(dofs.mapping[i])+"_joint_limit",new AxisRangeSet(i,robot.qMin[dofs.mapping[i]],robot.qMax[dofs.mapping[i]]));
  }
}

int ActiveRobotCSpace::NumDimensions()
{
  return (int)dofs.mapping.size();
}

string ActiveRobotCSpace::VariableName(int i)
{
  return robot.LinkName(dofs.mapping[i]);
}

void ActiveRobotCSpace::Sample(Config& x)
{
  x.resize(dofs.mapping.size());
  for(size_t j=0;j<joints.size();j++) {
    int i=joints[j];
    int link = robot.joints[i].linkIndex;
    int k=invMap[link];
    switch(robot.joints[i].type) {
    case RobotJoint::Weld:
      break;
    case RobotJoint::Normal:
      x(k) = Rand(robot.qMin(link),robot.qMax(link));
      break;
    case RobotJoint::Spin:
      x(k) = Rand(0,TwoPi);
      break;
    case RobotJoint::Floating:
    case RobotJoint::BallAndSocket:
      {
	Matrix3 R;
	QuaternionRotation qr;
	RandRotation(qr);
	qr.getMatrix(R);
	robot.SetJointByOrientation(i,robot.joints[i].linkIndex,R);
	vector<int> indices;
	robot.GetJointIndices(i,indices);
	for(size_t m=0;m<indices.size();m++)
	  x(invMap[indices[m]]) = robot.q(indices[m]);
      }
      break;
    default:
      break;
    }
  }
  return;
}

void ActiveRobotCSpace::Interpolate(const Config& x,const Config& y,Real u,Config& out)
{
  dofs.Map(x,xq);
  dofs.Map(y,yq);
  ::Interpolate(robot,xq,yq,u,tempq);
  out.resize(dofs.Size());
  dofs.InvMap(tempq,out);
}

Real ActiveRobotCSpace::Distance(const Config& x,const Config& y)
{
  //what norm to use
  NormAccumulator<Real> norm;
  for(size_t j=0;j<joints.size();j++) {
    int i=joints[j];
    switch(robot.joints[i].type) {
    case RobotJoint::Weld:
      break;
    case RobotJoint::Normal:
      {
	int l=invMap[robot.joints[i].linkIndex];
	norm << (x(l)-y(l));
      }
      break;
    case RobotJoint::Floating:
      {
	vector<int> indices;
	robot.GetJointIndices(i,indices);
	for(size_t j=0;j<indices.size();j++)
	  indices[j] = invMap[indices[j]];
	Assert(indices.size()==6);
	int tx = indices[0];
	int ty = indices[1];
	int tz = indices[2];
	int rz = indices[3];
	int ry = indices[4];
	int rx = indices[5];
	RigidTransform Tx,Ty;
	Tx.t.set(x[tx],x[ty],x[tz]);
	Ty.t.set(y[tx],y[ty],y[tz]);
	EulerAngleRotation Rx(x[rz],x[ry],x[rx]);
	EulerAngleRotation Ry(y[rz],y[ry],y[rx]);
	Rx.getMatrixZXY(Tx.R);
	Ry.getMatrixZXY(Ty.R);
	RigidTransform T; T.mulInverseB(Tx,Ty);
	Real cosangle = Half*(T.R.trace()-One);
	cosangle=Clamp(cosangle,-One,One);
	Real rdiff = Acos(cosangle);
	//sum += T.t.normSquared() + Sqr(rdiff);
	norm.collect(T.t.x);
	norm.collect(T.t.y);
	norm.collect(T.t.z);
	norm.collect(rdiff);
      }
      break;
    default:
      FatalError("TODO");
    }
  }
  return norm;
}

void ActiveRobotCSpace::Properties(PropertyMap& map) const
{
  //TODO
}

void ActiveRobotCSpace::InterpolateDeriv(const Config& a,const Config& b,Real u,Vector& dx)
{
  if(joints.empty()) {
    dx.sub(b,a);
    return;
  }
  dofs.Map(a,xq);
  dofs.Map(b,yq);
  Assert(u==0);
  ::InterpolateDerivative(robot,xq,yq,tempq);
  dx.resize(dofs.Size());
  dofs.InvMap(tempq,dx);
}

void ActiveRobotCSpace::InterpolateDerivA(const Config& a,const Config& b,Real u,const Vector& da,Vector& dx)
{
  FatalError("Not implemented");
}

void ActiveRobotCSpace::InterpolateDerivB(const Config& a,const Config& b,Real u,const Vector& db,Vector& dx)
{
  FatalError("Not implemented");
}

void ActiveRobotCSpace::InterpolateDeriv2(const Config& a,const Config& b,Real u,Vector& ddx)
{
  FatalError("Not implemented");
}

void ActiveRobotCSpace::Integrate(const Config& a,const Vector& da,Config& b)
{
  if(joints.empty()) {
    b.add(a,da);
    return;
  }
  dofs.Map(a,xq);
  dofs.Map(da,yq);
  ::Integrate(robot,xq,yq,tempq);
  b.resize(dofs.Size());
  dofs.InvMap(tempq,b);
}

SingleRobotCSpace::SingleRobotCSpace(RobotWorld& _world,int _index,WorldPlannerSettings* _settings)
  :RobotCSpace(*_world.robots[_index]),world(_world),index(_index),settings(_settings),constraintsDirty(true)
{
  Assert(settings != NULL);
  Assert((int)settings->robotSettings.size() > _index);

  const Vector& w=settings->robotSettings[index].distanceWeights;
  RobotCSpace::jointWeights = w;

  Init();
}

SingleRobotCSpace::SingleRobotCSpace(const SingleRobotCSpace& space)
  :RobotCSpace(space),world(space.world),index(space.index),settings(space.settings),fixedDofs(space.fixedDofs),fixedValues(space.fixedValues),ignoreCollisions(space.ignoreCollisions),constraintsDirty(true)
{
  Init();
}

bool SingleRobotCSpace::CheckJointLimits(const Config& x)
{
  robot.UpdateConfig(x);
  for(size_t i=0;i<robot.joints.size();i++) {
    if(robot.joints[i].type == RobotJoint::Normal || robot.joints[i].type == RobotJoint::Weld) {
      int k=robot.joints[i].linkIndex;
      if(x(k) < robot.qMin(k) || x(k) > robot.qMax(k)) {
	//printf("Joint %d value %g out of bounds [%g,%g]\n",i,x(i),robot.qMin(i),robot.qMax(i));
	return false;
      }
    }
  }
  for(size_t i=0;i<robot.drivers.size();i++) {
    Real v=robot.GetDriverValue(i);
    if(v < robot.drivers[i].qmin || v > robot.drivers[i].qmax) {
      //printf("Driver %d value %g out of bounds [%g,%g]\n",i,v,robot.drivers[i].qmin,robot.drivers[i].qmax);
      return false;
    }
  }
  return true;
}

bool SingleRobotCSpace::UpdateGeometry(const Config& x)
{
  robot.UpdateConfig(x);
  robot.UpdateGeometry();
  return true;
}

void SingleRobotCSpace::FixDof(int dof,Real value)
{
  fixedDofs.push_back(dof);
  fixedValues.push_back(value);
  constraintsDirty = true;
}

void SingleRobotCSpace::IgnoreCollisions(int a,int b)
{
  ignoreCollisions.push_back(pair<int,int>(a,b));
  constraintsDirty = true;
}

///NOTE: REQUIRES GEOMETRY TO BE UPDATED AT X
class CollisionFreeSet : public CSet
{
public:
  Geometry::AnyCollisionQuery& query;
  Real lipschitzBound;

  CollisionFreeSet(Geometry::AnyCollisionQuery& q,Real _lipschitzBound=Inf):query(q),lipschitzBound(_lipschitzBound) {}
  virtual bool Contains(const Config& x) { return !query.Collide(); }
  virtual Real ObstacleDistance(const Config& x) {
    Real dworkspace = query.Distance(0.0,0.0);
    return dworkspace / lipschitzBound;
  }
};

void SingleRobotCSpace::Init()
{
  if(!constraintsDirty) return;
  constraints.resize(0);
  constraintNames.resize(0);

  //add in fixed DOF constraints
  vector<int> isfixed(robot.q.n,-1);
  for(size_t i=0;i<fixedDofs.size();i++)
    isfixed[fixedDofs[i]] = (int)i;
  for(int i=0;i<robot.q.n;i++) {
    if(isfixed[i] >= 0) {
      int k=isfixed[i];
      stringstream ss;
      ss<<"fixed["<<robot.LinkName(i)<<"]="<<fixedValues[k];
      AddConstraint(ss.str(),new AxisRangeSet(i,fixedValues[k],fixedValues[k]));
    }
    else {
      if(IsInf(robot.qMin[i])!= -1 || IsInf(robot.qMax[i]) != 1)
        AddConstraint(robot.LinkName(i)+"_joint_limit",new AxisRangeSet(i,robot.qMin[i],robot.qMax[i]));
    }
  }
  vector<bool> oldCheckCollisions(ignoreCollisions.size());
  for(size_t i=0;i<ignoreCollisions.size();i++) {
    oldCheckCollisions[i] = settings->collisionEnabled(ignoreCollisions[i].first,ignoreCollisions[i].second);
    settings->collisionEnabled(ignoreCollisions[i].first,ignoreCollisions[i].second) = false;
    settings->collisionEnabled(ignoreCollisions[i].second,ignoreCollisions[i].first) = false;
  }

  AddConstraint("update_geometry",boost::bind1st(std::mem_fun(&SingleRobotCSpace::UpdateGeometry),this));

  int id = world.RobotID(index);
  collisionPairs.resize(0);
  collisionQueries.resize(0);
  settings->EnumerateCollisionQueries(world,id,-1,collisionPairs,collisionQueries);

  /*
  //compute lipschitz constants
  if(robot.lipschitzMatrix.isEmpty())
    robot.ComputeLipschitzMatrix();
  */

  for(size_t i=0;i<collisionPairs.size();i++)  {
    stringstream ss;
    ss<<"coll["<<world.GetName(collisionPairs[i].first)<<","<<world.GetName(collisionPairs[i].second)<<"]";

    /*
    //TODO: c-space free movement bounds
    int link=world.IsRobotLink(collisionPairs[i].first).second;
    pair<int,int> endid=world.IsRobotLink(collisionPairs[i].second);
    int endLink = (endid.first==index ? endid.second : -1);
    int lca = 0;
    if(endLink >= 0) {
      //checking self collision, what to do?
      int lca = robot.LCA(link,endLink);
      if(link != lca && endLink != lca)
        FatalError("Can't do branching structures yet\n");
      if(lca == link) //swap
        swap(link,endLink);
    }

    //printf("Getting lipschitz bounds for %d -> %d\n",link,endLink);

    Real d=0;
    int j=link;
    while(j != lca && j >= 0) {
      Assert( j >= 0 && j < (int)robot.links.size());
      d += Abs(dx(j)) * robot.lipschitzMatrix(j,link);
      j = robot.parents[j];
    }
    j=endLink;
    while(j != lca && j >= 0) {
      Assert( j >= 0 && j < (int)robot.links.size());
      d += Abs(dx(j)) * robot.lipschitzMatrix(j,link);
      j = robot.parents[j];
    }
    */

    AddConstraint(ss.str(),new CollisionFreeSet(collisionQueries[i]));
  }

  for(size_t i=0;i<ignoreCollisions.size();i++) {
    settings->collisionEnabled(ignoreCollisions[i].first,ignoreCollisions[i].second) = oldCheckCollisions[i];
    settings->collisionEnabled(ignoreCollisions[i].second,ignoreCollisions[i].first) = oldCheckCollisions[i];
  }
  constraintsDirty = false;
}

void SingleRobotCSpace::Sample(Config& x)
{
  RobotCSpace::Sample(x);
  const AABB3D& bb=settings->robotSettings[index].worldBounds;
  for(size_t i=0;i<robot.joints.size();i++) {
    if(robot.joints[i].type == RobotJoint::Floating) {
      //generate a floating base position
      Vector3 p;
      p.x = Rand(bb.bmin.x,bb.bmax.x);
      p.y = Rand(bb.bmin.y,bb.bmax.y);
      p.z = Rand(bb.bmin.z,bb.bmax.z);
      vector<int> indices;
      robot.GetJointIndices(i,indices);
      for(size_t k=0;k<3;k++)
	x(indices[k]) = p[k];
    }
  }
  for(size_t j=0;j<fixedDofs.size();j++)
    x(fixedDofs[j]) = fixedValues[j];
}

void SingleRobotCSpace::SampleNeighborhood(const Config& c,Real r,Config& x)
{
  RobotCSpace::SampleNeighborhood(c,r,x);
  for(size_t j=0;j<fixedDofs.size();j++)
    x(fixedDofs[j]) = fixedValues[j];
}

bool SingleRobotCSpace::IsFeasible(const Config& x)
{
  ///This is faster than going through all constraints
  if(!CheckJointLimits(x)) return false;

  return CheckCollisionFree(x);
}

bool SingleRobotCSpace::CheckCollisionFree(const Config& x)
{
  UpdateGeometry(x);

  //this method may be faster for many-DOF robots because it does broad-phase checking first to eliminate candidate collisions
  int id = world.RobotID(index);
  vector<int> idrobot(1,id);
  vector<int> idothers;
  for(size_t i=0;i<world.terrains.size();i++)
    idothers.push_back(world.TerrainID(i));
  for(size_t i=0;i<world.rigidObjects.size();i++)
    idothers.push_back(world.RigidObjectID(i));
  for(size_t i=0;i<world.robots.size();i++) {
    if((int)i != index)
      idothers.push_back(world.RobotID(i));
  }
  //environment collision check
  pair<int,int> res = settings->CheckCollision(world,idrobot,idothers);
  if(res.first >= 0) {
    //printf("Collision found: %s (%d) - %s (%d)\n",world.GetName(res.first).c_str(),res.first,world.GetName(res.second).c_str(),res.second);
    return false;
  }
  //self collision check
  res = settings->CheckCollision(world,idrobot);
  if(res.first >= 0) {
    //printf("Self-collision found: %s %s\n",world.GetName(res.first).c_str(),world.GetName(res.second).c_str());
    return false;
  }
  return true;
}

EdgePlanner* SingleRobotCSpace::PathChecker(const Config& a,const Config& b,int obstacle)
{
  if(constraints[obstacle]->IsConvex()) {
    return new TrueEdgeChecker(this,a,b);
  }
  SubsetConstraintCSpace* ospace = new SubsetConstraintCSpace(this,obstacle);
  return new EdgePlannerWithCSpaceContainer(ospace,new EpsilonEdgeChecker(ospace,a,b,settings->robotSettings[index].collisionEpsilon));
}

EdgePlanner* SingleRobotCSpace::PathChecker(const Config& a,const Config& b)
{
  return new EpsilonEdgeChecker(this,a,b,settings->robotSettings[index].collisionEpsilon);
  //uncomment this if you need an explicit edge planner
  //return new ExplicitEdgePlanner(this,a,b);
}

/*
vector<pair<int,int> > linkIndices;
vector<vector<Geometry::CollisionMeshQueryEnhanced> > linkCollisions;
void GetCollisionList(RobotWorld& world,int robot,WorldPlannerSettings* settings)
{
  if(linkCollisions.empty()) {
    linkIndices.resize(world.robots[robot]->links.size());
    linkCollisions.resize(world.robots[robot]->links.size());
    for(size_t i=0;i<world.robots[robot]->links.size();i++) {
      linkIndices[i].first = (int)i;
      linkIndices[i].second = -1;
    }
    vector<pair<int,int> > pairs;
    settings->EnumerateCollisionPairs(world,pairs);
    for(size_t i=0;i<pairs.size();i++) {
      pair<int,int> l1,l2;
      l1 = world.IsRobotLink(pairs[i].first);
      l2 = world.IsRobotLink(pairs[i].second);
      if(l1.first == robot && l1.second >= 0 && l2.first == robot && l2.second >= 0) { //involves two robot links
	linkIndices.push_back(pair<int,int>(l1.second,l2.second));
	linkCollisions.resize(linkCollisions.size()+1);
	settings->EnumerateCollisionQueries(world,pairs[i].first,pairs[i].second,linkCollisions.back());
      }
      else if(l1.first == robot && l1.second >= 0) {
	//find existing pair
	settings->EnumerateCollisionQueries(world,pairs[i].first,pairs[i].second,linkCollisions[l1.second]);
      }
      else if(l2.first == robot && l2.second >= 0) {
	settings->EnumerateCollisionQueries(world,pairs[i].first,pairs[i].second,linkCollisions[l2.second]);
      }
    }
    for(size_t i=0;i<linkCollisions.size();i++)
      printf("Collide link %d %d has %d elements to collide\n",linkIndices[i].first,linkIndices[i].second,linkCollisions[i].size());
    getchar();
  }
}
*/

void SingleRobotCSpace::GetJointLimits(Vector& bmin,Vector& bmax)
{
  bmin.resize(robot.links.size(),-Inf);
  bmax.resize(robot.links.size(),Inf);
  for(size_t i=0;i<robot.links.size();i++) {
    if(robot.joints[i].type == RobotJoint::Normal) {
      int k=robot.joints[i].linkIndex;
      bmin(k) = robot.qMin(k);
      bmax(k) = robot.qMax(k);
    }
    else if(robot.joints[i].type == RobotJoint::Spin) {
      int k=robot.joints[i].linkIndex;
      bmin(k) = 0;
      bmax(k) = TwoPi;
    }
  }
  /* TODO: driver limits
  robot.UpdateConfig(x);
  for(size_t i=0;i<robot.drivers.size();i++) {
    Real v=robot.GetDriverValue(i);
    jointLimitDist = Min(jointLimitDist,v-robot.drivers[i].qmin);
    jointLimitDist = Min(jointLimitDist,robot.drivers[i].qmax-v);
  }
  */
}

void SingleRobotCSpace::Properties(PropertyMap& map)
{
  RobotCSpace::Properties(map);
  if(!fixedDofs.empty()) {
    int dim;
    if(map.get("intrinsicDimension",dim))
      ;
    else {
      dim = robot.q.n;
      dim -= fixedDofs.size();
    }
    map.set("intrinsicDimension",dim);
    Real v;
    map.get("volume",v);
    vector<Real> minimum,maximum;
    map.getArray("minimum",minimum);
    map.getArray("maximum",maximum);
    for(size_t i=0;i<fixedDofs.size();i++) {
      int k=fixedDofs[i];
      if(robot.qMax[k] != robot.qMin[k])
	v /= (robot.qMax[k]-robot.qMin[k]);
      minimum[k] = maximum[k] = fixedValues[i];
    }
    map.set("volume",v);
    map.setArray("minimum",minimum);
    map.setArray("maximum",maximum);
  }
}

SingleRigidObjectCSpace::SingleRigidObjectCSpace(RobotWorld& _world,int _index,WorldPlannerSettings* _settings)
  :SE3CSpace(_settings->objectSettings[_index].worldBounds.bmin,_settings->objectSettings[_index].worldBounds.bmax),
  world(_world),index(_index),settings(_settings),constraintsDirty(true)
{
  Assert(settings != NULL);
  if(settings->objectSettings[index].translationWeight != 1.0)
    fprintf(stderr,"SingleRigidObjectCSpace: translation distance weight is not 1\n");
  SE3CSpace::SetAngleWeight(settings->objectSettings[index].rotationWeight);

  Init();
}

RigidObject* SingleRigidObjectCSpace::GetObject() const
{
  return world.rigidObjects[index];
}

void SingleRigidObjectCSpace::IgnoreCollisions(int id)
{
  for(size_t i=0;i<collisionPairs.size();i++) {
    if(collisionPairs[i].second == id) {
      collisionPairs[i] = collisionPairs.back();
      collisionPairs.resize(collisionPairs.size()-1);
      collisionQueries[i] = collisionQueries.back();
      collisionQueries.resize(collisionQueries.size()-1);
    }
  }
}

void SingleRigidObjectCSpace::Init()
{
  if(!constraintsDirty) return;
  MultiCSpace::FlattenConstraints();
  constraints.resize(3);
  constraintNames.resize(3);

  CSet::CPredicate f = boost::bind1st(std::mem_fun(&SingleRigidObjectCSpace::UpdateGeometry),this);
  CSpace::AddConstraint("update_geometry",f);

  if(collisionPairs.empty()) {
    int id = world.RigidObjectID(index);
    settings->EnumerateCollisionQueries(world,id,-1,collisionPairs,collisionQueries);
  }

  for(size_t i=0;i<collisionPairs.size();i++)
  {
    stringstream ss;
    ss<<"coll["<<world.GetName(collisionPairs[i].first)<<","<<world.GetName(collisionPairs[i].second)<<"]";
    CSpace::AddConstraint(ss.str(),new CollisionFreeSet(collisionQueries[i]));
  }
  constraintsDirty = false;
}

bool SingleRigidObjectCSpace::UpdateGeometry(const Config& q)
{
  RigidTransform T;
  SE3CSpace::GetTransform(q,GetObject()->T);
  GetObject()->UpdateGeometry();
  return true;
}

EdgePlanner* SingleRigidObjectCSpace::PathChecker(const Config& a,const Config& b)
{
  return new EpsilonEdgeChecker(this,a,b,settings->objectSettings[index].collisionEpsilon);
}


text:
title: Apache Mesos - CMake
layout: documentation
---

# Install CMake 3.7+

[cmake-download]: https://cmake.org/download/

## Linux

Install the latest version of CMake from [CMake.org][cmake-download].
A self-extracting tarball is available to make this process painless.

Currently, few of the common Linux flavors package a sufficient CMake
version. Ubuntu versions 12.04 and 14.04 package CMake 2;
Ubuntu 16.04 packages CMake 3.5. If you already installed cmake from packages,
you may remove it via: `apt-get purge cmake`.

The standard CentOS package is CMake 2, and unfortunately even the `cmake3`
package in EPEL is only CMake 3.6, you may remove them via:
`yum remove cmake cmake3`.

## Mac OS X

HomeBrew's CMake version is sufficient: `brew install cmake`.

## Windows

Download and install the MSI from [CMake.org][cmake-download].

**NOTE:** Windows needs CMake 3.8+, rather than 3.7+.

# Supported options

See [configuration options](configuration/cmake.md).

# Examples

See [CMake By Example](cmake-examples.md).

# Documentation

The [CMake documentation][] is written as a reference module. The most commonly
used sections are:

* [buildsystem overview](https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html)
* [commands](https://cmake.org/cmake/help/latest/manual/cmake-commands.7.html)
* [properties](https://cmake.org/cmake/help/latest/manual/cmake-properties.7.html)
* [variables](https://cmake.org/cmake/help/latest/manual/cmake-variables.7.html)

The wiki also has a set of [useful variables][].

[CMake documentation]: https://cmake.org/cmake/help/latest/
[useful variables]: https://cmake.org/Wiki/CMake_Useful_Variables

# Dependency graph

Like any build system, CMake has a dependency graph. The difference is
that targets in CMake's dependency graph are _much richer_ compared to other
build systems. CMake targets have the notion of 'interfaces', where build
properties are saved as part of the target, and these properties can be
inherited transitively within the graph.

For example, say there is a library `mylib`, and anything which links it must
include its headers, located in `mylib/include`. When building the library, some
private headers must also be included, but not when linking to it. When
compiling the executable `myprogram`, `mylib`'s public headers must be included,
but not its private headers. There is no manual step to add `mylib/include` to
`myprogram` (and any other program which links to `mylib`), it is instead
deduced from the public interface property of `mylib`. This is represented by
the following code:

```
# A new library with a single source file (headers are found automatically).
add_library(mylib mylib.cpp)

# The folder of private headers, not exposed to consumers of `mylib`.
target_include_directories(mylib PRIVATE mylib/private)

# The folder of public headers, added to the compilation of any consumer.
target_include_directories(mylib PUBLIC mylib/include)

# A new exectuable with a single source file.
add_executable(myprogram main.cpp)

# The creation of the link dependency `myprogram` -> `mylib`.
target_link_libraries(myprogram mylib)

# There is no additional step to add `mylib/include` to `myprogram`.
```

This same notion applies to practically every build property:
compile definitions via [`target_compile_definitions`][],
include directories via [`target_include_directories`][],
link libraries via [`target_link_libraries`][],
compile options via [`target_compile_options`][],
and compile features via [`target_compile_features`][].

All of these commands also take an optional argument of
`<INTERFACE|PUBLIC|PRIVATE>`, which constrains their transitivity in the graph.
That is, a `PRIVATE` include directory is recorded for the target, but not
shared transitively to anything depending on the target, `PUBLIC` is used
for both the target and dependencies on it, and `INTERFACE` is used only
for dependencies.

Notably missing from this list are link directories. CMake explicitly prefers
finding and using the absolute paths to libraries, obsoleting link directories.

[`target_compile_definitions`]: https://cmake.org/cmake/help/latest/command/target_compile_definitions.html
[`target_include_directories`]: https://cmake.org/cmake/help/latest/command/target_include_directories.html
[`target_link_libraries`]: https://cmake.org/cmake/help/latest/command/target_link_libraries.html
[`target_compile_options`]: https://cmake.org/cmake/help/latest/command/target_compile_options.html
[`target_compile_features`]: https://cmake.org/cmake/help/latest/command/target_compile_features.html

# Common mistakes

## Booleans

CMake treats `ON`, `OFF`, `TRUE`, `FALSE`, `1`, and `0` all as true/false
booleans. Furthermore, variables of the form `<target>-NOTFOUND` are also
treated as false (this is used for finding packages).

In Mesos, we prefer the boolean types `TRUE` and `FALSE`.

See [`if`](https://cmake.org/cmake/help/latest/command/if.html) for more info.

## Conditionals

For historical reasons, CMake conditionals such as `if` and `elseif`
automatically interpolate variable names. It is therefore dangerous to
interpolate them manually, because if `${FOO}` evaluates to `BAR`, and `BAR` is
another variable name, then `if (${FOO})` becomes `if (BAR)`, and `BAR` is then
evaluated again by the `if`. Stick to `if (FOO)` to check the value of `${FOO}`.
Do not use `if (${FOO})`.

Also see the CMake policies
[CMP0012](https://cmake.org/cmake/help/latest/policy/CMP0012.html) and
[CMP0054](https://cmake.org/cmake/help/latest/policy/CMP0054.html).

## Definitions

When using `add_definitions()` (which should be used rarely, as it is for
"global" compile definitions), the flags must be prefixed with `-D` to be
treated as preprocessor definitions. However, when using
`target_compile_definitions()` (which should be preferred, as it is
for specific targets), the flags do not need the prefix.

# Style

In general, wrap at 80 lines, and use a two-space indent. When wrapping
arguments, put the command on a separate line and arguments on subsequent lines:

```
target_link_libraries(
  program PRIVATE
  alpha
  beta
  gamma)
```

Otherwise keep it together:

```
target_link_libraries(program PUBLIC library)
```

Always keep the trailing parenthesis with the last argument.

Use a single space between conditionals and their open parenthesis, e.g.
`if (FOO)`, but not for commands, e.g. `add_executable(program)`.

CAPITALIZE the declaration and use of custom functions and macros (e.g.
`EXTERNAL` and `PATCH_CMD`), and do not capitalize the use of CMake built-in
(including modules) functions and macros. CAPITALIZE variables.

# CMake anti-patterns

[anti-patterns]: http://voices.canonical.com/jussi.pakkanen/2013/03/26/a-list-of-common-cmake-antipatterns/

Because CMake handles much more of the grunt work for you than other build
systems, there are unfortunately a lot of CMake [anti-patterns][] you should
look out for when writing new CMake code. These are some common problems
that should be avoided when writing new CMake code:

## Superfluous use of `add_dependencies`

When you've linked library `a` to library `b` with `target_link_libraries(a b)`,
the CMake graph is already updated with the dependency information. It is
redundant to use `add_dependencies(a b)` to (re)specify the dependency. In fact,
this command should _rarely_ be used.

The exceptions to this are:

  1. Setting a dependency from an imported library to a target added via
     `ExternalProject_Add`.
  2. Setting a dependency on Mesos modules since no explicit linking is done.
  3. Setting a dependency between executables (e.g. the `mesos-agent` requiring the
     `mesos-containerizer` executable). In general, runtime dependencies need
     to be setup with `add_dependency`, but never link dependencies.

## Use of `link_libraries` or `link_directories`

Neither of these commands should ever be used. The only appropriate command used
to link libraries is [`target_link_libraries`][], which records the information
in the CMake dependency graph. Furthermore, imported third-party libraries
should have correct locations recorded in their respective targets, so the use
of `link_directories` should never be necessary. The
[official documentation][link-directories] states:

> Note that this command is rarely necessary. Library locations returned by
> `find_package()` and `find_library()` are absolute paths. Pass these absolute
> library file paths directly to the `target_link_libraries()` command. CMake
> will ensure the linker finds them.

[link-directories]: https://cmake.org/cmake/help/latest/command/link_directories.html

The difference is that the former sets global (or directory level) side effects,
and the latter sets specific target information stored in the graph.

## Use of `include_directories`

This is similar to the above: the [`target_include_directories`][] should always
be preferred so that the include directory information remains localized to the
appropriate targets.

## Adding anything to `endif ()`

Old versions of CMake expected the style `if (FOO) ... endif (FOO)`, where the
`endif` contained the same expression as the `if` command. However, this is
tortuously redundant, so leave the parentheses in `endif ()` empty. This goes
for other endings too, such as `endforeach ()`, `endwhile ()`, `endmacro ()` and
`endfunction ()`.

## Specifying header files superfluously

One of the distinct advantages of using CMake for C and C++ projects is that
adding header files to the source list for a target is unnecessary. CMake is
designed to parse the source files (`.c`, `.cpp`, etc.) and determine their
required headers automatically. The exception to this is headers generated as
part of the build (such as protobuf or the JNI headers).

## Checking `CMAKE_BUILD_TYPE`

See the ["Building debug or release configurations"][config] example for more
information. In short, not all generators respect the variable
`CMAKE_BUILD_TYPE` at configuration time, and thus it must not be used in CMake
logic. A usable alternative (where supported) is a [generator expression][] such
as `$<$<CONFIG:Debug>:DEBUG_MODE>`.

[config]: cmake-examples.md#building-debug-or-release-configurations
[generator expression]: https://cmake.org/cmake/help/latest/manual/cmake-generator-expressions.7.html#logical-expressions

# Remaining hacks

## `3RDPARTY_DEPENDENCIES`

Until Mesos on Windows is stable, we keep some dependencies in an external
repository, [mesos-3rdparty](https://github.com/3rdparty/mesos-3rdparty). When
all dependencies are bundled with Mesos, this extra repository will no longer be
necessary. Until then, the CMake variable `3RDPARTY_DEPENDENCIES` points by
default to this URL, but it can also point to the on-disk location of a local
clone of the repo. With this option you can avoid pulling from GitHub for every
clean build.

## `EXTERNAL`

The CMake function `EXTERNAL` defines a few variables that make it easy for us
to track the directory structure of a dependency. In particular, if our
library's name is `boost`, we invoke:

```
EXTERNAL(boost ${BOOST_VERSION} ${CMAKE_CURRENT_BINARY_DIR})
```

Which will define the following variables as side-effects in the current scope:

* `BOOST_TARGET`     (a target folder name to put dep in e.g., `boost-1.53.0`)
* `BOOST_CMAKE_ROOT` (where to have CMake put the uncompressed source, e.g.,
                     `build/3rdparty/boost-1.53.0`)
* `BOOST_ROOT`       (where the code goes in various stages of build, e.g.,
                     `build/.../boost-1.53.0/src`, which might contain folders
                     `build-1.53.0-build`, `-lib`, and so on, for each build
                     step that dependency has)

The implementation is in `3rdparty/cmake/External.cmake`.

This is not to be confused with the CMake module [ExternalProject][], from which
we use `ExternalProject_Add` to download, extract, configure, and build our
dependencies.

[ExternalProject]: https://cmake.org/cmake/help/latest/module/ExternalProject.html

## `CMAKE_NOOP`

This is a CMake variable we define in `3rdparty/CMakeLists.txt` so that we can
cancel steps of `ExternalProject`. `ExternalProject`'s default behavior is to
attempt to configure, build, and install a project using CMake. So when one of
these steps must be skipped, we use set it to `CMAKE_NOOP` so that nothing
is run instead.

## `CMAKE_FORWARD_ARGS`

The `CMAKE_FORWARD_ARGS` variable defined in `3rdparty/CMakeLists.txt` is sent
as the `CMAKE_ARGS` argument to the `ExternalProject_Add` macro (along with any
per-project arguments), and is used when the external project is configured as a
CMake project. If either the `CONFIGURE_COMMAND` or `BUILD_COMMAND` arguments of
`ExternalProject_Add` are used, then the `CMAKE_ARGS` argument will be ignored.
This variable ensures that compilation configurations are properly propagated to
third-party dependencies, such as compiler flags.

### `CMAKE_SSL_FORWARD_ARGS`

The `CMAKE_SSL_FORWARD_ARGS` variable defined in `3rdparty/CMakeLists.txt`
is like `CMAKE_FORWARD_ARGS`, but only used for specific external projects
that find and link against OpenSSL.

## `LIBRARY_LINKAGE`

This variable is a shortcut used in `3rdparty/CMakeLists.txt`. It is set to
`SHARED` when `BUILD_SHARED_LIBS` is true, and otherwise it is set to `STATIC`.
The `SHARED` and `STATIC` keywords are used to declare how a library should be
built; however, if left out then the type is deduced automatically from
`BUILD_SHARED_LIBS`.

## `MAKE_INCLUDE_DIR`

This function works around a [CMake issue][cmake-15052] with setting include
directories of imported libraries built with `ExternalProject_Add`. We have to
call this for each `IMPORTED` third-party dependency which has set
`INTERFACE_INCLUDE_DIRECTORIES`, just to make CMake happy. An example is Glog:

```
MAKE_INCLUDE_DIR(glog)
```

[cmake-15052]: https://gitlab.kitware.com/cmake/cmake/issues/15052

## `GET_BYPRODUCTS`

This function works around a [CMake issue][cmake-060234] with the Ninja
generator where it does not understand imported libraries, and instead needs
`BUILD_BYPRODUCTS` explicitly set. This simply allows us to use
`ExternalProject_Add` and Ninja. For Glog, it looks like this:

```
GET_BYPRODUCTS(glog)
```

Also see the CMake policy [CMP0058][].

[cmake-060234]: https://cmake.org/pipermail/cmake/2015-April/060234.html
[CMP0058]: https://cmake.org/cmake/help/latest/policy/CMP0058.html

## `PATCH_CMD`

The CMake function `PATCH_CMD` generates a patch command given a patch file.
If the path is not absolute, it's resolved to the current source directory.
It stores the command in the variable name supplied. This is used to easily
patch third-party dependencies. For Glog, it looks like this:

```
PATCH_CMD(GLOG_PATCH_CMD glog-${GLOG_VERSION}.patch)
ExternalProject_Add(
  ${GLOG_TARGET}
  ...
  PATCH_COMMAND     ${GLOG_PATCH_CMD})
```

The implementation is in `3rdparty/cmake/PatchCommand.cmake`.

### Windows `patch.exe`

While using `patch` on Linux is straightforward, doing the same on Windows takes
a bit of work. `PATH_CMD` encapsulates this:

* Checks the cache variable `PATCHEXE_PATH` for `patch.exe`.
* Searches for `patch.exe` in its default locations.
* Copies `patch.exe` and a custom manifest to the temporary directory.
* Applies the manifest to avoid the UAC prompt.
* Uses the patched `patch.exe`.

As such, `PATCH_CMD` lets us apply patches as we do on Linux, without requiring
an administrative prompt.

Note that on Windows, the patch file must have CRLF line endings. A file with LF
line endings will cause the error: "Assertion failed, hunk, file patch.c, line
343". For this reason, it is required to checkout the Mesos repo with `git
config core.autocrlf true`.


text:
package de._2d6.scalaviz.graph

/**
  * The mode with which a [[Graph]] should be rendered
  */
sealed trait GraphMode {

  /**
    * Validate the given graph.
    * @throws IllegalArgumentException if the graph does not conform to this mode
    * @param graph The graph to validate
    */
  def validate(graph: Graph): Unit
}

/**
  * The mode with which a [[Graph]] should be rendered
  */
object GraphMode {

  /**
    * The default mode, allowing unconnected [[Node]]s within the [[Graph]]
    */
  case object Default extends GraphMode {

    override def validate(graph: Graph): Unit = {
      // Default graphs do not need mode validation
    }
  }

  /**
    * Strict mode, prohibiting unconnected [[Node]]s within the [[Graph]]
    */
  case object Strict extends GraphMode {

    override def validate(graph: Graph): Unit = {
      val connectedNodes = graph.edges.flatMap(edge => Seq(edge.from, edge.to))
      val allNodesAreConnected = graph.nodes.forall(connectedNodes.contains)
      require(allNodesAreConnected, "Graphs with strict mode must not contain unconnected nodes")
    }
  }

}


text:
Titanium.UI.setBackgroundColor("#000");

Titanium.UI.setBackgroundImage("/images/bgImage.png");

var win = Titanium.UI.currentWindow;

var btnBack = Ti.UI.createButton({
    title: L("NavButton_back")
});

win.leftNavButton = btnBack;

btnBack.addEventListener("click", function() {
    win.close();
});

var pWidth = Ti.Platform.displayCaps.platformWidth;

var pHeight = Ti.Platform.displayCaps.platformHeight;

var win1 = Titanium.UI.createWindow({
    url: "/windows/WmsMetadata.js",
    title: L("WmsMetadata_win_title"),
    modal: true,
    backgroundImage: "/images/bgImage.png"
});

win1.padre = win.padre;

var win2 = Titanium.UI.createWindow({
    url: "/windows/LayerMetadata.js",
    title: L("LayerMetadata_win_title"),
    modal: true,
    backgroundImage: "/images/bgImage.png"
});

win2.padre = win.padre;

var tblWmsServer = Titanium.UI.createTableView({
    width: pWidth - 20,
    height: pHeight - 110,
    top: 20,
    left: 10,
    backgroundColor: "#B0C4DE",
    borderRadius: 12,
    borderColor: "#AFEEEE",
    borderWidth: 2,
    minRowHeight: 80
});

var sectionMetadata = Ti.UI.createTableViewSection({
    headerTitle: L("WmsServer_section1_title")
});

var row = Titanium.UI.createTableViewRow({
    width: tblWmsServer.width,
    height: 80,
    className: "metadata-row"
});

var titleRow = Titanium.UI.createLabel({
    text: L("WmsServer_row1_title"),
    font: {
        fontSize: 22,
        fontWeight: "bold"
    },
    color: "#000",
    left: 10,
    top: 20,
    width: row.width - 20,
    height: "auto"
});

var iconImage = Titanium.UI.createImageView({
    image: "/images/next.png",
    width: 48,
    height: 48,
    right: 10,
    top: 20
});

row.add(titleRow);

row.add(iconImage);

sectionMetadata.add(row);

var sectionLayers = Ti.UI.createTableViewSection({
    headerTitle: L("WmsServer_section2_title")
});

var xmlData = Titanium.XML.parseString(win.xmlText);

win1.xml = xmlData;

win2.xml = xmlData;

layer = xmlData.documentElement.getElementsByTagName("Layer");

for (var i = 0; layer.length > i; i++) {
    var row = Titanium.UI.createTableViewRow({
        width: tblWmsServer.width,
        height: "auto",
        className: "layer-row"
    });
    var descriptionRow = Titanium.UI.createLabel({
        text: layer.item(i).getElementsByTagName("Title").item(0).textContent,
        font: {
            fontSize: 20,
            fontWeight: "bold"
        },
        color: "#000",
        left: 10,
        top: 10,
        width: row.width - 70,
        height: "auto"
    });
    var iconImage = Titanium.UI.createImageView({
        image: "/images/next.png",
        width: 48,
        height: 48,
        right: 10,
        top: 20
    });
    row.add(descriptionRow);
    row.add(iconImage);
    sectionLayers.add(row);
}

tblWmsServer.data = [ sectionMetadata, sectionLayers ];

win.add(tblWmsServer);

tblWmsServer.addEventListener("click", function(e) {
    if (0 == e.index) true == Ti.App.isAndroid ? win1.open() : win.padre.openWindow(win1); else {
        win2.rowID = e.index;
        true == Ti.App.isAndroid ? win2.open() : win.padre.openWindow(win2);
    }
});


text:
export declare class Tree<T> {
    constructor(root: TreeNode<T>);
    root: T;
    /**
     * @deprecated (use ActivatedRoute.parent instead)
     */
    parent(t: T): T;
    /**
     * @deprecated (use ActivatedRoute.children instead)
     */
    children(t: T): T[];
    /**
     * @deprecated (use ActivatedRoute.firstChild instead)
     */
    firstChild(t: T): T;
    /**
     * @deprecated
     */
    siblings(t: T): T[];
    /**
     * @deprecated (use ActivatedRoute.pathFromRoot instead)
     */
    pathFromRoot(t: T): T[];
}
export declare class TreeNode<T> {
    value: T;
    children: TreeNode<T>[];
    constructor(value: T, children: TreeNode<T>[]);
    toString(): string;
}


text:
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {GameReference} from "../../../../../../models/dto/game-reference";
import {Subscription} from "rxjs/Subscription";
import {Observable} from "rxjs/Observable";
import {RatelimitedRequestsService} from "../../../../../../services/ratelimited-requests.service";
import {GameApiService} from "../../../../../../services/game-api.service";
import {ResType} from "../../../../../../enums/api-response-type";
import {Summoner} from "../../../../../../models/dto/summoner";
import {GameRecordPersonalised} from "../../../../../../models/game-record-personalised";
import {GameRecord} from "../../../../../../models/dto/game-record";
import {ChampionsContainer} from "../../../../../../models/dto/containers/champions-container";
import {ItemsContainer} from "../../../../../../models/dto/containers/items-container";
import {SummonerspellsContainer} from "../../../../../../models/dto/containers/summonerspells-container";
import {TranslatorService} from "../../../../../../services/translator.service";
import {Champion} from "../../../../../../models/dto/champion";

@Component({
  selector: 'previous-games',
  templateUrl: './previous-games.component.html',
  styleUrls: ['./previous-games.component.scss']
})
export class PreviousGamesComponent implements OnInit {

  @Input() summoner: Summoner; // Required
  @Input() slice_of_gamehistory: Array<GameReference>; // Required
  @Input() limit: number = null; // Optional; First N games

  // Metadata
  @Input() champions: ChampionsContainer;
  @Input() items: ItemsContainer;
  @Input() summonerspells: SummonerspellsContainer;

  // State output
  @Output() loadStart: EventEmitter<boolean> = new EventEmitter();
  @Output() loaded: EventEmitter<boolean> = new EventEmitter();

  private ongoing_request: Subscription = null;
  private days_ago_collections = null;
  private error = '';
  private champion_id_filter = null;

  // Utils
  private gettext: Function;
  private Math = Math;

  constructor(private buffered_requests: RatelimitedRequestsService,
              private game_api: GameApiService,
              private translator: TranslatorService) {
    this.gettext = this.translator.getTranslation;
  }

  private getTimeAgoAsString(date: Date) {

    let time_difference_ms = new Date().getTime() - date.getTime(); // now - then
    let local_yesterday_begin = ((new Date()).getHours() + 24) * 1000 * 60 * 60; // (Hours today + 24 hours) earlier

    if (time_difference_ms < 1000*60*60*24) {
      // Less-than-day ago
      let full_hours_ago = Math.floor(time_difference_ms / (1000*60*60));
      if (full_hours_ago == 0) {
        // Count minutes instead
        let full_minutes_ago = Math.floor(time_difference_ms / (1000*60));
        if (full_minutes_ago == 0) {
          return `${this.gettext("just_now")}`;
        }
        if (full_minutes_ago == 1) {
          return `1 ${this.gettext("minute_ago")}`;
        }
        // Else
        return `${full_minutes_ago} ${this.gettext("n_minutes_ago")}`;
      }
      if (full_hours_ago == 1) {
        return `1  ${this.gettext("hour_ago")}`;
      }
      // Else
      return `${full_hours_ago} ${this.gettext("n_hours_ago")}`;

    } else if (time_difference_ms < local_yesterday_begin) {
      // Since (local-/browsertime) "yesterday" began
      return this.gettext("yesterday");

    } else {
      // DD. MM. YYYY
      return ("0"+date.getDate()).slice(-2) + '.' + ("0"+(date.getMonth()+1)).slice(-2) + '.' + date.getFullYear();
    }
  }

  private getDaysAgoAsString(collection) {
    let nr_of_days = collection.days_ago;
    if (nr_of_days === 0) {
      return this.gettext("today");
    } else if (nr_of_days === 1) {
      return this.gettext("yesterday");
    } else {
      if (collection.contents.length === 1) {
        return nr_of_days.toString() + ' ' + this.gettext("days_ago").slice(0,1) + '..';
      } else {
        return nr_of_days.toString() + ' ' + this.gettext("days_ago");
      }
    }
  }

  private getPlayedChampionsNameOrdered(): Array<Champion> {
    let played_champions = this.slice_of_gamehistory.map(gameref => gameref.chosen_champion.id)
      .filter((id, idx, self) => self.indexOf(id) === idx); // Filter unique, like set(<list>) in python
    return this.champions.listChampions()
      .filter(champion => played_champions.indexOf(champion.id) !== -1)
      .sort((a,b) => a.name.localeCompare(b.name));
  }

  private loadPreviousGames(opt_champion_id_filter?, opt_role_filter?) {
    // Cancel if any unfinished ongoing requests
    if (this.ongoing_request && !this.ongoing_request.closed) {
      return;
    }

    // If champion-filter is set then apply it
    let gamereferences = opt_champion_id_filter ?
      this.slice_of_gamehistory.filter(gameref => gameref.chosen_champion.id.toString() === opt_champion_id_filter)
      : this.slice_of_gamehistory;

    // If role-filter is set then apply it
    gamereferences = opt_role_filter ?
      gamereferences.filter(gameref => gameref.presumed_lane === opt_role_filter)
      : gamereferences;

    // If limit is set then apply it -> first N gamereferences
    gamereferences = this.limit ? gamereferences.slice(0, this.limit) : gamereferences;

    if (gamereferences.length === 0) {
      this.days_ago_collections = [];
      return;
    }

    // Start loading (optionally limited) game details
    this.loadStart.emit(true);
    this.ongoing_request = Observable.forkJoin(
      gamereferences.map((gameref: GameReference) => this.buffered_requests.buffer(() => {
        return this.game_api.getHistoricalGame(gameref.region, gameref.game_id);
      }))
    )
      .subscribe(game_api_responses => {
        if (game_api_responses.every(api_res => api_res.type == ResType.SUCCESS)) {
          let game_details = [];
          for (let i=0; i<gamereferences.length; i++) {
            game_details.push(new GameRecordPersonalised(
              (<GameRecord> game_api_responses[i].data).raw_origin,
              this.summoner,
              this.champions,
              this.items,
              this.summonerspells
            ));
          }

          let time_now = (new Date()).getTime();
          let time_since_daybreak = (new Date()).getHours() * 1000 * 60 * 60; // Hour accuracy
          this.days_ago_collections = game_details.reduce((days_ago_collections, g, i) => {
            // Parse the [today: [matches], yesterday: [matches], etc.] times
            let time_then = g.match_start_time.getTime();
            let happened_today = (time_now - time_then - time_since_daybreak) <= 0;
            let days_ago = happened_today ? 0 : Math.ceil((time_now - time_then - time_since_daybreak) / (1000*60*60*24));
            let collection = days_ago_collections.find(coll => coll.days_ago === days_ago);
            if (!collection) {
              collection = {
                days_ago: days_ago,
                contents: []
              };
              days_ago_collections.push(collection);
            }
            // Parse match itself
            let player_itself = g.teams.ally.players.find(p => p.is_the_target);
            collection.contents.push({
              player_as_participant: player_itself,
              role: gamereferences[i].presumed_lane,
              victory: g.teams.ally.stats.isWinningTeam,
              start_time: g.match_start_time,
              duration: g.match_duration_seconds,
              nr_carry: g.teams.ally.players
                .sort((p1,p2) => p2.stats.combat_totals.damage_dealt_vs_champions.all - p1.stats.combat_totals.damage_dealt_vs_champions.all)
                .map(p => p.summoner.id)
                .indexOf(this.summoner.id)+1,
              kda: player_itself.stats.kda.kills + '/' + player_itself.stats.kda.deaths + '/' + player_itself.stats.kda.assists,
              cs_lane: player_itself.stats.creeps.lane,
              cs_jungle: player_itself.stats.creeps.jungle,
              cs_at_ten: player_itself.stats.timeline.cs_at_ten
            });
            return days_ago_collections;
          }, []);
        } else {
          this.error = 'Something went wrong when requesting game details.';
        }
        this.loaded.emit(true);
      });
  }

  ngOnInit() {
    this.loadPreviousGames();
  }

}


text:
#ifndef QWAYLANDXCOMPOSITEBUFFER_H
#define QWAYLANDXCOMPOSITEBUFFER_H

#include "qwaylandbuffer.h"

#include "wayland-xcomposite-client-protocol.h"

class QWaylandXCompositeBuffer : public QWaylandBuffer
{
public:
    QWaylandXCompositeBuffer(struct wl_xcomposite *xcomposite,
                             uint32_t window,
                             const QSize &size,
                             struct wl_visual *visual);

    QSize size() const;
private:
    QSize mSize;
};

#endif // QWAYLANDXCOMPOSITEBUFFER_H


text:
package pixiv

import (
	"testing"

	"github.com/stretchr/testify/require"
)

func TestParsePixivURL(t *testing.T) {
	ret := ParseURL("♥ | NARU #pixiv https://www.pixiv.net/artworks/97336690")
	require.Equal(t, uint64(97336690), ret)
}


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

using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.Compute.Common;
using Microsoft.Azure.Commands.Compute.Extension.AzureDiskEncryption;
using Microsoft.Azure.Commands.Compute.StorageServices;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.Storage;
using Microsoft.WindowsAzure.Commands.Sync.Download;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Commands.Sync.Upload;

namespace Microsoft.Azure.Commands.Compute.Extension.AzureVMBackup
{
    /// <summary>
    /// Used to create/remove snapshots of the disk page blobs of the specified virtual machines.
    /// </summary>
    public class AzureVMBackupExtensionUtil
    {
        public const string extensionPublisher = "Microsoft.Azure.Security";
        public const string extensionType = "VMBackupForLinuxExtension";
        public const string extensionDefaultVersion = "0.1";
        public const string backupExtensionName = "vmbackupextension";
        public const string backupExtensionMetadataName = "vmbackuptag";
        public const string backupExtensionIdentityMetadataName = "vmbackupidentity";
        public const string backupSnapshotCommand = "snapshot";
        public const string backupDefaultLocale = "en-us";

        private List<string> GetDiskBlobUris(VirtualMachine virtualMachineResponse)
        {
            List<string> blobUris = new List<string>();
            string osDiskUri = virtualMachineResponse.StorageProfile.OsDisk.Vhd.Uri;
            blobUris.Add(osDiskUri);
            var dataDisks = virtualMachineResponse.StorageProfile.DataDisks;
            for (int i = 0; i < dataDisks.Count; i++)
            {
                blobUris.Add(dataDisks[i].Vhd.Uri);
            }
            return blobUris;
        }

        private string GetBase64Encoding(object obj)
        {
            string plainText = JsonConvert.SerializeObject(obj);
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
            string base64EncodedPrivateConfig = System.Convert.ToBase64String(plainTextBytes);
            return base64EncodedPrivateConfig;
        }

        /// <summary>
        /// find the snapshot with the tags
        /// </summary>
        /// <param name="blobUris"></param>
        /// <param name="snapshotTag"></param>
        /// <param name="taskId"></param>
        /// <param name="storageCredentialsFactory"></param>
        /// <returns></returns>
        public List<CloudPageBlob> FindSnapshot(IAzureContext azContext, List<string> blobUris, List<StorageCredentialsFactory> storageCredentialsFactory, Dictionary<string, string> snapshotQuery)
        {
            List<CloudPageBlob> snapshots = new List<CloudPageBlob>();
            for (int i = 0; i < blobUris.Count; i++)
            {
                BlobUri blobUri = null;
                if (BlobUri.TryParseUri(new Uri(blobUris[i]), out blobUri))
                {
                    StorageCredentials sc = storageCredentialsFactory[i].Create(blobUri);
                    CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(sc, azContext.Environment.GetEndpointSuffix(AzureEnvironment.Endpoint.StorageEndpointSuffix), true);
                    CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient();
                    CloudBlobContainer blobContainer = blobClient.GetContainerReference(blobUri.BlobContainerName);
                    IEnumerable<IListBlobItem> blobs = blobContainer.ListContainerBlobs(true, BlobListingDetails.All, null);
                    foreach (var blob in blobs)
                    {
                        if (blob is CloudPageBlob)
                        {
                            CloudPageBlob pageBlob = blob as CloudPageBlob;
                            if (pageBlob.IsSnapshot && pageBlob.Name == blobUri.BlobName)
                            {
                                bool allMatch = true;
                                foreach (string keyToQuey in snapshotQuery.Keys)
                                {
                                    if (!pageBlob.Metadata.Keys.Contains(keyToQuey))
                                    {
                                        allMatch = false;
                                    }
                                    else if (!string.Equals(pageBlob.Metadata[keyToQuey], snapshotQuery[keyToQuey]))
                                    {
                                        allMatch = false;
                                    }
                                }
                                if (allMatch)
                                {
                                    snapshots.Add(pageBlob);
                                }
                            }
                        }
                    }
                }
            }
            return snapshots;
        }

        internal string GetResourceGroupFromId(string id)
        {
            var matcher = new Regex("/subscriptions/([^/]+)/resourceGroups/([^/]+)/providers/(\\w+)");
            var result = matcher.Match(id);
            if (!result.Success || result.Groups == null || result.Groups.Count < 3)
            {
                throw new InvalidOperationException(string.Format("Cannot find resource group name and storage account name from resource identity {0}", id));
            }

            return result.Groups[2].Value;
        }

        public AzureVMBackupBlobSasUris GenerateBlobSasUris(List<string> blobUris, IAzureContext azContext)
        {
            AzureVMBackupBlobSasUris blobSASUris = new AzureVMBackupBlobSasUris();

            for (int i = 0; i < blobUris.Count; i++)
            {
                string blobUri = blobUris[i];
                BlobUri osBlobUri = null;
                if (BlobUri.TryParseUri(new Uri(blobUri), out osBlobUri))
                {
                    StorageManagementClient storageClient = AzureSession.Instance.ClientFactory.CreateArmClient<StorageManagementClient>(azContext, AzureEnvironment.Endpoint.ResourceManager);

                    // Need to convert osBlobUri.StorageAccountName into corresponding resource group name

                    var listResponse = storageClient.StorageAccounts.List();
                    var account = listResponse.First(accTemp => accTemp.Name.Equals(osBlobUri.StorageAccountName, StringComparison.InvariantCultureIgnoreCase));
                    string resourceGroupName = GetResourceGroupFromId(account.Id);

                    StorageCredentialsFactory storageCredentialsFactory = new StorageCredentialsFactory(resourceGroupName, storageClient, azContext.Subscription);

                    CloudPageBlobObjectFactory cloudPageBlobObjectFactory = new CloudPageBlobObjectFactory(storageCredentialsFactory, TimeSpan.FromMinutes(1));

                    CloudPageBlob pageBlob = cloudPageBlobObjectFactory.Create(osBlobUri);

                    SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy();
                    sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(5);
                    sasConstraints.Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.List;

                    string sasUri = osBlobUri.Uri + pageBlob.GetSharedAccessSignature(sasConstraints);
                    blobSASUris.blobSASUri.Add(sasUri);
                    blobSASUris.pageBlobUri.Add(blobUri);
                    blobSASUris.storageCredentialsFactory.Add(storageCredentialsFactory);
                }
                else
                {
                    throw new AzureVMBackupException(AzureVMBackupErrorCodes.WrongBlobUriFormat, "the blob uri is not in correct format.");
                }
            }
            return blobSASUris;
        }

        /// <summary>
        /// remove the vmbackups with the metadata  key "vmbackuptag" and value snapshotTag, snapshotTag is the parameter passed in.
        /// </summary>
        /// <param name="resourceGroupName"></param>
        /// <param name="vmName"></param>
        /// <param name="virtualMachineExtensionType"></param>
        /// <param name="location"></param>
        /// <param name="virtualMachineResponse"></param>
        /// <param name="profile"></param>
        /// <param name="VirtualMachineExtensionClient"></param>
        /// <param name="snapshotTag"></param>
        public void RemoveSnapshot(AzureVMBackupConfig vmConfig, string snapshotTag, VirtualMachineExtensionBaseCmdlet virtualMachineExtensionBaseCmdlet)
        {
            var virtualMachineResponse = virtualMachineExtensionBaseCmdlet.ComputeClient.ComputeManagementClient.VirtualMachines.GetWithInstanceView(vmConfig.ResourceGroupName, vmConfig.VMName);
            StorageManagementClient storageClient = AzureSession.Instance.ClientFactory.CreateArmClient<StorageManagementClient>(virtualMachineExtensionBaseCmdlet.DefaultProfile.DefaultContext, AzureEnvironment.Endpoint.ResourceManager);

            StorageCredentialsFactory storageCredentialsFactory = new StorageCredentialsFactory(vmConfig.ResourceGroupName, storageClient, virtualMachineExtensionBaseCmdlet.DefaultProfile.DefaultContext.Subscription);

            List<string> blobUris = this.GetDiskBlobUris(virtualMachineResponse.Body);
            AzureVMBackupBlobSasUris blobSASUris = this.GenerateBlobSasUris(blobUris, virtualMachineExtensionBaseCmdlet.DefaultProfile.DefaultContext);

            Dictionary<string, string> snapshotQuery = new Dictionary<string, string>();
            snapshotQuery.Add(backupExtensionMetadataName, snapshotTag);
            List<CloudPageBlob> snapshots = this.FindSnapshot(virtualMachineExtensionBaseCmdlet.DefaultProfile.DefaultContext, blobSASUris.pageBlobUri, blobSASUris.storageCredentialsFactory, snapshotQuery);
            if (snapshots == null || snapshots.Count == 0)
            {
                throw new AzureVMBackupException(AzureVMBackupErrorCodes.NoSnapshotFound, "snapshot with the tag not found.");
            }
            else
            {
                foreach (CloudPageBlob snapshot in snapshots)
                {
                    snapshot.DeleteAsync().ConfigureAwait(false).GetAwaiter().GetResult();
                }
            }
        }

        /// <summary>
        /// we only support the Linux box now, if it's a windows, one AzureVMBackupException would be thrown.
        /// </summary>
        /// <param name="resourceGroupName"></param>
        /// <param name="vmName"></param>
        /// <param name="virtualMachineExtensionType"></param>
        /// <param name="location"></param>
        /// <param name="virtualMachineResponse"></param>
        /// <param name="snapshotTag"></param>
        /// <param name="virtualMachineExtensionBaseCmdlet"></param>
        public void CreateSnapshotForDisks(AzureVMBackupConfig vmConfig, string snapshotTag, VirtualMachineExtensionBaseCmdlet virtualMachineExtensionBaseCmdlet)
        {
            var virtualMachine = virtualMachineExtensionBaseCmdlet.ComputeClient.ComputeManagementClient.VirtualMachines.GetWithInstanceView(
                vmConfig.ResourceGroupName,
                vmConfig.VMName);

            List<string> vmPageBlobUris = this.GetDiskBlobUris(virtualMachine.Body);

            AzureVMBackupBlobSasUris blobSASUris = this.GenerateBlobSasUris(vmPageBlobUris, virtualMachineExtensionBaseCmdlet.DefaultProfile.DefaultContext);

            string taskId = Guid.NewGuid().ToString();

            AzureVMBackupExtensionProtectedSettings privateConfig = new AzureVMBackupExtensionProtectedSettings();
            privateConfig.logsBlobUri = string.Empty;
            privateConfig.objectStr = this.GetBase64Encoding(blobSASUris);

            AzureVMBackupExtensionPublicSettings publicConfig = new AzureVMBackupExtensionPublicSettings();
            publicConfig.commandToExecute = backupSnapshotCommand;
            publicConfig.locale = backupDefaultLocale;
            publicConfig.commandStartTimeUTCTicks = DateTimeOffset.UtcNow.Ticks.ToString();
            publicConfig.taskId = taskId;
            AzureVMBackupMetadata backupMetadata = new AzureVMBackupMetadata();

            AzureVMBackupMetadataItem tagMetadataItem = new AzureVMBackupMetadataItem();
            tagMetadataItem.Key = backupExtensionMetadataName;
            tagMetadataItem.Value = snapshotTag;

            AzureVMBackupMetadataItem taskIdMetadataItem = new AzureVMBackupMetadataItem();
            taskIdMetadataItem.Key = backupExtensionIdentityMetadataName;
            taskIdMetadataItem.Value = taskId;

            backupMetadata.backupMetadata.Add(tagMetadataItem);
            backupMetadata.backupMetadata.Add(taskIdMetadataItem);

            publicConfig.objectStr = this.GetBase64Encoding(backupMetadata);

            VirtualMachineExtension vmExtensionParameters = new VirtualMachineExtension
            {
                Location = virtualMachine.Body.Location,
                Publisher = extensionPublisher,
                VirtualMachineExtensionType = extensionType,
                TypeHandlerVersion = extensionDefaultVersion,
                Settings = publicConfig,
                ProtectedSettings = privateConfig,
            };

            var vmBackupOperation = virtualMachineExtensionBaseCmdlet.VirtualMachineExtensionClient.CreateOrUpdate(
                vmConfig.ResourceGroupName,
                vmConfig.VMName,
                vmConfig.ExtensionName ?? backupExtensionName,
                vmExtensionParameters);

            // check the snapshots with the task id are all created.
            int timePeriod = 5000;
            int loopingTimes = ((int)TimeSpan.FromMinutes(10).TotalMilliseconds / timePeriod);

            Dictionary<string, string> snapshotQuery = new Dictionary<string, string>();
            snapshotQuery.Add(backupExtensionMetadataName, snapshotTag);
            snapshotQuery.Add(backupExtensionIdentityMetadataName, taskId);
            int i = 0;
            for (; i < loopingTimes; i++)
            {
                List<CloudPageBlob> snapshotsFound = this.FindSnapshot(virtualMachineExtensionBaseCmdlet.DefaultProfile.DefaultContext, blobSASUris.pageBlobUri, blobSASUris.storageCredentialsFactory, snapshotQuery);
                if (snapshotsFound.Count == vmPageBlobUris.Count)
                {
                    break;
                }
                else
                {
                    Thread.Sleep(timePeriod);
                }
            }
            if (i == loopingTimes)
            {
                throw new AzureVMBackupException(AzureVMBackupErrorCodes.TimeOut, "snapshot not created, or not found in time.");
            }
        }
    }
}


text:
{% extends "admin/base_site.html" %}
{% load i18n static %}

{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/dashboard.css" %}" />{% endblock %}

{% block coltype %}colMS{% endblock %}

{% block bodyclass %}{{ block.super }} dashboard{% endblock %}

{% block breadcrumbs %}{% endblock %}

{% block content %}

{% if app_list %}
    {# NOTE(willkg): This section is added to django admin index.html template. #}

            Management pages

                Test error handling

                Site statistics

    {# END SECTION #}

    {% for app in app_list %}

            {{ app.name }}

        {% for model in app.models %}

            {% if model.admin_url %}
                {{ model.name }}
            {% else %}
                {{ model.name }}
            {% endif %}

            {% if model.add_url %}
                {% trans 'Add' %}
            {% else %}

            {% endif %}

            {% if model.admin_url %}
                {% trans 'Change' %}
            {% else %}

            {% endif %}

        {% endfor %}

    {% endfor %}
{% else %}

{% trans "You don't have permission to edit anything." %}

{% endif %}

{% endblock %}

{% block sidebar %}

{% trans 'Recent actions' %}

{% trans 'My actions' %}

            {% load log %}
            {% get_admin_log 10 as admin_log for_user user %}
            {% if not admin_log %}

{% trans 'None available' %}

            {% else %}

            {% for entry in admin_log %}

                {% if entry.is_deletion or not entry.get_admin_url %}
                    {{ entry.object_repr }}
                {% else %}
                    {{ entry.object_repr }}
                {% endif %}

                {% if entry.content_type %}
                    {% filter capfirst %}{{ entry.content_type }}{% endfilter %}
                {% else %}
                    {% trans 'Unknown content' %}
                {% endif %}

            {% endfor %}

            {% endif %}

{% endblock %}


text:
package org.zstack.header.storage.snapshot;

/**
 */

import javax.persistence.metamodel.StaticMetamodel;

@StaticMetamodel(VolumeSnapshotVO.class)
public class VolumeSnapshotVO_ extends VolumeSnapshotAO_ {
}


text:
<?php

namespace Documents;

/**
 * @MappedSuperclass
 * @HasLifecycleCallbacks
 */
abstract class BaseDocument
{
    public $persisted = false;

    /** @String */
    protected $inheritedProperty;

    public function setInheritedProperty($value)
    {
        $this->inheritedProperty = $value;
    }

    public function getInheritedProperty()
    {
        return $this->inheritedProperty;
    }

    /** @PrePersist */
    public function prePersist()
    {
        $this->persisted = true;
    }
}