text:
# Collisions

## Overview
This tutorial will show you how to programmatically create different kinds of
bodies and set initial conditions for Skeletons. It will also demonstrate some
use of DART's Frame Semantics.

The tutorial consists of five Lessons covering the following topics:

- Creating a rigid body
- Creating a soft body
- Setting initial conditions and taking advantage of Frames
- Setting joint spring and damping properties
- Creating a closed kinematic chain

Please reference the source code in [**tutorialCollisions.cpp**](https://github.com/dartsim/dart/blob/release-5.1/tutorials/tutorialCollisions.cpp) and [**tutorialCollisions-Finished.cpp**](https://github.com/dartsim/dart/blob/release-5.1/tutorials/tutorialCollisions-Finished.cpp).

## Lesson 1: Creating a rigid body

Start by going opening the Skeleton code [tutorialCollisions.cpp](https://github.com/dartsim/dart/blob/release-5.1/tutorials/tutorialCollisions.cpp).
Find the function named ``addRigidBody``. You will notice that this is a templated
function. If you're not familiar with templates, that's okay; we won't be doing
anything too complicated with them. Different Joint types in DART are managed by
a bunch of different classes, so we need to use templates if we want the same
function to work with a variety of Joint types.

### Lesson 1a: Setting joint properties

The first thing we'll want to do is set the Joint properties for our new body.
Whenever we create a BodyNode, we must also create a parent Joint for it. A
BodyNode needs a parent Joint, even if that BodyNode is the root of the Skeleton,
because we need its parent Joint to describe how it's attached to the world. A
root BodyNode could be attached to the world by any kind of Joint. Most often,
it will be attached by either a FreeJoint (if the body should be completely
free to move with respect to the world) or a WeldJoint (if the body should be
rigidly attached to the world, unable to move at all), but *any* Joint type
is permissible.

Joint properties are managed in a nested class, which means it's a class which
is defined inside of another class. For example, ``RevoluteJoint`` properties are
managed in a class called ``RevoluteJoint::Properties`` while ``PrismaticJoint``
properties are managed in a class called ``PrismaticJoint::Properties``. However,
both ``RevoluteJoint`` and ``PrismaticJoint`` inherit the ``SingleDofJoint`` class
so the ``RevoluteJoint::Properties`` and ``PrismaticJoint::Properties`` classes
both inherit the ``SingleDofJoint::Properties`` class. The difference is that
``RevoluteJoint::Properties`` also inherits ``RevoluteJoint::UniqueProperties``
whereas ``PrismaticJoint::Properties`` inherits ``PrismaticJoint::UniqueProperties``
instead. Many DART classes contain nested ``Properties`` classes like this which
are compositions of their base class's nested ``Properties`` class and their own
``UniqueProperties`` class. As you'll see later, this is useful for providing a
consistent API that works cleanly for fundamentally different types of classes.

To create a ``Properties`` class for our Joint type, we'll want to say
```cpp
typename JointType::Properties joint_properties;
```

We need to include the ``typename`` keywords because of how the syntax works for
templated functions. Leaving it out should make your compiler complain.

From here, we can set the Joint properties in any way we'd like. There are only
a few things we care about right now: First, the Joint's name. Every Joint in a
Skeleton needs to have a non-empty unique name. Those are the only restrictions
that are placed on Joint names. If you try to make a Joint's name empty, it will
be given a default name. If you try to make a Joint's name non-unique, DART will
append a number tag to the end of the name in order to make it unique. It will
also print out a warning during run time, which can be an eyesore (because it
wants you to be aware when you are being negligent about naming things). For the
sake of simplicity, let's just give it a name based off its child BodyNode:

```cpp
joint_properties.mName = name+"_joint";
```

Don't forget to uncomment the function arguments.

Next we'll want to deal with offsetting the new BodyNode from its parent BodyNode.
We can use the following to check if there is a parent BodyNode:

```cpp
if(parent)
{
  // TODO: offset the child from its parent
}
```

Inside the brackets, we'll want to create the offset between bodies:

```cpp
math::Isometry3d tf(math::Isometry3d::Identity());
```

An ``math::Isometry3d`` is the Eigen library's version of a homogeneous
transformation matrix. Here we are initializing it to an Identity matrix to
start out. This is almost always something you should do when creating an
math::Isometry3d, because otherwise its contents will be completely arbitrary
trash.

We can easily compute the center point between the origins of the two bodies
using our default height value:

```cpp
tf.translation() = math::Vector3d(0, 0, default_shape_height / 2.0);
```

We can then offset the parent and child BodyNodes of this Joint using this
transform:

```cpp
joint_properties.mT_ParentBodyToJoint = tf;
joint_properties.mT_ChildBodyToJoint = tf.inverse();
```

Remember that all of that code should go inside the ``if(parent)`` condition.
We do not want to create this offset for root BodyNodes, because later on we
will rely on the assumption that the root Joint origin is lined up with the
root BodyNode origin.

### Lesson 1b: Create a Joint and BodyNode pair

A single function is used to simultaneously create a new Joint and its child
BodyNode. It's important to note that a Joint cannot be created without a
child BodyNode to accompany it, and a BodyNode cannot be created with parent
Joint to attach it to something. A parent Joint without a child BodyNode or
vice-versa would be non-physical and nonsensical, so we don't allow it.

Use the following to create a new Joint & BodyNode, and obtain a pointer to
that new BodyNode:

```cpp
BodyNode* bn = chain->createJointAndBodyNodePair<JointType>(
      parent, joint_properties, BodyNode::AspectProperties(name)).second;
```

There's a lot going on in this function, so let's break it down for a moment:

```cpp
chain->createJointAndBodyNodePair<JointType>
```

This is a Skeleton member function that takes template arguments. The first
template argument specifies the type of Joint that you want to create. In our
case, the type of Joint we want to create is actually a template argument of
our current function, so we just pass that argument along. The second template
argument of ``createJointAndBodyNodePair`` allows us to specify the BodyNode
type that we want to create, but the default argument is a standard rigid
BodyNode, so we can leave the second argument blank.

```cpp
(parent, joint_properties, BodyNode::AspectProperties(name))
```

Now for the function arguments: The first specifies the parent BodyNode. In the
event that you want to create a root BodyNode, you can simply pass in a nullptr
as the parent. The second argument is a ``JointType::Properties`` struct, so we
pass in the ``joint_properties`` object that we created earlier. The third argument is
a ``BodyNode::Properties`` struct, but we're going to set the BodyNode properties
later, so we'll just toss the name in by wrapping it up in a
``BodyNode::AspectProperties`` object and leave the rest as default values.

Now notice the very last thing on this line of code:

```cpp
.second;
```

The function actually returns a ``std::pair`` of pointers to the new Joint and
new BodyNode that were just created, but we only care about grabbing the
BodyNode once the function is finished, so we can append ``.second`` to the end
of the line so that we just grab the BodyNode pointer and ignore the Joint
pointer. The joint will of course still be created; we just have no need to
access it at this point.

### Lesson 1c: Make a shape for the body

We'll take advantage of the Shape::ShapeType enumeration to specify what kind of
Shape we want to produce for the body. In particular, we'll allow the user to
specify three types of Shapes: ``Shape::BOX``, ``Shape::CYLINDER``, and
``Shape::ELLIPSOID``.

```cpp
ShapePtr shape;
if(Shape::BOX == type)
{
  // TODO: Make a box
}
else if(Shape::CYLINDER == type)
{
  // TODO: Make a cylinder
}
else if(SHAPE::ELLIPSOID == type)
{
  // TODO: Make an ellipsoid
}
```

``ShapePtr`` is simply a typedef for ``std::shared_ptr<Shape>``. DART has this
typedef in order to improve space usage and readability, because this type gets
used very often.

Now we want to construct each of the Shape types within their conditional
statements. Each constructor is a bit different.

For box we pass in an math::Vector3d that contains the three dimensions of the box:

```cpp
shape = std::make_shared<BoxShape>(math::Vector3d(
                                     default_shape_width,
                                     default_shape_width,
                                     default_shape_height));
```

For cylinder we pass in a radius and a height:

```cpp
shape = std::make_shared<CylinderShape>(default_shape_width/2.0,
                                        default_shape_height);
```

For ellipsoid we pass in an math::Vector3d that contains the lengths of the three axes:

```cpp
shape = std::make_shared<EllipsoidShape>(
      default_shape_height*math::Vector3d::Ones());
```

Since we actually want a sphere, all three axis lengths will be equal, so we can
create an math::Vector3d filled with ones by using ``math::Vector3d::Ones()``
and then multiply it by the length that we actually want for the three components.

Finally, we want to add this shape as a visualization **and** collision shape for
the BodyNode:

```cpp
auto shapeNode =
   bn->createShapeNodeWith<VisualAspect, CollisionAspect, DynamicsAspect>(shape);
```

We want to do this no matter which type was selected, so those two lines of code
should be after all the condition statements.

### Lesson 1d: Set up the inertia properties for the body

For the simulations to be physically accurate, it's important for the inertia
properties of the body to match up with the geometric properties of the shape.
We can create an ``Inertia`` object and set its values based on the shape's
geometry, then give that ``Inertia`` to the BodyNode.

```cpp
Inertia inertia;
double mass = default_shape_density * shape->getVolume();
inertia.setMass(mass);
inertia.setMoment(shape->computeInertia(mass));
bn->setInertia(inertia);
```

### Lesson 1e: Set the coefficient of restitution

This is very easily done with the following function:

```cpp
shapeNode->getDynamicsAspect()->setRestitutionCoeff(default_restitution);
```

### Lesson 1f: Set the damping coefficient

In real life, joints have friction. This pulls energy out of systems over time,
and makes those systems more stable. In our simulation, we'll ignore air
friction, but we'll add friction in the joints between bodies in order to have
better numerical and dynamic stability:

```cpp
if(parent)
{
  Joint* joint = bn->getParentJoint();
  for(size_t i=0; i < joint->getNumDofs(); ++i)
    joint->getDof(i)->setDampingCoefficient(default_damping_coefficient);
}
```

If this BodyNode has a parent BodyNode, then we set damping coefficients of its
Joint to a default value.

## Lesson 2: Creating a soft body

Find the templated function named ``addSoftBody``. This function will have a
role identical to the ``addRigidBody`` function from earlier.

### Lesson 2a: Set the Joint properties

This portion is exactly the same as Lesson 1a. You can even copy the code
directly from there if you'd like to.

### Lesson 2b: Set the properties of the soft body

Last time we set the BodyNode properties after creating it, but this time
we'll set them beforehand.

First, let's create a struct for the properties that are unique to SoftBodyNodes:

```cpp
SoftBodyNode::UniqueProperties soft_properties;
```

Later we will combine this with a standard ``BodyNode::Properties`` struct, but
for now let's fill it in. Up above we defined an enumeration for a couple
different SoftBodyNode types. There is no official DART-native enumeration
for this, we created our own to use for this function. We'll want to fill in
the ``SoftBodyNode::UniqueProperties`` struct based off of this enumeration:

```cpp
if(SOFT_BOX == type)
{
  // TODO: make a soft box
}
else if(SOFT_CYLINDER == type)
{
  // TODO: make a soft cylinder
}
else if(SOFT_ELLIPSOID == type)
{
  // TODO: make a soft ellipsoid
}
```

Each of these types has a static function in the ``SoftBodyNodeHelper`` class
that will set up your ``UniqueProperties`` for you. The arguments for each of
the functions are a bit complicated, so here is how to call it for each type:

For the SOFT_BOX:
```cpp
// Make a wide and short box
double width = default_shape_height, height = 2*default_shape_width;
math::Vector3d dims(width, width, height);

double mass = 2*dims[0]*dims[1] + 2*dims[0]*dims[2] + 2*dims[1]*dims[2];
mass *= default_shape_density * default_skin_thickness;
soft_properties = SoftBodyNodeHelper::makeBoxProperties(
      dims, math::Isometry3d::Identity(), math::Vector3i(4,4,4), mass);
```

For the SOFT_CYLINDER:
```cpp
// Make a wide and short cylinder
double radius = default_shape_height/2.0, height = 2*default_shape_width;

// Mass of center
double mass = default_shape_density * height * 2*M_PI*radius
              * default_skin_thickness;
// Mass of top and bottom
mass += 2 * default_shape_density * M_PI*pow(radius,2)
            * default_skin_thickness;
soft_properties = SoftBodyNodeHelper::makeCylinderProperties(
      radius, height, 8, 3, 2, mass);
```

And for the SOFT_ELLIPSOID:
```cpp
double radius = default_shape_height/2.0;
math::Vector3d dims = 2*radius*math::Vector3d::Ones();
double mass = default_shape_density * 4.0*M_PI*pow(radius, 2)
              * default_skin_thickness;
soft_properties = SoftBodyNodeHelper::makeEllipsoidProperties(
      dims, 6, 6, mass);
```

Feel free to play around with the different parameters, like number of slices
and number of stacks. However, be aware that some of those parameters have a
minimum value, usually of 2 or 3. During runtime, you should be warned if you
try to create one with a parameter that's too small.

Lastly, we'll want to fill in the softness coefficients:

```cpp
soft_properties.mKv = default_vertex_stiffness;
soft_properties.mKe = default_edge_stiffness;
soft_properties.mDampCoeff = default_soft_damping;
```

### Lesson 2c: Create the Joint and Soft Body pair

This step is very similar to Lesson 1b, except now we'll want to specify
that we're creating a soft BodyNode. First, let's create a full
``SoftBodyNode::Properties``:

```cpp
SoftBodyNode::Properties body_properties(BodyNode::AspectProperties(name),
                                         soft_properties);
```

This will combine the ``UniqueProperties`` of the SoftBodyNode with the
standard properties of a BodyNode. Now we can pass the whole thing into
the creation function:

```cpp
SoftBodyNode* bn = chain->createJointAndBodyNodePair<JointType, SoftBodyNode>(
      parent, joint_properties, body_properties).second;
```

Notice that this time it will return a ``SoftBodyNode`` pointer rather than a
normal ``BodyNode`` pointer. This is one of the advantages of templates!

### Lesson 2d: Zero out the BodyNode inertia

A SoftBodyNode has two sources of inertia: the underlying inertia of the
standard BodyNode class, and the point mass inertias of its soft skin. In our
case, we only want the point mass inertias, so we should zero out the standard
BodyNode inertia. However, zeroing out inertia values can be very dangerous,
because it can easily result in singularities. So instead of completely zeroing
them out, we will just make them small enough that they don't impact the
simulation:

```cpp
Inertia inertia;
inertia.setMoment(1e-8*math::Matrix3d::Identity());
inertia.setMass(1e-8);
bn->setInertia(inertia);
```

### Lesson 2e: Make the shape transparent

To help us visually distinguish between the soft and rigid portions of a body,
we can make the soft part of the shape transparent. Upon creation, a SoftBodyNode
will have exactly one visualization shape: the soft shape visualizer. We can
grab that shape and reduce the value of its alpha channel:

```
auto shape = bn->getShapeNodesWith<VisualAspect>()[0];
math::Vector4d color = shape->getVisualAspect()->getRGBA();
color[3] = 0.4;
shape->getVisualAspect()->setRGBA(color);
```

### Lesson 2f: Give a hard bone to the SoftBodyNode

SoftBodyNodes are intended to be used as soft skins that are attached to rigid
bones. We can create a rigid shape, place it in the SoftBodyNode, and give some
inertia to the SoftBodyNode's base BodyNode class, to act as the inertia of the
bone.

Find the function ``createSoftBody()``. Underneath the call to ``addSoftBody``,
we can create a box shape that matches the dimensions of the soft box, but scaled
down:

```cpp
double width = default_shape_height, height = 2*default_shape_width;
math::Vector3d dims(width, width, height);
dims *= 0.6;
std::shared_ptr<BoxShape> box = std::make_shared<BoxShape>(dims);
```

And then we can add that shape to the visualization and collision shapes of the
SoftBodyNode, just like normal:

```cpp
bn->createShapeNodeWith<VisualAspect, CollisionAspect, DynamicsAspect>(box);
```

And we'll want to make sure that we set the inertia of the underlying BodyNode,
or else the behavior will not be realistic:

```cpp
Inertia inertia;
inertia.setMass(default_shape_density * box->getVolume());
inertia.setMoment(box->computeInertia(inertia.getMass()));
bn->setInertia(inertia);
```

Note that the inertia of the inherited BodyNode is independent of the inertia
of the SoftBodyNode's skin.

### Lesson 2g: Add a rigid body attached by a WeldJoint

To make a more interesting hybrid shape, we can attach a protruding rigid body
to a SoftBodyNode using a WeldJoint. Find the ``createHybridBody()`` function
and see where we call the ``addSoftBody`` function. Just below this, we'll
create a new rigid body with a WeldJoint attachment:

```cpp
bn = hybrid->createJointAndBodyNodePair<WeldJoint>(bn).second;
bn->setName("rigid box");
```

Now we can give the new rigid BodyNode a regular box shape:

```cpp
double box_shape_height = default_shape_height;
std::shared_ptr<BoxShape> box = std::make_shared<BoxShape>(
      box_shape_height*math::Vector3d::Ones());

bn->createShapeNodeWith<VisualAspect, CollisionAspect, DynamicsAspect>(box);
```

To make the box protrude, we'll shift it away from the center of its parent:

```cpp
math::Isometry3d tf(math::Isometry3d::Identity());
tf.translation() = math::Vector3d(box_shape_height/2.0, 0, 0);
bn->getParentJoint()->setTransformFromParentBodyNode(tf);
```

And be sure to set its inertia, or else the simulation will not be realistic:

```cpp
Inertia inertia;
inertia.setMass(default_shape_density * box->getVolume());
inertia.setMoment(box->computeInertia(inertia.getMass()));
bn->setInertia(inertia);
```

## Lesson 3: Setting initial conditions and taking advantage of Frames

Find the ``addObject`` function in the ``MyWorld`` class. This function will
be called whenever the user requests for an object to be added to the world.
In this function, we want to set up the initial conditions for the object so
that it gets thrown at the wall. We also want to make sure that it's not in
collision with anything at the time that it's added, because that would result
in problems for the simulation.

### Lesson 3a: Set the starting position for the object

We want to position the object in a reasonable place for us to throw it at the
wall. We also want to have the ability to randomize its location along the y-axis.

First, let's create a zero vector for the position:
```cpp
math::Vector6d positions(math::Vector6d::Zero());
```

You'll notice that this is an math::Vector**6**d rather than the usual
math::Vector**3**d. This vector has six components because the root BodyNode
has 6 degrees of freedom: three for orientation and three for translation.
Because we follow Roy Featherstone's Spatial Vector convention, the **first**
three components are for **orientation** using a logmap (also known as angle-axis)
and the **last** three components are for **translation**.

First, if randomness is turned on, we'll set the y-translation to a randomized
value:

```cpp
if(mRandomize)
  positions[4] = default_spawn_range * mDistribution(mMT);
```

``mDistribution(mMT)`` will generate a random value in the range \[-1, 1\]
inclusive because of how we initialized the classes in the constructor of
``MyWindow``.

Then we always set the height to the default value:
```cpp
positions[5] = default_start_height;
```

Finally, we use this vector to set the positions of the root Joint:
```cpp
object->getJoint(0)->setPositions(positions);
```

We trust that the root Joint is a FreeJoint with 6 degrees of freedom because
of how we constructed all the objects that are going to be thrown at the wall:
They were all given a FreeJoint between the world and the root BodyNode.

### Lesson 3b: Set the object's name

Every object in the world is required to have a non-empty unique name. Just like
Joint names in a Skeleton, if we pass a Skeleton into a world with a non-unique
name, the world will print out a complaint to us and then rename it. So avoid the
ugly printout, we'll make sure the new object has a unique name ahead of time:

```cpp
object->setName(object->getName()+std::to_string(mSkelCount++));
```

### Lesson 3c: Add the object to the world without collisions

Before we add the Skeleton to the world, we want to make sure that it
isn't actually placed inside of something accidentally. If an object in a
simulation starts off inside of another object, it can result in extremely
non-physical simulations, perhaps even breaking the simulation entirely.
We can access the world's collision detector directly to check make sure the
new object is collision-free:

```cpp
auto collisionEngine
  = mWorld->getConstraintSolver()->getCollisionDetector();
```

Now we shouldn't be surprised if the *other* objects are in collision with each
other, so we'll need to check whether our new object overlaps with any existing objects.
First, we use the collision engine to create a group which contains our object. Then,
we get a group containing the existing objects in the world and use it to check for
collisions.

```cpp
auto newGroup = collisionEngine->createCollisionGroup(object.get());
auto collisionGroup = mWorld->getConstraintSolver()->getCollisionGroup();

dart::collision::CollisionOption option;
dart::collision::CollisionResult result;
bool collision = collisionGroup->collide(newGroup.get(), option, &result);
```

If the new skeleton doesn't overlap an existing object, we can add it to the
world without any complaints:

```cpp
if (!collision)
{
  mWorld->addSkeleton(object);
}
else
{
  std::cout << "The new object spawned in a collision. "
    << "It will not be added to the world." << std::endl;
  return false;
}
```

Of course we should also print out a message so that user understands why we
didn't throw a new object.

### Lesson 3d: Creating reference frames

DART has a unique feature that we call Frame Semantics. The Frame Semantics of
DART allow you to create reference frames and use them to get and set data
relative to arbitrary frames. There are two crucial Frame types currently used
in DART: ``BodyNode``s and ``SimpleFrame``s.

The BodyNode class does not allow you to explicitly set its transform, velocity,
or acceleration properties, because those are all strictly functions of the
degrees of freedom that the BodyNode depends on. Because of this, the BodyNode
is not a very convenient class if you want to create an arbitrary frame of
reference. Instead, DART offers the ``SimpleFrame`` class which gives you the
freedom of arbitarily attaching it to any parent Frame and setting its transform,
velocity, and acceleration to whatever you'd like. This makes SimpleFrame useful
for specifying arbitrary reference frames.

We're going to set up a couple SimpleFrames and use them to easily specify the
velocity properties that we want the Skeleton to have. First, we'll place a
SimpleFrame at the Skeleton's center of mass:

```cpp
math::Isometry3d centerTf(math::Isometry3d::Identity());
centerTf.translation() = object->getCOM();
SimpleFrame center(Frame::World(), "center", centerTf);
```

Calling ``object->getCOM()`` will tell us the center of mass location with
respect to the World Frame. We use that to set the translation of the
SimpleFrame's relative transform so that the origin of the SimpleFrame will be
located at the object's center of mass.

Now we'll set what we want the object's angular and linear speeds to be:

```cpp
double angle = default_launch_angle;
double speed = default_start_v;
double angular_speed = default_start_w;
if(mRandomize)
{
  angle = (mDistribution(mMT) + 1.0)/2.0 *
      (maximum_launch_angle - minimum_launch_angle) + minimum_launch_angle;

  speed = (mDistribution(mMT) + 1.0)/2.0 *
      (maximum_start_v - minimum_start_v) + minimum_start_v;

  angular_speed = mDistribution(mMT) * maximum_start_w;
}
```

We just use the default values unless randomization is turned on.

Now we'll convert those speeds into directional velocities:

```cpp
math::Vector3d v = speed * math::Vector3d(cos(angle), 0.0, sin(angle));
math::Vector3d w = angular_speed * math::Vector3d::UnitY();
```

And now we'll use those vectors to set the velocity properties of the SimpleFrame:

```cpp
center.setClassicDerivatives(v, w);
```

The ``SimpleFrame::setClassicDerivatives()`` allows you to set the classic linear
and angular velocities and accelerations of a SimpleFrame with respect to its
parent Frame, which in this case is the World Frame. In DART, classic velocity and
acceleration vectors are explicitly differentiated from spatial velocity and
acceleration vectors. If you are unfamiliar with the term "spatial vector", then
you'll most likely want to work in terms of classic velocity and acceleration.

Now we want to create a new SimpleFrame that will be a child of the previous one:

```cpp
SimpleFrame ref(&center, "root_reference");
```

And we want the origin of this new Frame to line up with the root BodyNode of
our object:

```cpp
ref.setRelativeTransform(object->getBodyNode(0)->getTransform(&center));
```

Now we'll use this reference frame to set the velocity of the root BodyNode.
By setting the velocity of the root BodyNode equal to the velocity of this
reference frame, we will ensure that the overall velocity of Skeleton's center
of mass is equal to the velocity of the ``center`` Frame from earlier.

```cpp
object->getJoint(0)->setVelocities(ref.getSpatialVelocity());
```

Note that the FreeJoint uses spatial velocity and spatial acceleration for its
degrees of freedom.

Now we're ready to toss around objects!

## Lesson 4: Setting joint spring and damping properties

Find the ``setupRing`` function. This is where we'll setup a chain of BodyNodes
so that it behaves more like a closed ring.

### Lesson 4a: Set the spring and damping coefficients

We'll want to set the stiffness and damping coefficients of only the
DegreesOfFreedom that are **between** two consecutive BodyNodes. The first
six degrees of freedom are between the root BodyNode and the World, so we don't
want to change the stiffness of them, or else the object will hover unnaturally
in the air. But all the rest of the degrees of freedom should be set:

```cpp
for(size_t i=6; i < ring->getNumDofs(); ++i)
{
  DegreeOfFreedom* dof = ring->getDof(i);
  dof->setSpringStiffness(ring_spring_stiffness);
  dof->setDampingCoefficient(ring_damping_coefficient);
}
```

### Lesson 4b: Set the rest positions of the joints

We want to make sure that the ring's rest position works well for the structure
it has. Using basic geometry, we know we can compute the exterior angle on each
edge of a polygon like so:

```cpp
size_t numEdges = ring->getNumBodyNodes();
double angle = 2 * dart::math::pi() / numEdges;
```

Now it's important to remember that the joints we have between the BodyNodes are
BallJoints, which use logmaps (a.k.a. angle-axis) to represent their positions.
The BallJoint class provides a convenience function for converting rotations
into a position vector for a BallJoint. A similar function also exists for
EulerJoint and FreeJoint.

```cpp
for(size_t i=1; i < ring->getNumJoints(); ++i)
{
  Joint* joint = ring->getJoint(i);
  math::AngleAxisd rotation(angle, math::Vector3d(0, 1, 0));
  math::Vector3d restPos = BallJoint::convertToPositions(
        math::Matrix3d(rotation));

  // TODO: Set the rest position
}
```

Now we can set the rest positions component-wise:

```cpp
  for(size_t j=0; j<3; ++j)
    joint->setRestPosition(j, restPos[j]);
```

### Lesson 4c: Set the Joints to be in their rest positions

Finally, we should set the ring so that all the degrees of freedom (past the
root BodyNode) start out in their rest positions:

```cpp
for(size_t i=6; i < ring->getNumDofs(); ++i)
{
  DegreeOfFreedom* dof = ring->getDof(i);
  dof->setPosition(dof->getRestPosition());
}
```

## Lesson 5: Create a closed kinematic chain

Find the ``addRing`` function in ``MyWindow``. In here, we'll want to create a
dynamic constraint that attaches the first and last BodyNodes of the chain
together by a BallJoint-style constraint.

First we'll grab the BodyNodes that we care about:

```cpp
BodyNode* head = ring->getBodyNode(0);
BodyNode* tail = ring->getBodyNode(ring->getNumBodyNodes()-1);
```

Now we want to compute the offset where the BallJoint constraint should be located:

```cpp
math::Vector3d offset = math::Vector3d(0, 0, default_shape_height / 2.0);
offset = tail->getWorldTransform() * offset;
```

The offset will be located half the default height up from the center of the
tail BodyNode.

Now we have everything we need to construct the constraint:

```cpp
auto constraint = std::make_shared<dart::dynamics::BallJointConstraint>(
      head, tail, offset);
```

In order for the constraint to work, we'll need to add it to the world's
constraint solver:

```cpp
mWorld->getConstraintSolver()->addConstraint(constraint);
```

And in order to properly clean up the constraint when removing BodyNodes, we'll
want to add it to our list of constraints:

```cpp
mJointConstraints.push_back(constraint);
```

And that's it! You're ready to run the full tutorialCollisions application!

**When running the application, keep in mind that the dynamics of collisions are
finnicky, so you may see some unstable and even completely non-physical behavior.
If the application freezes, you may need to force quit out of it.**

repository: dartsim/dart

repo_name: dartsim/dart


text:
# Flexee

[![Travis CI](https://img.shields.io/travis/dlueth/qoopido.flexee.svg?style=flat-square)](https://travis-ci.org/dlueth/qoopido.flexee)
[![Coveralls](https://img.shields.io/coveralls/dlueth/qoopido.flexee.svg?style=flat-square)](https://coveralls.io/github/dlueth/qoopido.flexee)
[![David](https://img.shields.io/david/dlueth/qoopido.flexee.svg?style=flat-square)](https://github.com/dlueth/qoopido.flexee)
[![License](https://img.shields.io/github/license/dlueth/qoopido.flexee.svg?style=flat-square)](https://github.com/dlueth/qoopido.flexee)
[![GitHub version](https://img.shields.io/github/tag/dlueth/qoopido.flexee.svg?style=flat-square&label=github)](https://github.com/dlueth/qoopido.flexee)
[![NPM version](https://img.shields.io/npm/v/flexee.svg?style=flat-square)](https://www.npmjs.com/package/flexee)
[![NPM downloads](https://img.shields.io/npm/dm/flexee.svg?style=flat-square)](https://www.npmjs.org/package/flexee)
[![NPM downloads](https://img.shields.io/npm/dt/flexee.svg?style=flat-square)](https://www.npmjs.org/package/flexee)

Flexible & dead simple event emitter for Node.js supporting RegExp-based event subscription and global broadcast listeners.

## Installation

```
$ npm install --save flexee # npm
$ yarn add flexee           # yarn
```

## Usage
The only thing left to do after installation via NPM or yarn is to require the module:
```
var Flexee = require('flexee');
```

Afterwards you can either create an instance or extend ```Flexee``` with your own ```class``` and use its methods as described below.

### Listeners
Listeners (also referred to as callbacks) must be of type ```Function``` which will always receive an instance of type ```Event``` as their first parameter. If the event was emitted with further parameters these will be passed to the listener as separate arguments.

The passed ```Event``` instance offers access to the event ```name``` as well as its ```context``` and, in addition, offers a ```cancel``` method to stop further processing of an event.

### Subscribing to events
Flexee offers a total of three methods to subscribe to events: ```on```, ```once``` and ```limit```.

```
// register an event listener
emitter.on({String|RegExp|Object[]} identifier, {Function} callback, {Boolean=} prepend, {Number=} limit);

// register a once only event listener
emitter.once({String|RegExp|Object[]} identifier, {Function} callback, {Boolean=} prepend);

// register an event listener that gets called a limited number of times
emitter.limit({String|RegExp|Object[]} identifier, {Number} limit, {Function} callback);
```

```identifier``` can either be a specific event name as ```String```, a pattern of event names as ```RegExp``` or an ```array``` of both which gives you almost endless flexibitlity.

### Unsubscribing from events
The only method to know is the ```off``` method:

```
emitter.off({String|RegExp|Object[]} identifier, {Function=} callback);
```

```identifier``` can, again, either be a specific event name as ```String```, a pattern of event names as ```RegExp``` or an ```array``` of both. Just keep in mind that unsubscribing from a specific event name will never unsubscribe a RegExp-listener and vice versa.

### Emitting events
Any instance of ```Flexee``` has its own ```emit``` method:

```
emitter.emit({String} name, ...details);
```

### Retrieving listeners
If you need to retrieve any existing listener for a specific event simply use

```
emitter.listener({String} name);
```

Calling ```listener``` will always return an array which may be empty.

### Chaining
Any method beside ```listener``` returns the current instance to offer a chainable interface.

### Broadcast listeners
It is possible to not only subscribe to events emitted by a known instance of ```Flexee``` but also to subscribe to events emitted by any existing and/or future instance. This behaviour allows, e.g., to subscribe to events globally for logging purposes and the likes.

```
var Flexee = require('flexee');

// register a broadcast listener
Flexee.on({String|RegExp|Object[]} identifier, {Function} callback, {Boolean=} prepend, {Number=} limit);

// register a once only broadcast listener
Flexee.once({String|RegExp|Object[]} identifier, {Function} callback, {Boolean=} prepend);

// register a broadcast listener that gets called a limited number of times
Flexee.limit({String|RegExp|Object[]} identifier, {Number} limit, {Function} callback);

// unregsiter a broadcast listener
Flexee.off({String|RegExp|Object[]} identifier, {Function=} callback);

// retrieve boradcast listeners for a specific event
Flexee.listener({String} name);
```

license: MIT

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
# PBS 56 of X — More Bootstrap Content

In the previous instalment we got our first look at the functionality the Bootstrap documentation groups together under the heading _Content_. These are opt-in additional styles for standard HTML elements. Last time we looked at headings, paragraphs, quotations and lists. This time we’ll finish our overview of this aspect of Bootstrap with a look at styling images, figures, and tables.

In the next instalment we’ll move on to the most powerful aspect of Bootstrap, layout. This will take us a few instalments to cover, but when we’re done we’ll have learned how to use Bootstrap to arrange content on a page, and, better yet, to make our layouts _responsive_. That is to say, we’ll learn how to use Bootstrap to make our pages look right on any screen, from the smallest phone to the largest desktop!

You can [download this instalment’s ZIP file here](https://www.bartbusschots.ie/s/wp-content/uploads/2018/06/pbs56.zip) or [here on GitHub](https://cdn.jsdelivr.net/gh/bbusschots/pbs-resources/instalmentZips/pbs56.zip).

## Matching Podcast Episode 551

Listen along to this instalment on [episode 551 of the Chit Chat Across the Pond Podcast](https://www.podfeet.com/blog/2018/06/ccatp-551/)

<audio controls src="https://media.blubrry.com/nosillacast/traffic.libsyn.com/nosillacast/CCATP_2018_06_16.mp3">Your browser does not support HTML 5 audio 🙁</audio>

You can also Download the MP3

## PBS 55 Challenge Solution

The challenge set at the end of [the previous instalment](https://pbs.bartificer.net/pbs55) was to continue to improve the recipes we’ve been working on over the last few instalments.

The first part of the challenge was to convert the page header to a display heading. I chose to break my title into two parts, a main part, and a subtitle using the `<small>` tag:

```html
<h1 class="display-1 sticky-top bg-white border-bottom">Roasted Cucumber<br> <small class="text-muted">with Red Onion & Dill</small></h1>
```

The key point is the addition of the class `display-1` to the `<h1>` tag.

The next task was to add a pithy description to the top of the recipe, and to mark it as a lead paragraph. To aid screen readers and SEO, the paragraph should be preceded with a visually invisible heading:

```html
<h2 class="sr-only">Description</h2>
<p class="lead">An unusual roasted vegetable dish that's refreshingly tangy and will pair well with fish.</p>
```

The key here is the use of the class `lead` on the paragraph, and the class `sr-only` (screen reader only) to the heading.

Next, the heading at the top of the table of ingredients was to be rendered as if it were a heading tag. I felt that this heading was of equal importance to the other section headings on the page, all of which are `<h2>`s, so I chose to add the class `h2`:

```html
<table class="w-25 float-right">
  <thead>
    <tr>
      <th class="h2">Ingredients</th>
    </tr>
  </thead>
  <tbody>
    <!-- ... -->
  </tbody>
</table>
```

The fourth task was to update the quotation to use the appropriate markup and classes for block quotations:

```html
<blockquote class="blockquote">
  <p class="font-italic">"If the natural ..."</p>
  <footer class="blockquote-footer text-right"><strong>Julia Child</strong> in <em>Mastering ...</em> (1961)</footer>
</blockquote>
```

The key changes are the addition of the class `blockquote` to the `<blockquote>` tag, and the wrapping of the attribution in a `<footer>` tag with the class `blockquote-footer`.

Finally, the fifth task was to update the flex box with required equipment to use the appropriate list classes rather than the `d-block` hack used previously:

```
<ul class="list-unstyled d-flex flex-row justify-content-between text-center my-3 mx-0 p-0">
  <li>
    <!-- ... -->
  </li>
  <!-- ... -->
</ul>
```

The key points are the addition of the class `list-unstyled` to the `<ul>` tag, and the removal of all classes from the individual `<li>` tags.

I’ve included my full sample solution within the folder named `pbs55-challengeSolution` in [this instalment’s ZIP file](https://www.bartbusschots.ie/s/wp-content/uploads/2018/06/pbs56.zip) or [here on GitHub](https://cdn.jsdelivr.net/gh/bbusschots/pbs-resources/instalmentZips/pbs56.zip).

## Playground

Like last time, I’ve created an HTML document with some previously created elements and empty class attributes which you can use to play along with this instalment. This time the source is very long because it contains tabular data. So I’m not including the source below, but you’ll find it in [this instalment’s ZIP file](https://www.bartbusschots.ie/s/wp-content/uploads/2018/06/pbs56.zip) or [here on GitHub](https://cdn.jsdelivr.net/gh/bbusschots/pbs-resources/instalmentZips/pbs56.zip) as `pbs56a.html`, and in [this interactive Bootply playground](https://www.bootply.com/84ZKahLphH).

## Images & Figures

For the most part, images in Bootstrap are styled in the same way as any other block-like element — you use the border utilities to control the border, the spacing utilities to control the margin, and the positioning utilities to float images left or right if so desired.

For example, to add a rounded red border, float left, and add a margin to all sides but the left, you could do something like:

```
<img class="border border-danger rounded float-left m-3 ml-0" src="img.jpeg" alt="an image">
```

Note that we set the generic margin to `3` with the class `m-3`, and then the left margin to `0` with the class `ml-0`. This works because the classes controlling all four sides have a lower specificity than those controlling just two sides, which in turn have a lower specificity than those controlling just one side.

Bootstrap does provide one notable additional image feature though — the ability for an image to shrink to fit into the width of its container. Bootstrap refers to such images as being _responsive_, but you may also see them referred to as being _fluid_.

### Responsive/Fluid Images

A responsive image is one that shrinks so its width is never wider than its containing block. Note that the aspect ratio will be preserved, and that an image that’s too small to fill the container’s width won’t get stretched — responsive images shrink, they do not stretch!

To mark an image as responsive, simply give it the class `img-fluid`.

To see this in action, let’s add the class `img-fluid` to the first image that appears in the dummy page (the one of the posters with the ID `fig1`). Notice that, while your viewport is larger than the width of the image, it’s displayed in the normal way. Now, shrink your viewport by shrinking the width of your browser window and watch the image scale so it never overflows the page!

### Figures

Very often, when including an image in a page, you want to accompany it with a caption. In HTML 5, the combination of a graphic of some sort with a caption is referred to as a _figure_. The relevant HTML 5 tags are `<figure>` and `<figcaption>`.

Bootstrap provides some CSS classes for adding basic styles to figures. The containing `<figure>` tag should be given the class `figure`, the image itself the class `figure-img`, and the `<figcaption>` tag the class `figure-caption`.

As a first example, let’s add these classes to the first figure in the playground:

```html
<figure class="figure">
  <img id="fig1" class="figure-img img-fluid rounded" alt="Election Posters ..." src="https://upload.wikimedia.org...">
  <figcaption class="figure-caption">Abortion Referendum Campaign Posters...</figcaption>
</figure>
```

Note that because it generally looks better, I also added the Bootstrap utility class `rounded` to the image to give it subtly rounded corners.

Also note that I left the `img-fluid` class in place because I still want the image to shrink when needed.

You’ll see that the changes adding these tags make are subtle. The spacing is adjusted a little, and the caption is rendered in a subtle font.

A very likely next step would be to float the figure; so let’s do that by adding the classes `w-25` (to set the width), and `float-right` to the `<figure>` tag:

```html
<figure class="figure w-25 float-right">
  <!-- ... -->
</figure>
```

You may not want your figure to float. Instead, you might want to centre it within the page. This can be done too, but there’s a subtlety you’ll need to remember.

Let’s start by giving the components that make up our second figure (the map) the standard Bootstrap classes for figures (`figure`, `figure-img`, & `figure-caption`). We should also make the image responsive by giving it the class `img-fluid`, and centre the text within the caption by giving it the Bootstrap utility class `text-center`. This will format the caption nicely, but it won’t centre the figure:

```html
<figure class="figure">
  <img id="fig2" class="figure-img img-fluid" alt="Result Map" src="https://upload.wikimedia.org/...">
  <figcaption class="figure-caption text-center">Referendum result by ...</figcaption>
</figure>
```

As we’ve seen before, we can centre a regular block element by giving it a specific width and setting the left and right margins to `auto` with the Bootstrap utility class `mx-auto`. Try that on the figure by adding the classes `w-75` to set the width to 75%, and `mx-auto` to balance the margin left and right.

Perhaps surprisingly, that only half works — the width does change, but the figure does not get centred within the page. What’s going on?

As you can confirm to yourself with the developer tools of your choice, the class `figure` sets the `display` property to `inline-block`, and inline blocks don’t have margins! What’s the solution? Simple, just set the `display` to `block` with the Bootstrap utility class `d-block`:

```html
<figure class="figure w-75 mx-auto d-block">
  <img id="fig2" class="figure-img img-fluid" alt="Result Map" src="https://upload.wikimedia.org/...">
  <figcaption class="figure-caption text-center">Referendum result ...</figcaption>
</figure>
```

And with that, we now have a nicely centred and nicely formatted figure.

## Tables

Probably the most striking of the Bootstrap content classes are those for tables. Native HTML tables leave a lot to be desired, and Bootstrap really addresses the shortcomings.

Bootstrap assumes proper table markup, so be sure to enclose your header rows inside a `<thead>` tag, and your table’s body inside a `<tbody>` tag. Also, if your table has footer rows, they need to go within a `<tfoot>`.

### The Basics

To apply Bootstrap styling to a table, you have to give it the class `table`. That will give you the default Bootstrap styling for tables, which includes nice typography, and subtle borders at the top of each row. In my opinion the look is elegant and modern. To see for yourself, add the class `table` to both of the tables in the sandbox.

Once you’ve applied this basic class, you can apply additional classes to customise your table further. In general, these additional classes have been designed with the intention that they be combined with each other, at least where the combinations make sense.

### Coloured Tables

Firstly, the most dramatic change you can make to your tables is to invert them from their default dark on light rendering to light on dark. You do this with the class `table-dark`.

If inverting the entire table is a bit too dramatic for your taste, you can invert just the header by applying the class `thead-dark` to the `<thead>` tag. If even that’s a little too stark, you can get a more subtle grey background with the class `thead-light`.

You can experiment with all these options with the tables in the sandbox page, but I’m going to keep things subtle by adding the more subtle grey background to the first, smaller table in our sandbox with the class `thead-light`, and the darker heading to the second (larger) table with the class `thead-dark`.

Finally, there are table-specific variants of the colour utility classes. They can be used to set background colours at both the row and cell level. The following are available, and do what you would expect them to do:

*   `table-primary`
*   `table-secondary`
*   `table-success`
*   `table-danger`
*   `table-warning`
*   `table-info`
*   `table-light`
*   `table-dark`
*   `table-active`

These classes give a more toned-down colour than that which you get from the regular background utility classes (`bg-primary` etc.), but they don’t work on inverted tables. Thankfully the stronger colours from the traditional background utilities do work well on inverted tables.

As an example, let’s give the row with the votes in favour within the first (smaller) table the class `table-success`, and the row with the votes against the class `table-danger`.

### Row Highlighting

As your tables grow, and especially if they become very wide, it can be hard to follow the rows with your eyes. To make this easier, Bootstrap provides the class `table-striped` which, as its name suggests, alternates the background colour of each subsequent row.

Let’s see this in action by adding the class `table-striped` to the second, larger table in our sandbox page.

Another technique for helping users view large tables is to highlight the row the mouse is hovering over. This can be done with the `table-hover` class.

Both of these classes work on both regularly coloured tables and dark tables. Do also note that the effects are only applied to rows within the body of the table, that is to say, `<tr>`s within the `<tbody>`.

### Borders

By default, Bootstrap adds some subtle partial borders to the rows within tables, but no borders between cells. The default look is minimalistic and contemporary, so you may well choose to keep it, but you don’t have to. You can override the default partial borders in two ways — you can use the class `table-borderless` to remove all borders, or `table-bordered` to add borders to all sides of all cells.

Again, both of these classes work on regular and dark tables.

You can experiment with both of these classes in the sandbox, but I’m going to leave the borders on the larger table as they are, and make the first, smaller table fully bordered by adding the class `table-bordered`.

### Smaller More Subtle Tables

In keeping with Bootstrap’s modern look, its default rendering to tables has a lot of white space, and uses quite large fonts. Sometimes you need your tables to be a little more compact, and that’s what the `table-sm` class is for!

The smaller of the two tables in the sandbox is well suited to shrinking down a little. Let’s give it the class `table-sm`.

Let’s take things a little further and shrink the table and float it right by adding the class `w-50` and `float-right`.

The first smaller table in the sandbox should now look something like:

```html
<table class="table table-bordered table-sm w-50 float-right">
  <caption class="">National total results...</caption>
  <thead class="thead-light">
    <!-- ... -->
  </thead>
  <tbody class="">
    <tr class="table-success">
      <th>Yes</th>
      <!-- ... -->
    </tr>
    <tr class="table-danger">
      <th>No</th>
      <!-- ... -->
    </tr>
    <!-- ... -->
  </tbody>
</table>
```

### Table Captions

The HTML spec allows tables to define captions using the `<caption>` tag. Note that captions are not headings, they are descriptions of the table’s content in the same way that you’d caption an image. For that reason, Bootstrap’s style for table captions is subtle, and consistent with the way Bootstrap styles `<figcaption>`s.

### Horizontally Scrolling Tables

Normally, when a table becomes too wide to fit into its container, it overflows through the right edge of the container. That’s unlikely to be what you want. So if you have a big table, Bootstrap gives you the option of having it automatically develop a horizontal scroll bar whenever it would ordinarily overflow.

This kind of automatic scrolling is made available via the `table-responsive` class, but unlike most of the other table-related classes, this one is not applied to the `<table>` tag, or even to a tag within the table. Instead, you have to wrap the table with another tag, usually a `<div>`, and give it the class `table-responsive`.

Let’s do this for the second, larger, table in our sandbox:

```html
<div class="table-responsive">
  <table class="table table-striped">
    <caption class="">Detailed results...</caption>
    <thead class="thead-dark">
      <!-- -->
    </thead>
    <tbody class="">
      <!-- -->
    </tbody>
    <tfoot>
      <!-- -->
    </tfoot>
  </table>
</div>
```

You’ll find a version of the sandbox page with all the examples added as `pbs56b.html` in [this instalment’s ZIP file](https://www.bartbusschots.ie/s/wp-content/uploads/2018/06/pbs56.zip) or [here on GitHub](https://cdn.jsdelivr.net/gh/bbusschots/pbs-resources/instalmentZips/pbs56.zip).

## A Challenge

For this challenge we’ll continue to improve the recipe we’ve been building up for the past few instalments. Update your recipe with the following enhancements:

1.  Make the image in your recipe’s figure responsive.
2.  Style your recipe’s figure as you think works best, perhaps floated, or perhaps centred.
3.  Style your table of ingredients as you like.
4.  Make any other improvements you consider appropriate.

## Final Thoughts

We’ve now covered two of Bootstrap’s four aspects — the utility classes and the content classes. Next we’ll move on to the layout classes. Bootstrap’s layout engine is very powerful, and it has a lot of features. So unsurprisingly, it will take us a few instalments to make our way through it. When we’re done we’ll be able to lay out our pages just the way we want, and in such a way that they’ll look great on any screen. Bootstrap doesn’t just do layouts, it does responsive layouts!

repository: bartificer/programming-by-stealth

gha_language: HTML

gha_license_id: MIT

repo_name: bartificer/programming-by-stealth


text:
import { LiteYoutubeEmbed } from "react-lite-yt-embed";
import { Tweet } from "react-twitter-widgets"
import PageHeader from "../../components/PageHeader";
import Head from "../../components/Head";
import WideSection from "../../components/WideSection";

<PageHeader title="Problems" mb={0}>
  <Head
    title="Problems – Max Stoiber (@mxstbr)"
    description="A list of problems I encounter relatively frequently that annoy me."
  />
</PageHeader>

Inspired by [Wilhelm Klopp](https://wilhelmklopp.com/problems/), these are some of the problems I'm thinking about. If any of these trigger any thoughts, please [reach out and talk to me](https://twitter.com/mxstbr) about them — I'd love to chat!

## Local dev environments are brittle

Making local dev environments work often requires incantations of unbelievable length. What should the right set of env variables look like? Where do you get those from? How do you start the server, the client and the db and connect them all together? How do you abstract the differences between operating systems? etc. etc. etc.

Docker _kind of_ solves this, but it's really optimized for production usage. It makes a lot of common development tasks unbearably slow. (e.g. installing dependencies, watching files, syncing files from host to volume, etc.) You have to remember to execute commands in the container (`docker-compose exec app yarn add package`). etc.etc.

Fundamentally, Docker is the wrong tool for the job. It works, but it's far from ideal.

docker-compose though is really nice: One command to start/stop the local development environment which'll work on any operating system?! Fantastic!

Is there a way to get the benefits of Docker (-compose) in a lighter-weight package optimized for development?

 They're fine, but they could be much more specific to _my_ app and setup.

ui-devtools.com is a great example of "DevTools specific to my stack" and makes for a fantastic development experience.

However, contrast that with the React DevTools: those are only useful for debugging. UI Devtools, on the other hand, is useful for _development_.

My first intuition was that it's because UI Devtools writes out to my code, but really that's not the point. It could just as well not do that and still be super useful.

What makes UI Devtools useful for development is its ability to scope itself to _my app_. I can lightly try different of _my styles_ on _my app_ in real-time.

Think about this then: how could React DevTools scope itself to my app and be useful for development?

What if you could drag and drop any React component that's already in your app onto the page? Or even just edit them in real-time into the JSX tree?

## It is impossible to know who owns what in a big company

At GitHub, we had a Slack channel for asking "Who owns this?", and even then it was really hard to figure out how to find who to talk to about a certain thing.

On top of that, it's really hard to know what _isn't_ owned by anyone. What's currently unowned and bitrotting?

Could be specific to code, internal tools, or even all processes. Who owns the code review process? Who owns the promotion process? etc. etc.

## Making good decisions is really hard

How do you make a good decisions? 🤷♂ It's hard to learn the skill of making good decisions.

Might be because the iteration speed is really slow? You can only try one branch, and you can't really figure out if the other one would've worked better or worse — you basically can't A/B test a decision.

gha_language: JavaScript


text:
# @orbit-ui/components

Full documentation available at: https://orbit.sharegate.design

## Add a new component

Adding a new component package involve a few extra steps:

- [Understand the components guidelines](#component-guidelines)
- [Write storybook stories](#write-storybook-stories)
- [Write tests](#tests)
- [Update the documentation](#update-the-documentation)
- [Include the component in the bundle](#include-the-component-in-the-bundle)

### Write storybook stories

As mentionned in the [contributing guide](../../CONTRIBUTING.md), Storybook is use to *develop*, *document* and *test* a component.

To develop and document, we leverage the [CSF](https://storybook.js.org/docs/formats/component-story-format/) and [MDX](https://storybook.js.org/docs/formats/mdx-syntax/) features of Storybook.

To test, we rely on a third party called [Chromatic](https://www.chromaticqa.com/) that fully integrate with Storybook to provide visual testing capabilities.

#### Develop and document

Development stories are written for 2 purposes:

- For the developper to test a component use case in a isolated story during the development lifecycle.
- For the design team to try the component behaviors.

Documentation stories are written... well for documentation purpose!

To define a story once for development and documentation a story must be written with [CSF](https://storybook.js.org/docs/formats/component-story-format/) in an `*.stories.mdx` file. The name of the file should match the component name.

A story must:

- Be located in the `Components` top level section of the Storybook navigation menu.
- The second level segment must be the capitalized name of the component.

Here's an exemple for the button component:

```jsx
// Button.stories.mdx

<Meta title="Components/Button" />
```

A component stories must provide:

- A story named *default* that render the component default state.

The stories must be located in a `docs` folder next to the `src` folder of your component. Storybook is configured to load the following component stories: `packages/components/src/*/docs/**.stories.mdx`.

```
/packages
    /components
        /buttons
            /docs
                Button.stories.mdx
            /src
```

#### Tests

Before reading the following sections, please read [our introduction to Orbit testing practices](../../CONTRIBUTING.md#testing).

##### Visual testing

Specific stories for Chromatic are written to validate the specifications of a component with automated visual tests. The specifications stories are validated [every night](https://circleci.com/gh/gsoft-inc) with [Chromatic](https://www.chromaticqa.com/) for visual regression issues.

Storybook is a fantastic tool for visual testing because a story is essentially a test specification. When it does make sense, multiple specifications can be bundled together in a story to save on Chromatic snapshots (which are not cheap!).

Specifications stories must be written with the [storiesOf API](https://storybook.js.org/docs/formats/storiesof-api/) in a `*.chroma.jsx` file.

A specifications story must:

- Be located in the `Chromatic` top level section of the Storybook navigation menu.
- The second level segment must be the capitalized name of the component (same as the development stories).

Here's an example:

```javascript
// Button.chroma.jsx

import { paramsBuilder, storiesOfBuilder } from "@stories/utils";

function stories(segment) {
    return storiesOfBuilder(module, "Chromatic/Button")
        .segment(segment)
        .parameters(
            paramsBuilder()
                .build()
            )
        .build();
}

stories("/segment")
    .add("story-name",
         () =>
            ...
    )
```

The stories must be located in a `tests/chromatic` folder next to the `src` folder of your component. Storybook is configured to load the following tests specifications: `packages/components/src/*/tests/chromatic/**.chroma.[jsx|tsx]`.

```
/packages
    /components
        /buttons
            /src
            /tests
                /chromatic
                    Button.chroma.jsx
```

Every component should have a test for "zoom" and "styling". Have a look at the existing tests to learn more.

For more information about the Storybook automated visual tests workflow, read the following [blog post](https://blog.hichroma.com/the-delightful-storybook-workflow-b322b76fd07) and the following [introduction to visual testing](https://storybook.js.org/tutorials/visual-testing-handbook/react/en/introduction/).

##### Interaction testing

Since visual testing tools like Chromatic can't help much for interaction testing we rely on Jest](https://jestjs.io/) and [React Testing Library](https://testing-library.com/docs/react-testing-library/intro/) for those. Similar to visual testing, interaction tests are validated [every night](https://circleci.com/gh/gsoft-inc).

*NOTE: You should always prefer a visual test with Chromatic over an interaction test with Jest and React Testing Library. Chromatic tests are much quicker to write and easier to maintain.*

Interaction tests must:

- Be written  in a `*.test.[jsx|tsx]` file.
- Be located in a `tests/jest` folder next to the `src` folder of your component.

```
/packages
    /components
        /buttons
            /src
            /tests
                /jest
                    Button.test.jsx
```

Here's an example:

```javascript
// Button.test.jsx

test("call onChange when the button is selected", () => {
    ....
});
```

Usually, interaction tests are split into 4 distinct regions: *Behaviors*, *Aria*, *Api* and *Refs*.

## Component guidelines

Every Orbit custom components must share a consistent API and a similar design. Please read carefully the following guidelines before you develop a new component or update an existing one.

### Common functionnalities

All components should:
- Use Orbit's [tokens](https://orbit.sharegate.design/?path=/docs/tokens--page)
- Support Orbit's [color schemes](https://orbit.sharegate.design/?path=/docs/color-schemes--page) and [theming](https://orbit.sharegate.design/?path=/docs/theming--page)
- Implement Orbit's [style props](https://orbit.sharegate.design/?path=/docs/style-props--page)
- Support Orbit's [responsive styles](https://orbit.sharegate.design/?path=/docs/responsive-styles--page)

### Design

#### Functional components

All components should be developed as functional components.

#### Hooks

All components should leverage React hooks.

#### Styling

An Orbit component shouldn't use any CSS in JS properties.

All styling should be done with native CSS and use our foundation CSS variables when possible

#### Controlled & Auto-controlled

A component should always be develop to offer a [controlled](https://reactjs.org/docs/forms.html) and [auto-controlled](https://reactjs.org/docs/uncontrolled-components.html) usage.

A *controlled* component gives a lot of flexibility to the consumer and is well fit for a lot of use cases but also involve additional code. We believe a component should be flexible but also painless to use. That's why a component should also offer an *auto-controlled* mode for basic use cases who don't requires controlling the props.

#### Never stop event propagation

A component shouldn't stop the propagation of an event. Instead, other parts of the code should determine whether or not it should handle the event.

For more information, read the following [blog post](https://css-tricks.com/dangers-stopping-event-propagation/).

#### Handler event argument

Every component should provide the initiating event as the first argument when calling a user event handler.

```jsx
const handleChange = event => {
    if (!isNil(onValueChange)) {
        onValueChange(event, event.target.value);
    }
});
```

#### Do the component stuff before calling the event handler

Before calling the user event handler always execute all the component logic related to the event.

```jsx
const handleChange = event => {
    const newValue = event.target.value;

    // Call setValue before calling onValueChange.
    setValue(newValue);

    if (!isNil(onValueChange)) {
        onValueChange(event, newValue);
    }
});
```

#### Spread props

Unhandled props should always be spread on the root element of the component. If it's not practical to spread the props on the root element, consider adding an additional prop for the root element props (like `wrapperProps`) and spread those props on the root element.

```jsx
function MyComponent({ className, children ...rest }) {
    return (
        <Div className={className} {...rest}>
            {children}
        </Div>
    );
}
```

#### Slots

All "slotable" components should accept an optionnal slot property.

#### As prop

A component should always accept an `as` prop and apply it to the root element of the component. The `as` prop allow the consumer to specify the type of the element to render. A default value should always be provided.

The following usage should be possible for all components:

```jsx
<Button as="link" href="#>Click me!</Button>
```

> This is not true anymore, component public interface doesn't accept `as` prop anymore. Instead, when needed, the `as()` function should be used. That being said, since our internals are still dependend on the `as` prop, every components should still accept the prop internally.

#### Ref

A component should always accept a `ref` prop and apply it to the root element of the component.

> If the component have a wrapper element, like the text input component, the ref could instead be rendered on the input element. When the ref is not rendered on the root element, add a `wrapperProps` prop which accept a ref for the wrapper element.

### Developer experience

#### Props and Typings

Every component and functions should provide static typings with [TypeScript](https://www.typescriptlang.org/).

### Component props naming

#### Event handlers props

Event handler props should be prefix by `on` and be in the present tense.

Ex:

- Prefer `onChange` to `onChanged`
- Prefer `onItemClick` to `onItemClicked`

#### Boolean props

A boolean prop shouldn't be prefix with `is`.

Ex:

- Prefer `open` to `isOpen`
- Prefer `disabled` to `isDisabled`

#### Prefer simpler props name

When there is no possible *ambiguities*, prefer a simpler prop name.

For example, prefer `icon` to `inputIcon`.

#### Initial values props name

Auto-controlled components will usually expose initial values props. Those props should be prefix with `default`.

Ex:

- `defaultOpen`
- `defaultStartDate`
- `defaultValues`

### Accessibility

All components should follow [WAI-ARIA practices](https://www.w3.org/WAI/ARIA/apg/) when applicable.

## License

Copyright © 2023, GSoft inc. This code is licensed under the Apache License, Version 2.0. You may obtain a copy of this license at https://github.com/gsoft-inc/gsoft-license/blob/master/LICENSE.

repository: gsoft-inc/sg-orbit

gha_language: TypeScript

repo_name: gsoft-inc/sg-orbit


text:
<!-- README.md is generated from README.Rmd. Please edit that file -->
powsimR: Power analysis for bulk and single cell RNA-seq experiments
====================================================================

NEWS
----

**Version 1.1.1** released with the following changes / additions (2018-04-19):

-   `simulateDE` now with the option to perform DE testing on filtered/imputed counts (option `DEFilter`)

**Version 1.1.0** released with the following changes / additions (2018-03-29):

-   simulation of batch effects (see options `p.B`, `bLFC` and `bPattern` in `DESetup` and `simulateCounts`)
-   simulation of spike-in expression (see `estimateSpike` , `plotSpike` and option `spikeIns` in `simulateDE` and `simulateCounts`)
-   simulation of multiple sample groups (e.g. single cell populations) with `simulateCounts`
-   imputation and prefiltering options prior to normalisation in DE power simulations added (scImpute, scone, Seurat, DrImpute, SAVER)
-   additional normalisation options and DE tools (esp. for single cells) included in `simulateDE`
-   evaluation of simulation setup using estimated versus true value comparisons of library size factors and log2 fold changes in `evaluateSim` and `plotEvalSim`
-   increased flexibility in preprocessing for distribution evaluation in `evaluateDist`

Installation Guide
------------------

For the installation, the R package `devtools` is needed.

``` r
install.packages("devtools")
library(devtools)
```

I recommend to install first the dependencies manually and then powsimR:

``` r
ipak <- function(pkg, repository = c("CRAN", "Bioconductor", "github")) {
    new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
    # new.pkg <- pkg
    if (length(new.pkg)) {
        if (repository == "CRAN") {
            install.packages(new.pkg, dependencies = TRUE)
        }
        if (repository == "Bioconductor") {
            source("https://bioconductor.org/biocLite.R")
            biocLite(new.pkg, dependencies = TRUE, ask = FALSE)
        }
        if (repository == "github") {
            devtools::install_github(new.pkg, build_vignettes = FALSE, dependencies = TRUE)
        }
    }
}

# CRAN PACKAGES
cranpackages <- c("bbmle", "broom", "cluster", "cobs", "cowplot", "data.table",
    "doParallel", "dplyr", "drc", "DrImpute", "fastICA", "fitdistrplus", "foreach",
    "gamlss.dist", "ggExtra", "ggplot2", "ggthemes", "grDevices", "glmnet",
    "grid", "gtools", "Hmisc", "kernlab", "MASS", "matrixStats", "mclust", "methods",
    "minpack.lm", "moments", "msir", "NBPSeq", "nonnest2", "parallel", "penalized",
    "plyr", "pscl", "reshape2", "ROCR", "Rtsne", "scales", "Seurat", "snow",
    "stats", "tibble", "tidyr", "VGAM", "ZIM")
ipak(cranpackages, repository = "CRAN")

# BIOCONDUCTOR
biocpackages <- c("AnnotationDbi", "baySeq", "Biobase", "BiocGenerics", "BiocParallel",
    "DEDS", "DESeq2", "EBSeq", "edgeR", "IHW", "iCOBRA", "limma", "Linnorm",
    "MAST", "monocle", "NOISeq", "qvalue", "ROTS", "RUVSeq", "S4Vectors", "scater",
    "scDD", "scde", "scone", "scran", "SCnorm", "SingleCellExperiment", "SummarizedExperiment",
    "zinbwave")
ipak(biocpackages, repository = "Bioconductor")

# GITHUB
githubpackages <- c("nghiavtr/BPSC", "VCCRI/cidr", "cz-ye/DECENT", "mohuangx/SAVER",
    "statOmics/zingeR")
ipak(githubpackages, repository = "github")
```

After installing the dependencies, powsimR can be installed by using devtools as well.

``` r
devtools::install_github("bvieth/powsimR", build_vignettes = TRUE, dependencies = FALSE)
library("powsimR")
```

Alternative, you can try to install powsimR and its dependencies directly using devtools:

``` r
devtools::install_github("bvieth/powsimR")
```

Some users have experienced issues installing powsimR due to vignette compilation errors. If that is the case, you can leave out building the vignette.

### DLLs and ulimit

Note that the error "maximal number of DLLs reached..." might occur due to the loading of many shared objects by Bioconductor packages. Restarting the R session after installing dependencies / powsimR will help. Starting with R version 3.4.0, one can set the environmental variable 'R\_MAX\_NUM\_DLLS' to a higher number. See `?Startup()` for more information. I recommend to increase the maximum number of DLLs that can be loaded to at least 500. The environmental variable R\_MAX\_NUM\_DLLS can be set in R\_HOME/etc/Renviron prior to starting R. For that locate the Renviron file and add the following line: R\_MAX\_NUM\_DLLS=xy where xy is the number of DLLs. On my Ubuntu machine, the Renviron file is in /usr/lib/R/etc/ and I can set it to 500.

In addition, the user limits for open files (unix: ulimit) might have to be set to a higher number to accomodate the increase in DLLs. Please check out the help pages for [MACs](https://gist.github.com/tombigel/d503800a282fcadbee14b537735d202c) and [Linux](https://glassonionblog.wordpress.com/2013/01/27/increase-ulimit-and-file-descriptors-limit/) for guidance.

User Guide
----------

For examples and tips on using the package, please see the vignette [here](https://github.com/bvieth/powsimR/tree/master/vignettes/powsimR.html)

Citation
--------

Please use the following entry for citing powsimR.

``` r
citation("powsimR")
```

powsimR is published in [Bioinformatics](https://doi.org/10.1093/bioinformatics/btx435). A preprint paper is also on [bioRxiv](https://doi.org/10.1101/117150).

Notes
-----

Please send bug reports and feature requests by opening a new issue on [this page](https://github.com/bvieth/powsimR/issues).

repository: nlawlor/powsimR

repo_name: nlawlor/powsimR


text:
# Angular 5 Monaco Editor Loader
>Build an Angular 5 application with Monaco Editor.

This library allows you to load Monaco Editor in your **Angular v5** apps written in _TypeScript_, _ES6_ or _ES5_.
The project is based on the official _Angular_ packages and xyz.MonacoEditorLoader.

Install with the command:

```
npm i @julceswhat/angular5-monaco-editor-loader
```

An easy to use Monaco Editor Loader Service for Angular 5! Just add `*loadMonacoEditor` in your HTML Element, and you don't have to worry about timing issues!

```
<div *loadMonacoEditor id="container"></div>

```

With custom monaco-editor path
```
<div *loadMonacoEditor="'libs/monaco-editor/vs'" id="container"></div>

```

Get the [Changelog](https://github.com/julceswhat/angular5-monaco-editor-loader/blob/master/CHANGELOG.md).

## Contents
* [1 Prerequisites](#1)
* [2 Using webpack](#2)
* [3 Using Angular CLI](#3)
* [4 Using the Library](#4)
* [5 Running the demo app](#5)
* [6 Motivation](#6)

## 1 Prerequisites

1. Make sure that you are serving `Monaco Editor` in `/assets/monaco-editor/vs`

2. If you are using straight `app.component` then **DO NOT USE the directive**. Instead use the following code in `app.component.ts`:

```
  constructor(private monaco: MonacoEditorLoaderService) {

  }

  this.monaco.isMonacoLoaded.subscribe(value => {
      if (value) {
        // Initialize monaco...
      }
    })
```

3. If you are creating a component on top of monaco, then just use the directive `*loadMonacoEditor` inside your component's HTML

## 2 Using webpack
If you are using `Webpack` do the following:
```
plugins: [
     new CopyWebpackPlugin([
         {
             from: 'node_modules/monaco-editor/min/vs',
             to: './src/assets/monaco',
         }
     ]),
 ],
 ```

## 3 Using Angular CLI

1. For development modify `.angular-cli.json` to the following:
 ```
 "assets": [
        {
          "glob": "**/*",
          "input": "../node_modules/monaco-editor/dev/",
          "output": "./assets/monaco-editor/"
        },
        {
          "glob": "favicon.ico",
          "input": "./",
          "output": "./"
        }
      ]
```

2. For production modify `.angular-cli.json` to the following:
Modify `.angular-cli.json` to the following:
 ```
 "assets": [
        {
          "glob": "**/*",
          "input": "../node_modules/monaco-editor/min/",
          "output": "./assets/monaco-editor/"
        },
        {
          "glob": "**/*",
          "input": "../node_modules/monaco-editor/min-maps/",
          "output": "./assets/min-maps/"
        },
        {
          "glob": "favicon.ico",
          "input": "./",
          "output": "./"
        }
      ]
```

3. Add `/// <reference path="./../node_modules/monaco-editor/monaco.d.ts" />` in you `typings.d.ts` file to remove monaco editor undefined errors and allow compilation.

## 4 Usage

1. In your component's module or app module. Import the following:

```
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MonacoEditorLoaderModule, MonacoEditorLoaderService } from '@julceswhat/angular5-monaco-editor-loader';

import { AppComponent } from './app.component';
import { MonacoEditorComponent } from './monaco-editor/monaco-editor.component';

@NgModule({
  declarations: [
    AppComponent,
    MonacoEditorComponent
  ],
  imports: [
    BrowserModule,
    MonacoEditorLoaderModule <-- Insert this>
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

```

2. Just add `*loadMonacoEditor`, so with your custom component where you plan to create your own monaco component. Just add the following:

```
<monaco-editor *loadMonacoEditor></monaco-editor>
```

3. And in my custom component where I want to host `Monaco Editor` I just do the following like I expect the Monaco library to be loaded at this point:

```
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'monaco-editor',
  templateUrl: './monaco-editor.component.html',
  styleUrls: ['./monaco-editor.component.css']
})
export class MonacoEditorComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
      noSemanticValidation: true,
      noSyntaxValidation: false
    });

    // compiler options
    monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
      target: monaco.languages.typescript.ScriptTarget.ES2016,
      allowNonTsExtensions: true
    });

    // extra libraries
    monaco.languages.typescript.javascriptDefaults.addExtraLib([
      'declare class Facts {',
      '    /**',
      '     * Returns the next fact',
      '     */',
      '    static next():string',
      '}',
    ].join('\n'), 'filename/facts.d.ts');

    var jsCode = [
      '"use strict";',
      '',
      "class Chuck {",
      "    greet() {",
      "        return Facts.next();",
      "    }",
      "}"
    ].join('\n');

    monaco.editor.create(document.getElementById("container"), {
      value: jsCode,
      language: "javascript"
    });
  }

}
```

4. And that's it! No `timeouts`! No `then`! It just goes with the correct flow in Angular!

## 5 Running the demo app
Make sure you have **Angular CLI** installed!

1. Clone this repository
2. `cd demo`
3. `npm install`
4. `ng serve`

## 6 Motivation
I wanted to use Monaco Editor with my Angular 5 project, but couldn't find any library that would help me with this. Since I couldn't find anything, I decided to refactor a library that worked for previous Angular versions.

Most of the code that was found [here](https://github.com/leolorenzoluis/xyz.MonacoEditorLoader) just wasn't working with Angular 5.

## Previous versions
- **Angular v4** & **Angular v2**
    - [Branch](https://github.com/leolorenzoluis/xyz.MonacoEditorLoader)

## License
MIT


text:
Initialize service account for tiller before install

```
helm init
kubectl apply -f core/helm.yaml
cd aleph
helm install .
```

To upgrade:

`helm upgrade reslease-name .`

repository: Ueland/aleph

repo_name: Ueland/aleph


text:
# gistpub

1. Go to https://github.com/settings/tokens and generate a personal token with a `gist` permission.
2. `GH_TOKEN=<your-token> npm start -- <your-username> <target-gist-id-to-append-list-to>`

For an example see https://git.io/gistpub.

license: Unlicense

repository: ilyaigpetrov/gistpub

gha_license_id: Unlicense

repo_name: ilyaigpetrov/gistpub


text:
Installing AppArmor
------------------------

Most of the instructions are from here: https://wiki.debian.org/AppArmor/HowToUse

To manually install the profile for ARMOREProxy in ARMORE you will need to do the following:

1) Install ARMORE First

2) ```sudo apt-get install apparmor apparmor-profiles apparmor-utils```

3) Copy the usr.bin.ARMOREProxy profile to /etc/apparmor.d/

4) ```sudo perl -pi -e 's,GRUB_CMDLINE_LINUX="(.*)"$,GRUB_CMDLINE_LINUX="$1 apparmor=1 security=apparmor",' /etc/default/grub```

5) ```sudo update-grub```

6) ```sudo reboot```

7) Check the status by doing: ```sudo aa-status```

8) By default the profile is in Audit mode, you can change the flag in the file, or do: ```sudo aa-enforce /etc/apparmor.d/usr.bin.ARMOREProxy```

9) ```sudo dmesg``` should also show issues regarding apparmor

repository: GridProtectionAlliance/ARMORE

repo_name: GridProtectionAlliance/ARMORE


text:
# LiveBus
Make it easy to pass data between activity and activity

Usage
--------

**STEP 1**

Add dependency to your gradle file:
```groovy
implementation 'ro0opf.lifeinus:livebus:0.0.2'
```

**STEP 2**

``` java
public class AnyActivity extends AppCompatActivity {
    ...
    LiveBus liveBus = LiveBus.getInstance();

    void function() {
        ...
        liveBus.sendBus(KEY, OBJECT);
        ...
    }
    ...
}
```

``` java
public class MainActivity extends AppCompatActivity {
    ...
    LiveBus liveBus = LiveBus.getInstance();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        liveBus.getBus(KEY).observe(this, o -> {
            // do something
        });
        ...
    }
    ...

    @Override
    void onDestroy() {
        ...
        liveBus.removeBus(KEY);
        ...
    }
    ...
}
```

License
--------

    Copyright 2019 ro0opf, Inc.

    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.

branch_name: refs/heads/develop

gha_language: Java


text:
# IEC 62056-21

[![CircleCI](https://circleci.com/gh/pwitab/iec62056-21/tree/master.svg?style=svg)](https://circleci.com/gh/pwitab/iec62056-21/tree/master)
[![Coverage Status](https://coveralls.io/repos/github/pwitab/iec62056-21/badge.svg)](https://coveralls.io/github/pwitab/iec62056-21)

A Python library for IEC 62056-21, Direct Local Data Exchange of Energy Meters.
Former IEC 61107 or IEC 1107

## Installation

We only support python 3.6+

Install via pip:

```
pip install iec62056-21
```

## About IEC 62056-21

IEC 62056-21 (earlier IEC 61107 or sometimes just IEC 1107, is an international
standard for a computer protocol to read utility meters. It is designed to operate
over any media, including the Internet. A meter sends ASCII (in modes A..D) or
HDLC (mode E) data to a nearby hand-held unit (HHU) using a serial port. The physical
media are usually either modulated light, sent with an LED and received with a
photodiode, or a pair of wires, usually modulated by a 20mA current loop. The protocol
is usually half-duplex.

## Limitations of this library.

* At the moment we only support Mode C.
* We assume that only protocol mode Normal is used.

## Example usage:

Reading a meter using a optical usb probe via the D0-interface.

```python
from iec62056_21.client import Iec6205621Client

client = Iec6205621Client.with_serial_transport(port='/dev/tty_something')
client.connect()
print(client.standard_readout())

```

Reading a meter over an internet connection.
```python
from iec62056_21.client import Iec6205621Client

client = Iec6205621Client.with_tcp_transport(address=('<IP_ADDRESS>', 8000), device_address='12345678', password='00000000')
client.connect()
print(client.standard_readout())
```

## Derivative protocols

Some manufacturer are using a derivative protocol to IEC 62056-21. They comply with
most things but might for example not use the access request features according to
standard or they have a slightly different flow in command execution

This library can be used with some of them. You just need to be aware of the differences.
We provide special handlers for some unique parts that is included in this library.
They might be split into separate libraries in the future.

### LIS-200

A protocol for Elster devices. Main difference is that they have the concept of
locks instead of password and instead of answering the password request you need to
write the password to a certain register.

## Development

This library is developed by Palmlund Wahlgren Innovative Technology AB in Sweden and
is used in our multi utility AMR solution: [Utilitarian](https://docs.utilitarian.io)

## Contributing

*   Check for open issues or open a fresh issue to start a discussion around a feature
    idea or a bug.
*   Fork the repository on GitHub to start making your changes to the master branch (or
    branch off of it).
*   Write a test which shows that the bug was fixed or that the feature works as expected.
*   Send a pull request and bug the maintainer until it gets merged and published.

gha_language: Python


text:
# Develop DL models using Tensorflow and pipelines for industrialization and model serving

# TensorFlow and Google Cloud Platform (GCP) documentations and instructions
- TensorFlow notes
  [Notes](https://github.axa.com/henry-webel/gcp_course_notes/)
- Google Cloud Platform Fundamentals
  [Lectures](https://github.axa.com/henry-webel/gcp_course_notes/blob/master/gcp_fundamentals_lectures.md)
- Google Cloud Platform Instructions
  - Google Cloud Datalab
    [Instructions](https://github.axa.com/henry-webel/gcp_course_notes/blob/master/gcp_datalab.md)

# General presentation and results of this project:
[Documentation](doc/DOC.md)

# Check if your Anaconda/python installation is configured "properly"
[Configuration](doc/SETUP.md)

## How to install the code

### Download the code from GitHub
- go to the directory in which you want to download the package from git
- download the package from Github:
  - ```git clone https://github.com/tarrade/proj_DL_models_and_pipelines_with_GCP.git```
  - or with other method from your choice (web interface, zip ...)
- open an "Anaconda prompt" in the directory that contain the code from GitHub:
  ```your_dir/proj_DL_models_and_pipelines_with_GCP/```

### Create the python conda env
This will provide you a unique list of python packages needed to run the code.
It seems 1.12 is causing trouble on  a Mac, use 1.11 instead

- create a python env based on a list of packages from environment.yml
  ```conda env create -f environment.yml -n env_gcp_dl```

 - activate the env
  ```conda activate env_gcp_dl```

 - in case of issue clean all the cache in conda
   ```conda clean -a -y```

### Update or delete the python conda env
- update a python env based on a list of packages from environment.yml
  ```conda env update -f environment.yml -n env_gcp_dl```

- delete the env to recreate it when too many changes are done
  ```conda env remove -n env_gcp_dl```

### TensorBoard
- open a anaconda prompt
- go to the directory in which you want to download the package from git
- activate the env:
  ```conda activate env_gcp_dl```
- execute TensorBoard:
  ```tensorboard --logdir ./results```
- open a web browser (Firefox) and copy the link that appear in the prompt above:
  ```http://<something>:6006```

 ![alt text](./doc/img/plot1.PNG)
 ![alt text](./doc/img/plot2.PNG)


text:
<img src ="https://user-images.githubusercontent.com/9453/77267767-0aba1a80-6c7a-11ea-8b22-68f945debbd3.png" width="200px" align="right"
/>

# hapi-camper

![GitHub package.json version](https://img.shields.io/github/package-json/v/johnschult/hapi-camper)
![GitHub package.json dependency version (dev dep on branch)](https://img.shields.io/github/package-json/dependency-version/johnschult/hapi-camper/dev/@hapi/hapi)
![GitHub package.json dependency version (prod)](https://img.shields.io/github/package-json/dependency-version/johnschult/hapi-camper/mongoose)
![GitHub](https://img.shields.io/github/license/johnschult/hapi-camper)

![GitHub last commit](https://img.shields.io/github/last-commit/johnschult/hapi-camper)
![Requires.io](https://img.shields.io/requires/github/johnschult/hapi-camper)
![OSS Lifecycle](https://img.shields.io/osslifecycle/johnschult/hapi-camper)
[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)

![Node.js CI](https://github.com/johnschult/hapi-camper/workflows/Node.js%20CI/badge.svg)

## Mongoose Model Hapi Plugin

**hapi-camper** was designed to work seamlessly with the [hapi web framework](https://hapi.dev)
and its other components (but works great on its own or with other frameworks). If you are using
a different web framework and find this module useful, check out [hapi](https://hapi.dev) –
they work even better together.

## Useful resources

- [Documentation and API](https://github.com/johnschult/hapi-camper/blob/master/API.md)
- [Mongoose Models](https://mongoosejs.com/docs/models.html)

## Credits

This project was inspired by and drawn from the work of the following individuals:

- [Andrew G. Silluron](https://github.com/asilluron)
- [Luis Miguel Bula](https://github.com/bulaluis)

repository: johnschult/hapi-camper

repo_name: johnschult/hapi-camper