text:
title: Unity - basic 2D water line
tags: unity
shortdesc: A simple 2D water line in Unity.
---

I just managed to have a 2d water line in Unity 4.3.

I'd like to share a good working base with you, it's not a ready to use solution but it can be a good start for a more complex water line.

It's not that hard to make, but it lacks of buoyancy, droplets, reflection... like I said, it's a start.

Thanks to [http://forum.unity3d.com/threads/141925-2d-Water](http://forum.unity3d.com/threads/141925-2d-Water) and [http://games.deozaan.com/unity/MeshTutorial.pdf](http://games.deozaan.com/unity/MeshTutorial.pdf)

## The idea

The line is a list of dots connected by springs.

Then we create a simple mesh (few triangles) between each pair of dots.

Finally, we update the mesh vertices at each update using the new dots positions.

## The result

Here's the result with the ``Sprite-default`` material:

[ ![wave][wave]][wave]

[ ![editor][editor]][editor]

[ ![wireframe][wireframe]][wireframe]

You can probably apply some shader on it.

## The script

[See on Gist](https://gist.github.com/valryon/7927741)

```csharp
// Author: Damien Mayance (http://dmayance.com)
// 2013 - Pixelnest Studio (http://pixelnest.io)
//
// This script simulates a simple 2d water line behavior, like you see in many 2d games.
// See http://dmayance.com/water-line-2d-unity/ for further explanations.
//
// Usage:
// - Attach it to an object
// - Then fill the "Material" parameter
// - Start the game (here it is only visible at runtime)
//
// The parameters can be modified during runtime, but for EDITOR only.
// The width and height should stay fixed during the game otherwise.
using UnityEngine;
using System.Collections;

public struct WaterLinePart
{
  public float height;
  public float velocity;
  public GameObject gameObject;
  public Mesh mesh;
  public Vector2 boundsMin;
  public Vector2 boundsMax;
}

public class WaterLine : MonoBehaviour
{
  public float velocityDamping = 0.999999f; // Proportional velocity damping, must be less than or equal to 1.
  public float timeScale = 25f;

  public int Width = 50;
  public float Height = 10f;
  public Material material;
  public Color color = Color.blue;

  private WaterLinePart[] parts;

  private int size;
  private float currentHeight;

#if UNITY_EDITOR
  private bool cleanRequested;
#endif

  void Start()
  {

#if UNITY_EDITOR
    // Remove what we see from the editor
    Clear();
#endif

    Initialize();
  }

  private void Initialize()
  {
    size = Width;
    currentHeight = Height;

    material.color = color;

    parts = new WaterLinePart[size];

    // we'll use spheres to represent each vertex for demonstration purposes
    for (int i = 0; i < size; i++)
    {
      // Create a game object
      GameObject go = new GameObject("WavePart");
      go.transform.parent = this.transform;
      go.transform.localPosition = new Vector3(i - (size / 2), 0, 0);

      parts[i].gameObject = go;
    }

    // Create the meshes
    for (int i = 0; i < size; i++)
    {
      GameObject go = parts[i].gameObject;

      // Except for the last point
      if (i < size - 1)
      {
        Mesh mesh = new Mesh();
        mesh.MarkDynamic();
        parts[i].mesh = mesh;

        go.AddComponent<MeshFilter>();
        go.AddComponent<MeshRenderer>();

        // Define vertices for the mesh (the points of the model)
        UpdateMeshVertices(i);

        // Define triangles and normals
        InitializeTrianglesAndNormalsForMesh(i);

        go.GetComponent<MeshFilter>().mesh = mesh;
        go.GetComponent<MeshRenderer>().material = material;
      }
    }

    // Small wave
    Splash(size / 2, 10);
  }

#if UNITY_EDITOR
  /// <summary>
  /// SUPER VIOLENT METHOD FOR EDITOR MODE
  /// </summary>
  private void Clear()
  {
    for (int i = 0; i < size; i++)
    {
      DestroyImmediate(parts[i].mesh);
      DestroyImmediate(parts[i].gameObject);
    }

    parts = null;
  }
#endif

  private void UpdateMeshVertices(int i)
  {
    Mesh mesh = parts[i].mesh;
    if (mesh == null) return;

    Transform current = parts[i].gameObject.transform;

    Transform next = current;
    if (i < parts.Length - 1)
    {
      next = parts[i + 1].gameObject.transform;
    }

    Vector3 left = Vector3.zero;
    Vector3 right = next.localPosition - current.localPosition;

    // Get all parts of the mesh (it's just 2 planes, one on top and one on the front face)
    Vector3 topLeftFront = new Vector3(left.x, left.y, 0);
    Vector3 topRightFront = new Vector3(right.x, right.y, 0);
    Vector3 topLeftBack = new Vector3(left.x, left.y, 1);
    Vector3 topRightBack = new Vector3(right.x, right.y, 1);
    Vector3 bottomLeftFront = new Vector3(left.x, left.y + (0 - Height), 0);
    Vector3 bottomRightFront = new Vector3(right.x, right.y + (0 - Height), 0);

    mesh.vertices = new Vector3[] { topLeftFront, topRightFront, topLeftBack, topRightBack, bottomLeftFront, bottomRightFront };

    parts[i].boundsMin = topLeftFront + current.position;
    parts[i].boundsMax = bottomRightFront + current.position;
  }

  private void InitializeTrianglesAndNormalsForMesh(int i)
  {
    Mesh mesh = parts[i].mesh;
    if (mesh == null) return;

    // Normals
    var uvs = new Vector2[mesh.vertices.Length];
    for (int i2 = 0; i2 < uvs.Length; i2++)
    {
      uvs[i2] = new Vector2(mesh.vertices[i2].x, mesh.vertices[i2].z);
    }
    mesh.uv = uvs;

    // Triangles
    mesh.triangles = new int[] { 5, 4, 0, 0, 1, 5, 0, 2, 3, 3, 1, 0 };

    // For shader
    mesh.RecalculateNormals();
  }

  void Update()
  {
#if UNITY_EDITOR
    // Size has been updated?
    if (Width != size || Height != currentHeight)
    {
      cleanRequested = true;
    }

    // Recalculate everything!
    // This should be for the editor only!
    if (cleanRequested)
    {
      cleanRequested = false;
      Debug.Log("Reinitializing water. Make sure we are in editor mode!");
      Clear();
      Initialize();
    }

    color = material.color;
#endif

    // Water tension is simulated by a simple linear convolution over the height field.
    for (int i = 1; i < size - 1; i++)
    {
#if UNITY_EDITOR
      // Objects deleted from editor
      if (parts[i].gameObject == null)
      {
        cleanRequested = true;
        return;
      }
#endif
      int j = i - 1;
      int k = i + 1;
      parts[i].height = (parts[i].gameObject.transform.localPosition.y + parts[j].gameObject.transform.localPosition.y + parts[k].gameObject.transform.localPosition.y) / 3.0f;
    }

    // Velocity and height are updated...
    for (int i = 0; i < size; i++)
    {
      // update velocity and height
      parts[i].velocity = (parts[i].velocity + (parts[i].height - parts[i].gameObject.transform.localPosition.y)) * velocityDamping;

      float timeFactor = Time.deltaTime * timeScale;
      if (timeFactor > 1f) timeFactor = 1f;

      parts[i].height += parts[i].velocity * timeFactor;

      // Update the dot position
      Vector3 newPosition = new Vector3(
          parts[i].gameObject.transform.localPosition.x,
          parts[i].height,
          parts[i].gameObject.transform.localPosition.z);
      parts[i].gameObject.transform.localPosition = newPosition;
    }

    // Update meshes
    for (int i = 0; i < size; i++)
    {
      UpdateMeshVertices(i);
    }
  }

  #region Interaction

  /// <summary>
  /// Make waves from a point
  /// </summary>
  /// <param name="location"></param>
  /// <param name="force"></param>
  public void Splash(Vector3 location, int force)
  {
    // Find the touched part
    for (int i = 0; i < (size - 1); i++)
    {
      if (location.x >= parts[i].boundsMin.x
        && location.x < parts[i].boundsMax.x)
      {
        if (location.y <= parts[i].boundsMin.y
       && location.y > parts[i].boundsMax.y)
        {
          Splash(i, force);
        }
      }
    }

  }

  private void Splash(int i, int heightModifier)
  {
    parts[i].gameObject.transform.localPosition = new Vector3(
      parts[i].gameObject.transform.localPosition.x,
      parts[i].gameObject.transform.localPosition.y + heightModifier,
      parts[i].gameObject.transform.localPosition.z
      );
  }

  #endregion
}
```

Enjoy! ;)

[editor]: {{site.url}}/static/content/posts/2013-12-12/editor.png

[wireframe]: {{site.url}}/static/content/posts/2013-12-12/wireframe.png

[wave]: {{site.url}}/static/content/posts/2013-12-12/wave.gif


text:
$(document).ready(function() {
	var uid = window.getComputedStyle(document.querySelector('#email-address'), ':after').getPropertyValue('content');
	console.log(uid);
  //use ajax to send to webserver
});

redpajama_set_name: RedPajamaGithub


text:
package smile.math.kernel;

/**
 * A Mercer Kernel is a kernel that is positive semi-definite. When a kernel
 * is positive semi-definite, one may exploit the kernel trick, the idea of
 * implicitly mapping data to a high-dimensional feature space where some
 * linear algorithm is applied that works exclusively with inner products.
 * Assume we have some mapping Φ from an input space X to a feature space H,
 * then a kernel k(u, v) = <Φ(u), Φ(v)> may be used to define the
 * inner product in feature space H.
 * <p>
 * Positive definiteness in the context of kernel functions also implies that
 * a kernel matrix created using a particular kernel is positive semi-definite.
 * A matrix is positive semi-definite if its associated eigenvalues are nonnegative.
 *
 * @author Haifeng Li
 */
public interface MercerKernel<T> {

    /**
     * Kernel function.
     */
    public double k(T x, T y);
}


text:
#pragma once
#include <aws/proton/Proton_EXPORTS.h>
#include <aws/proton/ProtonRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/proton/model/Tag.h>
#include <utility>

namespace Aws
{
namespace Proton
{
namespace Model
{

  /**
   */
  class AWS_PROTON_API CreateComponentRequest : public ProtonRequest
  {
  public:
    CreateComponentRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "CreateComponent"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
An optional customer-provided description of the component.

     */
    inline const Aws::String& GetDescription() const{ return m_description; }

    /**
     *
An optional customer-provided description of the component.

     */
    inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; }

    /**
     *
An optional customer-provided description of the component.

     */
    inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }

    /**
     *
An optional customer-provided description of the component.

     */
    inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); }

    /**
     *
An optional customer-provided description of the component.

     */
    inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }

    /**
     *
An optional customer-provided description of the component.

     */
    inline CreateComponentRequest& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}

    /**
     *
An optional customer-provided description of the component.

     */
    inline CreateComponentRequest& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}

    /**
     *
An optional customer-provided description of the component.

     */
    inline CreateComponentRequest& WithDescription(const char* value) { SetDescription(value); return *this;}

    /**
     *
The name of the Proton environment that you want to associate this component
     * with. You must specify this when you don't specify
     * serviceInstanceName and serviceName.

     */
    inline const Aws::String& GetEnvironmentName() const{ return m_environmentName; }

    /**
     *
The name of the Proton environment that you want to associate this component
     * with. You must specify this when you don't specify
     * serviceInstanceName and serviceName.

     */
    inline bool EnvironmentNameHasBeenSet() const { return m_environmentNameHasBeenSet; }

    /**
     *
The name of the Proton environment that you want to associate this component
     * with. You must specify this when you don't specify
     * serviceInstanceName and serviceName.

     */
    inline void SetEnvironmentName(const Aws::String& value) { m_environmentNameHasBeenSet = true; m_environmentName = value; }

    /**
     *
The name of the Proton environment that you want to associate this component
     * with. You must specify this when you don't specify
     * serviceInstanceName and serviceName.

     */
    inline void SetEnvironmentName(Aws::String&& value) { m_environmentNameHasBeenSet = true; m_environmentName = std::move(value); }

    /**
     *
The name of the Proton environment that you want to associate this component
     * with. You must specify this when you don't specify
     * serviceInstanceName and serviceName.

     */
    inline void SetEnvironmentName(const char* value) { m_environmentNameHasBeenSet = true; m_environmentName.assign(value); }

    /**
     *
The name of the Proton environment that you want to associate this component
     * with. You must specify this when you don't specify
     * serviceInstanceName and serviceName.

     */
    inline CreateComponentRequest& WithEnvironmentName(const Aws::String& value) { SetEnvironmentName(value); return *this;}

    /**
     *
The name of the Proton environment that you want to associate this component
     * with. You must specify this when you don't specify
     * serviceInstanceName and serviceName.

     */
    inline CreateComponentRequest& WithEnvironmentName(Aws::String&& value) { SetEnvironmentName(std::move(value)); return *this;}

    /**
     *
The name of the Proton environment that you want to associate this component
     * with. You must specify this when you don't specify
     * serviceInstanceName and serviceName.

     */
    inline CreateComponentRequest& WithEnvironmentName(const char* value) { SetEnvironmentName(value); return *this;}

    /**
     *
A path to a manifest file that lists the Infrastructure as Code (IaC) file,
     * template language, and rendering engine for infrastructure that a custom
     * component provisions.

     */
    inline const Aws::String& GetManifest() const{ return m_manifest; }

    /**
     *
A path to a manifest file that lists the Infrastructure as Code (IaC) file,
     * template language, and rendering engine for infrastructure that a custom
     * component provisions.

     */
    inline bool ManifestHasBeenSet() const { return m_manifestHasBeenSet; }

    /**
     *
A path to a manifest file that lists the Infrastructure as Code (IaC) file,
     * template language, and rendering engine for infrastructure that a custom
     * component provisions.

     */
    inline void SetManifest(const Aws::String& value) { m_manifestHasBeenSet = true; m_manifest = value; }

    /**
     *
A path to a manifest file that lists the Infrastructure as Code (IaC) file,
     * template language, and rendering engine for infrastructure that a custom
     * component provisions.

     */
    inline void SetManifest(Aws::String&& value) { m_manifestHasBeenSet = true; m_manifest = std::move(value); }

    /**
     *
A path to a manifest file that lists the Infrastructure as Code (IaC) file,
     * template language, and rendering engine for infrastructure that a custom
     * component provisions.

     */
    inline void SetManifest(const char* value) { m_manifestHasBeenSet = true; m_manifest.assign(value); }

    /**
     *
A path to a manifest file that lists the Infrastructure as Code (IaC) file,
     * template language, and rendering engine for infrastructure that a custom
     * component provisions.

     */
    inline CreateComponentRequest& WithManifest(const Aws::String& value) { SetManifest(value); return *this;}

    /**
     *
A path to a manifest file that lists the Infrastructure as Code (IaC) file,
     * template language, and rendering engine for infrastructure that a custom
     * component provisions.

     */
    inline CreateComponentRequest& WithManifest(Aws::String&& value) { SetManifest(std::move(value)); return *this;}

    /**
     *
A path to a manifest file that lists the Infrastructure as Code (IaC) file,
     * template language, and rendering engine for infrastructure that a custom
     * component provisions.

     */
    inline CreateComponentRequest& WithManifest(const char* value) { SetManifest(value); return *this;}

    /**
     *
The customer-provided name of the component.

     */
    inline const Aws::String& GetName() const{ return m_name; }

    /**
     *
The customer-provided name of the component.

     */
    inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }

    /**
     *
The customer-provided name of the component.

     */
    inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }

    /**
     *
The customer-provided name of the component.

     */
    inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }

    /**
     *
The customer-provided name of the component.

     */
    inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }

    /**
     *
The customer-provided name of the component.

     */
    inline CreateComponentRequest& WithName(const Aws::String& value) { SetName(value); return *this;}

    /**
     *
The customer-provided name of the component.

     */
    inline CreateComponentRequest& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}

    /**
     *
The customer-provided name of the component.

     */
    inline CreateComponentRequest& WithName(const char* value) { SetName(value); return *this;}

    /**
     *
The name of the service instance that you want to attach this component to.
     * If you don't specify this, the component isn't attached to any service instance.
     * Specify both serviceInstanceName and serviceName or
     * neither of them.

     */
    inline const Aws::String& GetServiceInstanceName() const{ return m_serviceInstanceName; }

    /**
     *
The name of the service instance that you want to attach this component to.
     * If you don't specify this, the component isn't attached to any service instance.
     * Specify both serviceInstanceName and serviceName or
     * neither of them.

     */
    inline bool ServiceInstanceNameHasBeenSet() const { return m_serviceInstanceNameHasBeenSet; }

    /**
     *
The name of the service instance that you want to attach this component to.
     * If you don't specify this, the component isn't attached to any service instance.
     * Specify both serviceInstanceName and serviceName or
     * neither of them.

     */
    inline void SetServiceInstanceName(const Aws::String& value) { m_serviceInstanceNameHasBeenSet = true; m_serviceInstanceName = value; }

    /**
     *
The name of the service instance that you want to attach this component to.
     * If you don't specify this, the component isn't attached to any service instance.
     * Specify both serviceInstanceName and serviceName or
     * neither of them.

     */
    inline void SetServiceInstanceName(Aws::String&& value) { m_serviceInstanceNameHasBeenSet = true; m_serviceInstanceName = std::move(value); }

    /**
     *
The name of the service instance that you want to attach this component to.
     * If you don't specify this, the component isn't attached to any service instance.
     * Specify both serviceInstanceName and serviceName or
     * neither of them.

     */
    inline void SetServiceInstanceName(const char* value) { m_serviceInstanceNameHasBeenSet = true; m_serviceInstanceName.assign(value); }

    /**
     *
The name of the service instance that you want to attach this component to.
     * If you don't specify this, the component isn't attached to any service instance.
     * Specify both serviceInstanceName and serviceName or
     * neither of them.

     */
    inline CreateComponentRequest& WithServiceInstanceName(const Aws::String& value) { SetServiceInstanceName(value); return *this;}

    /**
     *
The name of the service instance that you want to attach this component to.
     * If you don't specify this, the component isn't attached to any service instance.
     * Specify both serviceInstanceName and serviceName or
     * neither of them.

     */
    inline CreateComponentRequest& WithServiceInstanceName(Aws::String&& value) { SetServiceInstanceName(std::move(value)); return *this;}

    /**
     *
The name of the service instance that you want to attach this component to.
     * If you don't specify this, the component isn't attached to any service instance.
     * Specify both serviceInstanceName and serviceName or
     * neither of them.

     */
    inline CreateComponentRequest& WithServiceInstanceName(const char* value) { SetServiceInstanceName(value); return *this;}

    /**
     *
The name of the service that serviceInstanceName is associated
     * with. If you don't specify this, the component isn't attached to any service
     * instance. Specify both serviceInstanceName and
     * serviceName or neither of them.

     */
    inline const Aws::String& GetServiceName() const{ return m_serviceName; }

    /**
     *
The name of the service that serviceInstanceName is associated
     * with. If you don't specify this, the component isn't attached to any service
     * instance. Specify both serviceInstanceName and
     * serviceName or neither of them.

     */
    inline bool ServiceNameHasBeenSet() const { return m_serviceNameHasBeenSet; }

    /**
     *
The name of the service that serviceInstanceName is associated
     * with. If you don't specify this, the component isn't attached to any service
     * instance. Specify both serviceInstanceName and
     * serviceName or neither of them.

     */
    inline void SetServiceName(const Aws::String& value) { m_serviceNameHasBeenSet = true; m_serviceName = value; }

    /**
     *
The name of the service that serviceInstanceName is associated
     * with. If you don't specify this, the component isn't attached to any service
     * instance. Specify both serviceInstanceName and
     * serviceName or neither of them.

     */
    inline void SetServiceName(Aws::String&& value) { m_serviceNameHasBeenSet = true; m_serviceName = std::move(value); }

    /**
     *
The name of the service that serviceInstanceName is associated
     * with. If you don't specify this, the component isn't attached to any service
     * instance. Specify both serviceInstanceName and
     * serviceName or neither of them.

     */
    inline void SetServiceName(const char* value) { m_serviceNameHasBeenSet = true; m_serviceName.assign(value); }

    /**
     *
The name of the service that serviceInstanceName is associated
     * with. If you don't specify this, the component isn't attached to any service
     * instance. Specify both serviceInstanceName and
     * serviceName or neither of them.

     */
    inline CreateComponentRequest& WithServiceName(const Aws::String& value) { SetServiceName(value); return *this;}

    /**
     *
The name of the service that serviceInstanceName is associated
     * with. If you don't specify this, the component isn't attached to any service
     * instance. Specify both serviceInstanceName and
     * serviceName or neither of them.

     */
    inline CreateComponentRequest& WithServiceName(Aws::String&& value) { SetServiceName(std::move(value)); return *this;}

    /**
     *
The name of the service that serviceInstanceName is associated
     * with. If you don't specify this, the component isn't attached to any service
     * instance. Specify both serviceInstanceName and
     * serviceName or neither of them.

     */
    inline CreateComponentRequest& WithServiceName(const char* value) { SetServiceName(value); return *this;}

    /**
     *
The service spec that you want the component to use to access service inputs.
     * Set this only when you attach the component to a service instance.

     */
    inline const Aws::String& GetServiceSpec() const{ return m_serviceSpec; }

    /**
     *
The service spec that you want the component to use to access service inputs.
     * Set this only when you attach the component to a service instance.

     */
    inline bool ServiceSpecHasBeenSet() const { return m_serviceSpecHasBeenSet; }

    /**
     *
The service spec that you want the component to use to access service inputs.
     * Set this only when you attach the component to a service instance.

     */
    inline void SetServiceSpec(const Aws::String& value) { m_serviceSpecHasBeenSet = true; m_serviceSpec = value; }

    /**
     *
The service spec that you want the component to use to access service inputs.
     * Set this only when you attach the component to a service instance.

     */
    inline void SetServiceSpec(Aws::String&& value) { m_serviceSpecHasBeenSet = true; m_serviceSpec = std::move(value); }

    /**
     *
The service spec that you want the component to use to access service inputs.
     * Set this only when you attach the component to a service instance.

     */
    inline void SetServiceSpec(const char* value) { m_serviceSpecHasBeenSet = true; m_serviceSpec.assign(value); }

    /**
     *
The service spec that you want the component to use to access service inputs.
     * Set this only when you attach the component to a service instance.

     */
    inline CreateComponentRequest& WithServiceSpec(const Aws::String& value) { SetServiceSpec(value); return *this;}

    /**
     *
The service spec that you want the component to use to access service inputs.
     * Set this only when you attach the component to a service instance.

     */
    inline CreateComponentRequest& WithServiceSpec(Aws::String&& value) { SetServiceSpec(std::move(value)); return *this;}

    /**
     *
The service spec that you want the component to use to access service inputs.
     * Set this only when you attach the component to a service instance.

     */
    inline CreateComponentRequest& WithServiceSpec(const char* value) { SetServiceSpec(value); return *this;}

    /**
     *
An optional list of metadata items that you can associate with the Proton
     * component. A tag is a key-value pair.

For more information, see Proton
     * resources and tagging in the Proton
     * Administrator Guide or Proton
     * User Guide.

     */
    inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; }

    /**
     *
An optional list of metadata items that you can associate with the Proton
     * component. A tag is a key-value pair.

For more information, see Proton
     * resources and tagging in the Proton
     * Administrator Guide or Proton
     * User Guide.

     */
    inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; }

    /**
     *
An optional list of metadata items that you can associate with the Proton
     * component. A tag is a key-value pair.

For more information, see Proton
     * resources and tagging in the Proton
     * Administrator Guide or Proton
     * User Guide.

     */
    inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; }

    /**
     *
An optional list of metadata items that you can associate with the Proton
     * component. A tag is a key-value pair.

For more information, see Proton
     * resources and tagging in the Proton
     * Administrator Guide or Proton
     * User Guide.

     */
    inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); }

    /**
     *
An optional list of metadata items that you can associate with the Proton
     * component. A tag is a key-value pair.

For more information, see Proton
     * resources and tagging in the Proton
     * Administrator Guide or Proton
     * User Guide.

     */
    inline CreateComponentRequest& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;}

    /**
     *
An optional list of metadata items that you can associate with the Proton
     * component. A tag is a key-value pair.

For more information, see Proton
     * resources and tagging in the Proton
     * Administrator Guide or Proton
     * User Guide.

     */
    inline CreateComponentRequest& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;}

    /**
     *
An optional list of metadata items that you can associate with the Proton
     * component. A tag is a key-value pair.

For more information, see Proton
     * resources and tagging in the Proton
     * Administrator Guide or Proton
     * User Guide.

     */
    inline CreateComponentRequest& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; }

    /**
     *
An optional list of metadata items that you can associate with the Proton
     * component. A tag is a key-value pair.

For more information, see Proton
     * resources and tagging in the Proton
     * Administrator Guide or Proton
     * User Guide.

     */
    inline CreateComponentRequest& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(std::move(value)); return *this; }

    /**
     *
A path to the Infrastructure as Code (IaC) file describing infrastructure
     * that a custom component provisions.

Components support a single
     * IaC file, even if you use Terraform as your template language.

     */
    inline const Aws::String& GetTemplateFile() const{ return m_templateFile; }

    /**
     *
A path to the Infrastructure as Code (IaC) file describing infrastructure
     * that a custom component provisions.

Components support a single
     * IaC file, even if you use Terraform as your template language.

     */
    inline bool TemplateFileHasBeenSet() const { return m_templateFileHasBeenSet; }

    /**
     *
A path to the Infrastructure as Code (IaC) file describing infrastructure
     * that a custom component provisions.

Components support a single
     * IaC file, even if you use Terraform as your template language.

     */
    inline void SetTemplateFile(const Aws::String& value) { m_templateFileHasBeenSet = true; m_templateFile = value; }

    /**
     *
A path to the Infrastructure as Code (IaC) file describing infrastructure
     * that a custom component provisions.

Components support a single
     * IaC file, even if you use Terraform as your template language.

     */
    inline void SetTemplateFile(Aws::String&& value) { m_templateFileHasBeenSet = true; m_templateFile = std::move(value); }

    /**
     *
A path to the Infrastructure as Code (IaC) file describing infrastructure
     * that a custom component provisions.

Components support a single
     * IaC file, even if you use Terraform as your template language.

     */
    inline void SetTemplateFile(const char* value) { m_templateFileHasBeenSet = true; m_templateFile.assign(value); }

    /**
     *
A path to the Infrastructure as Code (IaC) file describing infrastructure
     * that a custom component provisions.

Components support a single
     * IaC file, even if you use Terraform as your template language.

     */
    inline CreateComponentRequest& WithTemplateFile(const Aws::String& value) { SetTemplateFile(value); return *this;}

    /**
     *
A path to the Infrastructure as Code (IaC) file describing infrastructure
     * that a custom component provisions.

Components support a single
     * IaC file, even if you use Terraform as your template language.

     */
    inline CreateComponentRequest& WithTemplateFile(Aws::String&& value) { SetTemplateFile(std::move(value)); return *this;}

    /**
     *
A path to the Infrastructure as Code (IaC) file describing infrastructure
     * that a custom component provisions.

Components support a single
     * IaC file, even if you use Terraform as your template language.

     */
    inline CreateComponentRequest& WithTemplateFile(const char* value) { SetTemplateFile(value); return *this;}

  private:

    Aws::String m_description;
    bool m_descriptionHasBeenSet;

    Aws::String m_environmentName;
    bool m_environmentNameHasBeenSet;

    Aws::String m_manifest;
    bool m_manifestHasBeenSet;

    Aws::String m_name;
    bool m_nameHasBeenSet;

    Aws::String m_serviceInstanceName;
    bool m_serviceInstanceNameHasBeenSet;

    Aws::String m_serviceName;
    bool m_serviceNameHasBeenSet;

    Aws::String m_serviceSpec;
    bool m_serviceSpecHasBeenSet;

    Aws::Vector<Tag> m_tags;
    bool m_tagsHasBeenSet;

    Aws::String m_templateFile;
    bool m_templateFileHasBeenSet;
  };

} // namespace Model
} // namespace Proton
} // namespace Aws


text:
#include "igt.h"
#include <limits.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <errno.h>

IGT_TEST_DESCRIPTION("Tests the DRM_IOCTL_GET_CLIENT ioctl.");

igt_simple_main
{
	int fd, ret;
	drm_client_t client;

	fd = drm_open_driver(DRIVER_ANY);

	/* Look for client index 0.  This should exist whether we're operating
	 * on an otherwise unused drm device, or the X Server is running on
	 * the device.
	 */
	client.idx = 0;
	ret = ioctl(fd, DRM_IOCTL_GET_CLIENT, &client);
	igt_assert(ret == 0);

	/* Look for some absurd client index and make sure it's invalid.
	 * The DRM drivers currently always return data, so the user has
	 * no real way to detect when the list has terminated.  That's bad,
	 * and this test is XFAIL as a result.
	 */
	client.idx = 0x7fffffff;
	ret = ioctl(fd, DRM_IOCTL_GET_CLIENT, &client);
	igt_assert(ret == -1 && errno == EINVAL);

	close(fd);
}


text:
namespace ash {
namespace eche_app {

class FakeEcheMessageReceiver : public EcheMessageReceiver {
 public:
  FakeEcheMessageReceiver();
  ~FakeEcheMessageReceiver() override;

  void FakeGetAppsAccessStateResponse(proto::Result result,
                                      proto::AppsAccessState status);
  void FakeSendAppsSetupResponse(proto::Result result,
                                 proto::AppsAccessState status);
  void FakeStatusChange(proto::StatusChangeType status_change_type);

 private:
  using EcheMessageReceiver::NotifyGetAppsAccessStateResponse;
  using EcheMessageReceiver::NotifySendAppsSetupResponse;
  using EcheMessageReceiver::NotifyStatusChange;
};

}  // namespace eche_app
}  // namespace ash

#endif  // ASH_WEBUI_ECHE_APP_UI_FAKE_ECHE_MESSAGE_RECEIVER_H_


text:
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}

module Duckling.Rules.KO
  ( rules
  ) where

import Duckling.Dimensions.Types
import qualified Duckling.AmountOfMoney.KO.Rules as AmountOfMoney
import qualified Duckling.Distance.KO.Rules as Distance
import qualified Duckling.Duration.KO.Rules as Duration
import qualified Duckling.Numeral.KO.Rules as Numeral
import qualified Duckling.Ordinal.KO.Rules as Ordinal
import qualified Duckling.Quantity.KO.Rules as Quantity
import qualified Duckling.Temperature.KO.Rules as Temperature
import qualified Duckling.Time.KO.Rules as Time
import qualified Duckling.TimeGrain.KO.Rules as TimeGrain
import Duckling.Types
import qualified Duckling.Volume.KO.Rules as Volume

rules :: Some Dimension -> [Rule]
rules (This Distance) = Distance.rules
rules (This Duration) = Duration.rules
rules (This Numeral) = Numeral.rules
rules (This Email) = []
rules (This AmountOfMoney) = AmountOfMoney.rules
rules (This Ordinal) = Ordinal.rules
rules (This PhoneNumber) = []
rules (This Quantity) = Quantity.rules
rules (This RegexMatch) = []
rules (This Temperature) = Temperature.rules
rules (This Time) = Time.rules
rules (This TimeGrain) = TimeGrain.rules
rules (This Url) = []
rules (This Volume) = Volume.rules


text:
'use strict';
/**
 * Created by antoinelucas on 12/05/2016.
 */
var jwt = require('jwt-simple'),
  config = require('./../../../config/config'),
  _ = require('lodash');

exports.hasRole = function (roles) {
  return function (req, res, next) {
    var token = (req.body && req.body.access_token) ||
      (req.query && req.access_token) ||
      (req.headers[config.jwt.authHeaderName]);

    if (token) {
      try {
        var decoded = jwt.decode(token, config.jwt.secret);
        if (_.isString(roles)) {
          roles = [roles];
        }
        if (decoded.roles && _.intersection(decoded.roles, roles).length > 1) {
          next();
        }
      } catch(err) {
        res.send(401, { err: 'Invalid authorization token' });
      }
    } else {
      res.send(401, { err: 'Invalid authorization token' });
    }
  };
};


text:
let val = 1

function decorateA<O extends any>(fn: (first: {value: typeof val}) => O) {
    return (): O => fn({value: val})
}
let a = decorateA(({value}) => 5)

function decorateB<O extends any>(fn: (first: typeof val) => O) {
    return (): O => fn(val)
}
let b = decorateB((value) => 5)

function decorateC<O extends any>(fn: (first: {value: number}) => O) {
    return (): O => fn({value: val})
}
let c = decorateC(({value}) => 5)

type First = {value: typeof val}
function decorateD<O extends any>(fn: (first: First) => O) {
    return (): O => fn({value: val})
}
let d = decorateD(({value}) => 5)

//// [typeofObjectInference.js]
var val = 1;
function decorateA(fn) {
    return function () { return fn({ value: val }); };
}
var a = decorateA(function (_a) {
    var value = _a.value;
    return 5;
});
function decorateB(fn) {
    return function () { return fn(val); };
}
var b = decorateB(function (value) { return 5; });
function decorateC(fn) {
    return function () { return fn({ value: val }); };
}
var c = decorateC(function (_a) {
    var value = _a.value;
    return 5;
});
function decorateD(fn) {
    return function () { return fn({ value: val }); };
}
var d = decorateD(function (_a) {
    var value = _a.value;
    return 5;
});


text:
#include <aws/apigateway/model/Model.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace APIGateway
{
namespace Model
{

Model::Model() :
    m_idHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_schemaHasBeenSet(false),
    m_contentTypeHasBeenSet(false)
{
}

Model::Model(JsonView jsonValue) :
    m_idHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_schemaHasBeenSet(false),
    m_contentTypeHasBeenSet(false)
{
  *this = jsonValue;
}

Model& Model::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("id"))
  {
    m_id = jsonValue.GetString("id");

    m_idHasBeenSet = true;
  }

  if(jsonValue.ValueExists("name"))
  {
    m_name = jsonValue.GetString("name");

    m_nameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("description"))
  {
    m_description = jsonValue.GetString("description");

    m_descriptionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("schema"))
  {
    m_schema = jsonValue.GetString("schema");

    m_schemaHasBeenSet = true;
  }

  if(jsonValue.ValueExists("contentType"))
  {
    m_contentType = jsonValue.GetString("contentType");

    m_contentTypeHasBeenSet = true;
  }

  return *this;
}

JsonValue Model::Jsonize() const
{
  JsonValue payload;

  if(m_idHasBeenSet)
  {
   payload.WithString("id", m_id);

  }

  if(m_nameHasBeenSet)
  {
   payload.WithString("name", m_name);

  }

  if(m_descriptionHasBeenSet)
  {
   payload.WithString("description", m_description);

  }

  if(m_schemaHasBeenSet)
  {
   payload.WithString("schema", m_schema);

  }

  if(m_contentTypeHasBeenSet)
  {
   payload.WithString("contentType", m_contentType);

  }

  return payload;
}

} // namespace Model
} // namespace APIGateway
} // namespace Aws


text:
""" Execute MMLF experiments

This module contains an operation and a process for MMLF. One MMLF
process consists of a executing one run of a predefined number of
episodes of a MMLF world. An MMLF operation consists of one or several runs of
one or several MMLF worlds.

.. note:: The results of the runs are not stored in the standard operation
    result directories but in the MMLF ReadWrite Area. Only the outputs of the
    MMLF to stdout are stored in log files stored in the operation result
    directories.

.. todo:: documentation link to MMLF-framework

:Author: Jan-Hendrik Metzen

"""

import sys
import os
import time
import csv
import xml.etree.ElementTree as ElementTree
if sys.version_info[0] == 2 and sys.version_info[1] < 6:
    import processing
else:
    import multiprocessing as processing

import pySPACE
from pySPACE.missions.operations.base import Operation, Process

class MmlfOperation(Operation):
    """ Operation class for executing MMLF experiments.

    An MMLF operation consists of one or several runs of
    one or several MMLF worlds.
    """
    def __init__(self, processes, operation_spec, result_directory,
                 world_name, number_processes, create_process=None):
        super(MmlfOperation, self).__init__(processes, operation_spec,
                                            result_directory)

        self.world_name = world_name
        self.number_processes = number_processes
        self.create_process = create_process

    @classmethod
    def create(cls, operation_spec, result_directory, debug=False, input_paths=[]):
        """
        A factory method that creates an MMLF operation based on the
        information given in the operation specification operation_spec
        """
        assert(operation_spec["type"] == "mmlf")

        # The generic world configuration YAML file
        world_conf = """
worldPackage : %s
environment:
%s
agent:
%s
monitor:
    policyLogFrequency : 100000
%s
"""
        # Create directory for the experiment
        world_name = operation_spec['world_name']
        world_path = "%s/config/%s" % (result_directory, world_name)
        if not os.path.exists(world_path):
            os.makedirs(world_path)

        # Compute all possible parameter combinations
        # Determine all parameter combinations that should be tested
        parameter_settings = cls._get_parameter_space(operation_spec)

        # If the operation spec defines parameters for a generalized domain:
        if "generalized_domain" in operation_spec:
            # We have to test each parameter setting in each instantiation of
            # the generalized domain. This can be achieved by computing the
            # crossproduct of parameter settings and domain settings
            augmented_parameter_settings = []
            for parameter_setting in parameter_settings:
                for domain_parameter_setting in operation_spec["generalized_domain"]:
                    instantiation = dict(parameter_setting)
                    instantiation.update(domain_parameter_setting)
                    augmented_parameter_settings.append(instantiation)
            parameter_settings = augmented_parameter_settings

        # Create and remember all worlds for the given  parameter_settings
        world_pathes = []

        # for all parameter setting
        for parameter_setting in parameter_settings:
            # Add 4 blanks to all lines in templates
            environment_template = operation_spec['environment_template']
            environment_template = \
                    "\n".join("    " + line
                                for line in environment_template.split("\n"))
            agent_template = operation_spec['agent_template']
            agent_template = \
                    "\n".join("    " + line
                                for line in agent_template.split("\n"))
            monitor_conf = \
                operation_spec['monitor_conf'] if 'monitor_conf' in operation_spec else ""
            monitor_conf = \
                    "\n".join("    " + line
                                for line in monitor_conf.split("\n"))

            # Instantiate the templates
            environment_conf = environment_template
            agent_conf = agent_template
            for parameter, value in parameter_setting.iteritems():
                environment_conf = environment_conf.replace(parameter, str(value))
                agent_conf = agent_conf.replace(parameter, str(value))

            def get_parameter_str(parameter_name):
                return "".join(subpart[:4]
                                    for subpart in  parameter_name.split("_"))
            configuration_str = "{" + "}{".join(["%s:%s" % (get_parameter_str(parameter),
                                                            str(value)[:6])
                                        for parameter, value in parameter_setting.iteritems()]) + "}"
            configuration_str = configuration_str.replace('_','')

            world_file_name = "world_%s.yaml" %  configuration_str

            open(os.path.join(world_path, world_file_name),
                 'w').write(world_conf % (world_name, environment_conf,
                                          agent_conf, monitor_conf))
            world_pathes.append(os.path.join(world_path, world_file_name))

        number_processes = len(world_pathes)*int(operation_spec["runs"])

        if debug is True:
            # To better debug creation of processes we don't limit the queue
            # and create all processes before executing them
            processes = processing.Queue()
            cls._createProcesses(processes, world_pathes, operation_spec,
                                 result_directory)
            return cls( processes, operation_spec, result_directory,
                                            world_name, number_processes)
        else:
            # Create all processes by calling a recursive helper method
            # in another thread so that already created processes can be
            # executed although creation of processes is not finished yet.
            # Therefor a queue is used which size is limited to guarantee that
            # not to much objects are created (since this costs memory).
            # However, the actual number of 100 is arbitrary and might be
            # changed according to the system at hand.
            processes = processing.Queue(100)
            create_process = processing.Process(target =
                cls._createProcesses, args=( processes, world_pathes,
                                operation_spec, result_directory))
            create_process.start()
            # create and return the operation object
            return cls( processes, operation_spec, result_directory,
                        world_name, number_processes, create_process)

    @classmethod
    def _createProcesses(cls, processes, world_pathes, operation_spec,
                         result_directory):
        """Function that creates the mmlf process. """
        # For each created world, perform operation_spec["runs"] runs
        for world_conf_path in world_pathes:
            for run_number in range(operation_spec["runs"]):
                process = MMLFProcess(mmlf_path=operation_spec["mmlf_path"],
                                      world_conf_path=world_conf_path,
                                      learning_episodes=operation_spec["learning_episodes"],
                                      test_episodes=operation_spec["test_episodes"],
                                      result_directory=result_directory)
                processes.put(process)
        # give executing process the sign that creation is now finished
        processes.put(False)

    def consolidate(self):
        """ Consolidates the results of the MMLF operation."""
        return  # Consolidation into a csv-file currently not supported.
        # Consolidate the results in an csv table
        output_file = open(os.path.join(self.result_directory,
                                        'results.csv'), 'w')
        results_writer = csv.writer(output_file)

        # Determine directory in which the operation's results are stored
        log_dir = os.path.join(self.result_directory, 'logs', self.world_name)

        # For all configurations tested
        keys = None
        for conf_dir in [os.path.join(log_dir, name) for name in os.listdir(log_dir)
                           if os.path.isdir(os.path.join(log_dir, name))]:
            # Read agent configuration dict
            agent_conf = ElementTree.parse(os.path.join(conf_dir, 'agent.xml'))
            conf_dict = dict(agent_conf.getroot().find('configDict').items())

            # Read environment configuration dict
            env_conf = ElementTree.parse(os.path.join(conf_dir, 'env.xml'))
            conf_dict.update(dict(env_conf.getroot().find('configDict').items()))

            # Evaluate the values of all dict entries
            for key, value in conf_dict.iteritems():
                conf_dict[key] = eval(value)

            # Flatten (potentially) nested dict
            expanded_conf_dict = MmlfOperation._flatten_dict(conf_dict)

            if keys is None:
                keys = expanded_conf_dict.keys()
                # TODO: Currently hard coded
                keys.append('reward')
                keys.append('accumulated_reward')
                keys.append('offline_reward')
                keys.append('offline_accumulated_reward')
                results_writer.writerow(keys)

            # For all runs conducted with this setup
            for run_dir in [os.path.join(conf_dir, name) for name in os.listdir(conf_dir)
                                if os.path.isdir(os.path.join(conf_dir, name))]:
                # Read in the accumulated reward per episode file
                reward_file = \
                    open(os.path.join(run_dir, 'environment_logs', 'reward'),
                         'r')
                rewards = [eval(row) for row in reward_file.readlines()]
                # Chop off overlong sequences
                rewards = rewards[:self.operation_spec["learning_episodes"]]

                expanded_conf_dict['reward'] = rewards
                expanded_conf_dict['accumulated_reward'] = sum(rewards)

                # Read in the accumulated reward per episode file of the
                # offline test
                offline_reward_file = \
                    open(os.path.join(run_dir, 'environment_logs',
                                      'offlineReward'),'r')
                offline_rewards = [eval(row) for row in offline_reward_file.readlines()]
                # Chop off overlong sequences
                offline_rewards = offline_rewards[:self.operation_spec["test_episodes"]]

                expanded_conf_dict['offline_reward'] = offline_rewards
                expanded_conf_dict['offline_accumulated_reward'] = sum(offline_rewards)

                results_writer.writerow([expanded_conf_dict[key] for key in keys])

        output_file.close()

    @classmethod
    def _flatten_dict(cls, input_dict):
        """ Flatten the (potentially) nested dict *input_dict* """
        flattened_dict = dict()
        for key, value in input_dict.iteritems():
            if type(value) == dict:
                value = cls._flatten_dict(value)
                for subkey, subvalue in value.iteritems():
                    flattened_dict[key + '_' + subkey] = subvalue
            else:
                flattened_dict[key] = value
        return flattened_dict

class MMLFProcess(Process):
    """ Process for executing an MMLF run

    One MMLF process consists of a executing one run of a predefined number of
    episodes of a MMLF world.

    The following **parameters** are mandatory:

      :mmlf_path: The path to the MMLF code
      :world_conf_path:   The relative path of the world configuration file
                          within the specified MMLF rw area
      :learning_episodes:   The number of episodes the MMLF agent is allowed
                            to train (i.e. optimize its policy)
      :test_episodes:   The number of episodes the learned policy is tested.
                        This can be set to 1 for deterministic environments.
      :result_directory:   The directory where the stdout of the MMLF run is
                           stored
    """

    def __init__(self, mmlf_path, world_conf_path, learning_episodes,
                 test_episodes, result_directory):

        super(MMLFProcess, self).__init__()

        self.result_directory = result_directory

        self.mmlf_path = mmlf_path
        self.world_conf_path = world_conf_path
        self.learning_episodes = learning_episodes
        self.test_episodes = test_episodes

        self.handler_class = None

    def __call__(self):
        """ Executes this process on the respective modality """
        # Restore configuration
        pySPACE.configuration = self.configuration

        ############## Prepare benchmarking ##############
        super(MMLFProcess, self).pre_benchmarking()

        # Redirect stdout to a log file
        process_log_file_name = "%s/%s_%s" % (self.result_directory,
                                              time.strftime("%Y%m%d_%H_%M_%S"),
                                              os.getpid())
        log_file = open(process_log_file_name, 'w')
        sys.stdout = log_file
        sys.stderr = log_file
        # Insert path to MMLF to python search path and import it
        sys.path.insert(0, self.mmlf_path)
        mmlf = __import__("mmlf")

        # On distributed file systems, it might happen that our configuration
        # file is not yet available on the machine where this process is
        # executed
        while not os.path.exists(self.world_conf_path):
            mmlf.log.warn("Config file %s not yet available on local machine"
                                                        % self.world_conf_path)
            time.sleep(1)

        mmlf.initializeRWArea(rwPath=self.result_directory)

        # Create and start world
        world = mmlf.loadWorldFromConfigFile(self.world_conf_path, useGUI=False)
        try:
            world.run(self.learning_episodes)
        except Exception, e:
            mmlf.log.error("An exception of type %s occurred: %s"
                                                    % (e.__class__.__name__, e))
            print __import__("traceback").print_exc()
        # Stop the world
        world.stop()

        # Restore stdout
        sys.stdout.flush()
        sys.stdout = sys.__stdout__

        ############## Clean up after benchmarking ##############
        super(MMLFProcess, self).post_benchmarking()


text:
layout: post
title: ASP.NET Core Tutorial (4) Entity Framework Core
author: Andy Feng
---

# Update #
update EF Core tools, vs -> Tools –> NuGet Package Manager –> Package Manager Console

Install-Package Microsoft.EntityFrameworkCore.Tools -Version 2.1.4

reverse database to entities

Scaffold-DbContext "Data Source=67.224.94.82,4108; Initial Catalog=TweebaaScheduler; MultipleActiveResultSets=True; User Id=wnTweebaa; Password=Tweebaawebapp2014!2016" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Entities\Tweebaa


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

import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.events.Location;
import com.google.devtools.build.lib.syntax.EvalException;
import com.google.devtools.build.lib.syntax.FuncallExpression;
import com.google.devtools.build.lib.syntax.MethodDescriptor;
import java.util.Map;

/** Base class for native implementations of {@link Info}. */
// todo(vladmos,dslomov): make abstract once DefaultInfo stops instantiating it.
public class NativeInfo extends Info {
  protected final ImmutableMap<String, Object> values;

  // Initialized lazily.
  private ImmutableSet<String> fieldNames;

  @Override
  public Object getValue(String name) throws EvalException {
    if (values.containsKey(name)) {
      return values.get(name);
    } else if (hasField(name)) {
      MethodDescriptor methodDescriptor = FuncallExpression.getStructField(this.getClass(), name);
      try {
        return FuncallExpression.invokeStructField(methodDescriptor, name, this);
      } catch (InterruptedException exception) {
        // Struct fields on NativeInfo objects are supposed to behave well and not throw
        // exceptions, as they should be logicless field accessors. If this occurs, it's
        // indicative of a bad NativeInfo implementation.
        throw new IllegalStateException(
            String.format("Access of field %s was unexpectedly interrupted, but should be "
                + "uninterruptible. This is indicative of a bad provider implementation.", name));
      }
    } else {
      return null;
    }
  }

  @Override
  public boolean hasField(String name) {
    return getFieldNames().contains(name);
  }

  @Override
  public ImmutableCollection<String> getFieldNames() {
    if (fieldNames == null) {
      fieldNames = ImmutableSet.<String>builder()
          .addAll(values.keySet())
          .addAll(FuncallExpression.getStructFieldNames(this.getClass()))
          .build();
    }
    return fieldNames;
  }

  public NativeInfo(Provider provider) {
    this(provider, Location.BUILTIN);
  }

  public NativeInfo(Provider provider, Location loc) {
    this(provider, ImmutableMap.of(), loc);
  }

  // TODO(cparsons): Remove this constructor once ToolchainInfo stops using it.
  @Deprecated
  public NativeInfo(Provider provider, Map<String, Object> values, Location loc) {
    super(provider, loc);
    this.values = copyValues(values);
  }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using ExtensionBlocks;

namespace RegistryPlugin.Taskband.ShellItems
{
    public class ShellBag0Xc3 : ShellBag
    {
        public ShellBag0Xc3(byte[] rawBytes)
        {
            FriendlyName = "Network location";

            ExtensionBlocks = new List<IExtensionBlock>();

            var index = 0;

            var size = BitConverter.ToUInt16(rawBytes, index);
            index += 2;

            var classtypeIndicator = rawBytes[index] & 0x70;
            index += 1;

            var unknown1 = rawBytes[index];
            index += 1;

            var flags = rawBytes[index];
            index += 1;

            var len = 0;

            while (rawBytes[index + len] != 0x0)
            {
                len += 1;
            }

            var tempBytes = new byte[len];
            Array.Copy(rawBytes, index, tempBytes, 0, len);

            index += len;

            var location = CodePagesEncodingProvider.Instance.GetEncoding(1252).GetString(tempBytes);

            while (rawBytes[index] == 0x0)
            {
                index += 1;
                if (index >= rawBytes.Length)
                {
                    break;
                }
            }

            //TODO there is still more here. finish this
            //4D-69-63-72-6F-73-6F-66-74-20-4E-65-74-77-6F-72-6B-00-00-02-00-00-00
            //M-i-c-r-o-s-o-f-t- -N-e-t-w-o-r-k------

            Value = location;
        }

        public override string ToString()
        {
            var sb = new StringBuilder();

            sb.AppendLine(base.ToString());

            return sb.ToString();
        }
    }
}


text:
using System;
using System.Reflection;
using KSP.Localization;

namespace LanguagePatches
{
    public static class FakeLocalizer
    {
        private static MethodInfo _Format = typeof(Localizer).GetMethod("_Format", BindingFlags.NonPublic | BindingFlags.Instance);

        /// <summary>
        /// A static empty array, so we don't have to create a new one every time Format gets called
        /// </summary>
        private static String[] empty = new String[0];

        /// <summary>
        /// Integrates the regex based translations into the official system
        /// </summary>
        public static String Format(String template)
        {
            String output = (String)_Format.Invoke(Localizer.Instance, new Object[] { template, empty });
            if (output == template)
                return template;
            return LanguagePatches.Translate(output, null);
        }

        /// <summary>
        /// Integrates the regex based translations into the official system
        /// </summary>
        public static String Format(String template, params String[] list)
        {
            String output = (String)_Format.Invoke(Localizer.Instance, new Object[] { template, list });
            if (output == template)
                return template;
            return LanguagePatches.Translate(output, null);
        }

        /// <summary>
        /// Integrates the regex based translations into the official system
        /// </summary>
        public static String Format(String template, params Object[] list)
        {
            String[] array = new String[list.Length];
            for (Int32 i = 0; i < list.Length; i++)
            {
                array[i] = list[i].ToString();
            }
            String output = (String)_Format.Invoke(Localizer.Instance, new Object[] { template, array });
            if (output == template)
                return template;
            return LanguagePatches.Translate(output, null);
        }
    }
}


text:
var AppDispatcher = require('../bootstrap').MortarJS.Dispatcher;
var AppActionConstants = require('../constants/AppActionConstants');
var ResourceApi = require('../utils/ResourceApi');

var ResourceActions = function (resource) {
	this.resource = resource;
};

/**
 * Options to modify the request:
 *
 * dataNode: name of property of data if nested JSON object
 * modifiers: query params to modify request, e.g. filters, include, query, etc
 */
ResourceActions.prototype.options = {};

/**
 * The resource operation currently being performed. One of: ['receive', 'create', 'update', 'deactivate']
 */
ResourceActions.prototype.resourceOperation = '';

/**
 * Count returned objects to properly name events
 *
 * @param data
 * @returns {string}
 * @todo remove and leave an event name override
 */
ResourceActions.prototype.count = function (data) {
	return data.length === 1 ? 'ONE' : 'ALL';
};

/**
 * Build an event name string for the dispatcher
 *
 * @returns {string}
 * @private
 */
ResourceActions.prototype._buildEventName = function () {
	var operation = this.resourceOperation.toUpperCase();
	return operation[operation.length - 1] === 'E' ? operation + 'D' : operation + 'ED';
};

/**
 * Determine an appropriate callback based on how we want to handle responses
 *
 * @param options
 * @returns {function(this:ResourceActions)}
 * @private
 */
ResourceActions.prototype._findAppropriateCallback = function (options) {
	if (typeof options.refresh === 'undefined') {
		return this.receiveResource.bind(this);
	} else if (options.refresh === 'list') {
		return this.refreshResourceList.bind(this);
	} else if (options.refresh === 'single') {
		return this.refreshResource.bind(this);
	}
};

/**
 * Accept response and dispatch an appropriately named event.
 *
 * @param data
 */
ResourceActions.prototype.receiveResource = function (data, paginationData) {
	paginationData = paginationData || {};

	var eventName = this.eventName ||
			this.resource.toUpperCase() + '_' + this._buildEventName(),
		eventData = this.eventData || null;
	// If this.resource isn't available here to dispatch an event, save it in a separate store?
	AppDispatcher.dispatch({
		type: eventName,
		eventData: eventData,
		data: data,
		paginationData: paginationData
	});
};

/**
 * Retrieve a resource by ID (GET)
 *
 * @param resource
 * @param options
 */
ResourceActions.prototype.getResource =  function (id, options) {
	this.options = options;
	this.resourceOperation = 'receive';
	if (options.eventName) this.eventName = options.eventName;
	if (options.eventData) this.eventData = options.eventData;

	ResourceApi.getResource(this.resource, id, options, this.receiveResource.bind(this));
};

/**
 * Retreive a list of resources (GET)
 *
 * @param options
 */
ResourceActions.prototype.listResource = function (options) {
	this.options = options;
	this.resourceOperation = 'list';
	if (options.eventName) this.eventName = options.eventName;
	if (options.eventData) this.eventData = options.eventData;

	ResourceApi.listResource(this.resource, options, this.receiveResource.bind(this));
};

/**
 * Create a resource (POST)
 *
 * @param resource
 * @param data
 * @param options
 * @todo should this refresh?
 */
ResourceActions.prototype.createResource = function (resource, options) {
	this.options = options;
	this.resourceOperation = 'create';
	ResourceApi.createResource(this.resource, resource, options, this._findAppropriateCallback(options));
};

/**
 * Update a resource (PUT)
 *
 * @param resource
 * @param data
 * @param options
 */
ResourceActions.prototype.updateResource = function (resource, options) {
	this.options = options;
	this.resourceOperation = 'update';
	ResourceApi.updateResource(this.resource, resource, options, this._findAppropriateCallback(options));
};

/**
 * Deactivate a resource (DELETE)
 *
 * @param resource
 * @param data
 * @param options
 */
ResourceActions.prototype.deactivateResource = function (resource, options) {
	this.options = options;
	this.resourceOperation = 'deactivate';
	ResourceApi.deactivateResource(this.resource, resource, options, this._findAppropriateCallback(options));
};

/**
 * Accept a response, filter it through, and begin a request to refresh data
 *
 * @param data
 */
ResourceActions.prototype.refreshResource = function (data) {
	this.receiveResource(data);
	this.getResource(this.resource, this.options);
};

/**
 * Accept a response, filter it through, and begin a request to refresh data
 *
 * @param data
 */
ResourceActions.prototype.refreshResourceList = function (data) {
	this.listResource(this.options);
};

module.exports = ResourceActions;


text:
module Rack
  # The Rack protocol version number implemented.
  VERSION = [1,1]

  # Return the Rack protocol version as a dotted string.
  def self.version
    VERSION.join(".")
  end

  # Return the Rack release as a dotted string.
  def self.release
    "1.3"
  end

  autoload :Builder, "rack/builder"
  autoload :BodyProxy, "rack/body_proxy"
  autoload :Cascade, "rack/cascade"
  autoload :Chunked, "rack/chunked"
  autoload :CommonLogger, "rack/commonlogger"
  autoload :ConditionalGet, "rack/conditionalget"
  autoload :Config, "rack/config"
  autoload :ContentLength, "rack/content_length"
  autoload :ContentType, "rack/content_type"
  autoload :ETag, "rack/etag"
  autoload :File, "rack/file"
  autoload :Deflater, "rack/deflater"
  autoload :Directory, "rack/directory"
  autoload :ForwardRequest, "rack/recursive"
  autoload :Handler, "rack/handler"
  autoload :Head, "rack/head"
  autoload :Lint, "rack/lint"
  autoload :Lock, "rack/lock"
  autoload :Logger, "rack/logger"
  autoload :MethodOverride, "rack/methodoverride"
  autoload :Mime, "rack/mime"
  autoload :NullLogger, "rack/nulllogger"
  autoload :Recursive, "rack/recursive"
  autoload :Reloader, "rack/reloader"
  autoload :Runtime, "rack/runtime"
  autoload :Sendfile, "rack/sendfile"
  autoload :Server, "rack/server"
  autoload :ShowExceptions, "rack/showexceptions"
  autoload :ShowStatus, "rack/showstatus"
  autoload :Static, "rack/static"
  autoload :URLMap, "rack/urlmap"
  autoload :Utils, "rack/utils"
  autoload :Multipart, "rack/multipart"

  autoload :MockRequest, "rack/mock"
  autoload :MockResponse, "rack/mock"

  autoload :Request, "rack/request"
  autoload :Response, "rack/response"

  module Auth
    autoload :Basic, "rack/auth/basic"
    autoload :AbstractRequest, "rack/auth/abstract/request"
    autoload :AbstractHandler, "rack/auth/abstract/handler"
    module Digest
      autoload :MD5, "rack/auth/digest/md5"
      autoload :Nonce, "rack/auth/digest/nonce"
      autoload :Params, "rack/auth/digest/params"
      autoload :Request, "rack/auth/digest/request"
    end
  end

  module Session
    autoload :Cookie, "rack/session/cookie"
    autoload :Pool, "rack/session/pool"
    autoload :Memcache, "rack/session/memcache"
  end
end


text:
<resources>
    <string name="app_name">BeaconDemo</string>
</resources>


text:
require "bootstrap_sb_admin_base_v2/version"

module BootstrapSbAdminBaseV2
  module Rails
    class Engine < ::Rails::Engine
      require "font-awesome-rails"
    end
  end
end


text:
<?php

namespace Gedmo\Tree\Entity\Repository;

use Gedmo\Exception\InvalidArgumentException,
    Gedmo\Tree\Strategy,
    Gedmo\Tree\Strategy\ORM\MaterializedPath,
    Gedmo\Tool\Wrapper\EntityWrapper;

/**
 * The MaterializedPathRepository has some useful functions
 * to interact with MaterializedPath tree. Repository uses
 * the strategy used by listener
 *
 * @author Gustavo Falco <comfortablynumb84@gmail.com>
 * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
 * @package Gedmo.Tree.Entity.Repository
 * @subpackage MaterializedPathRepository
 * @link http://www.gediminasm.org
 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
class MaterializedPathRepository extends AbstractTreeRepository
{
    /**
     * Get tree query builder
     *
     * @return Doctrine\ORM\QueryBuilder
     */
    public function getTreeQueryBuilder()
    {
        return $this->getChildrenQueryBuilder();
    }

    /**
     * Get tree query
     *
     * @return Doctrine\ORM\Query
     */
    public function getTreeQuery()
    {
        return $this->getTreeQueryBuilder()->getQuery();
    }

    /**
     * Get tree
     *
     * @return array
     */
    public function getTree()
    {
        return $this->getTreeQuery()->execute();
    }

    /**
     * Get all root nodes query builder
     *
     * @return Doctrine\ORM\QueryBuilder
     */
    public function getRootNodesQueryBuilder($sortByField = null, $direction = 'asc')
    {
        return $this->getChildrenQueryBuilder(null, true, $sortByField, $direction);
    }

    /**
     * Get all root nodes query
     *
     * @return Doctrine\ORM\Query
     */
    public function getRootNodesQuery($sortByField = null, $direction = 'asc')
    {
        return $this->getRootNodesQueryBuilder($sortByField, $direction)->getQuery();
    }

    /**
     * Get all root nodes
     *
     * @return array
     */
    public function getRootNodes($sortByField = null, $direction = 'asc')
    {
        return $this->getRootNodesQuery($sortByField, $direction)->execute();
    }

    /**
     * Get children from node
     *
     * @return Doctrine\ORM\QueryBuilder
     */
    public function getChildrenQueryBuilder($node = null, $direct = false, $sortByField = null, $direction = 'asc')
    {
        $meta = $this->getClassMetadata();
        $config = $this->listener->getConfiguration($this->_em, $meta->name);
        $separator = addcslashes($config['path_separator'], '%');
        $alias = 'materialized_path_entity';
        $path = $config['path'];
        $qb = $this->_em->createQueryBuilder($meta->name)
            ->select($alias)
            ->from($meta->name, $alias);

        if (is_object($node) && $node instanceof $meta->name) {
            $node = new EntityWrapper($node, $this->_em);
            $nodePath = $node->getPropertyValue($path);
            $expr = $qb->expr()->andx()->add(
                $qb->expr()->like($alias.'.'.$path, $qb->expr()->literal($nodePath.'%'))
            );
            $expr->add($qb->expr()->neq($alias.'.'.$path, $qb->expr()->literal($nodePath)));

            if ($direct) {
                $expr->add(
                    $qb->expr()->not(
                        $qb->expr()->like($alias.'.'.$path, $qb->expr()->literal($nodePath.'%'.$separator.'%'.$separator))
                ));
            }

            $qb->where('('.$expr.')');
        } else if ($direct) {
            $expr = $qb->expr()->not(
                $qb->expr()->like($alias.'.'.$path, $qb->expr()->literal('%'.$separator.'%'.$separator.'%'))
            );
            $qb->where('('.$expr.')');
        }

        $orderByField = is_null($sortByField) ? $alias.'.'.$config['path'] : $alias.'.'.$sortByField;
        $orderByDir = $direction === 'asc' ? 'asc' : 'desc';
        $qb->orderBy($orderByField, $orderByDir);

        return $qb;
    }

    /**
     * Get children query
     *
     * @return Doctrine\ORM\Query
     */
    public function getChildrenQuery($node = null, $direct = false, $sortByField = null, $direction = 'asc')
    {
        return $this->getChildrenQueryBuilder($node, $direct, $sortByField, $direction)->getQuery();
    }

    /**
     * Get children
     *
     * @return array
     */
    public function getChildren($node = null, $direct = false, $sortByField = null, $direction = 'asc')
    {
        return $this->getChildrenQuery($node, $direct, $sortByField, $direction)->execute();
    }

    /**
     * {@inheritdoc}
     */
    protected function validate()
    {
        return $this->listener->getStrategy($this->_em, $this->getClassMetadata()->name)->getName() === Strategy::MATERIALIZED_PATH;
    }
}


text:
package dom.asistencia;

import java.util.Date;
import java.util.List;

import org.apache.isis.applib.DomainObjectContainer;
import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.Hidden;
import org.apache.isis.applib.annotation.MemberOrder;
import org.apache.isis.applib.annotation.Named;
import org.apache.isis.applib.annotation.PublishedAction;
import org.apache.isis.applib.annotation.PublishedObject;

@Named("Contabilizar Asistencia")
@DomainService(menuOrder = "90")
public class ContabilizarAsistenciasService {

	// region > identification in the UI
	@Hidden
	public String getId() {
		return "contarAsistencia";
	}

	public String title() {
		return "Contabilizar Asistencia";
	}

	public String iconName() {
		return "SimpleObject";
	}

	// endregion

	@MemberOrder(sequence = "2")
	@PublishedAction
	public ContabilizarAsistenciasView contarAsistenciasCurso(
			@Named("Esquema") Asistencia esquema, @Named("Curso") Curso curso,
			@Named("Desde") Date desde, @Named("Hasta") Date hasta) {

		// memento: esquema, anio, division, desde, hasta

		String mementoString = esquema.getDescripcion() + "," + curso.getAnio()
				+ "," + curso.getDivision() + ","
				+ TraductorService.DateToString(desde) + ","
				+ TraductorService.DateToString(hasta) + ",-1";

		return container.newViewModelInstance(
				ContabilizarAsistenciasView.class, mementoString);
	}

	public List<Asistencia> choices0ContarAsistenciasCurso() {

		return container.allInstances(Asistencia.class);
	}

	public Asistencia default0ContarAsistenciasCurso() {

		return choices0ContarAsistenciasCurso().get(0);
	}

	public List<Curso> choices1ContarAsistenciasCurso() {

		return CursoRepositorio.querylistAll();
	}

	public Curso default1ContarAsistenciasCurso() {

		return choices1ContarAsistenciasCurso().get(0);
	}

	// region > injected services
	// //////////////////////////////////////

	@javax.inject.Inject
	static DomainObjectContainer container;

	// endregion
}


text:
{% extends "bootstrap/base.html" %}
{% block title %}Flasky{% endblock %}
{% block navbar %}

            Douban Test

主页

                {% if current_user.is_authenticated %}

注销

                {% else %}

登录

                {% endif %}

{% endblock %}

{% block content %}

    {% for message in get_flashed_messages() %}

        <button type="button" class="close" data-dismiss="alert">×</button>
        {{ message }}

    {% endfor %}

    {% block page_content %}{% endblock %}

{% endblock %}


text:
import {ConstantNode, Node, Tensor} from './graph';
import * as priority_queue from './priority_queue';
import {PriorityQueue} from './priority_queue';
import {TensorArrayMap} from './tensor_array_map';

/**
 * Given a target node in a graph, accumulate the set of all nodes that need to
 * be evaluated in order to evaluate the target graph. Traversal stops anywhere
 * a node's values are fed in externally via "feed dicts".
 * @param nodes The nodes to be evaluated.
 * @param terminatingNodes The set of nodes that stop traversal.
 * @return The unordered set of nodes that need to be evaluated.
 */
export function getUnorderedEvaluationSet(
    nodes: Node[], terminatingNodes: Node[]): Node[] {
  const terminatingNodeMap: {[id: number]: Node} = {};
  const seen: {[id: number]: Node} = {};
  const set: Node[] = [];
  const visit: Node[] = nodes.slice();
  terminatingNodes.forEach(node => terminatingNodeMap[node.id] = node);
  /* Flood fill: While the 'to visit' stack is not empty, pop a node off of it.
   * If the node has not yet been visited, add it to the set, mark it as seen,
   * and enqueue all of its ancestor (input) nodes. */
  while (visit.length !== 0) {
    const cur = visit.pop();
    if (seen[cur.id] == null) {
      if (terminatingNodeMap[cur.id] == null) {
        Object.keys(cur.inputs)
            .map(inputName => cur.inputs[inputName])
            .forEach(input => visit.push(input.node));
      }
      set.push(cur);
      seen[cur.id] = cur;
    }
  }
  return set;
}

/**
 * Given a set of nodes, compute their order such that all dependent nodes are
 * evaluated after their dependees. This is the 'inference order' for nodes in
 * the operation graph.
 * @param unorderedEvaluationSet The unordered set of nodes that need to be
 * evaluated.
 * @return The input nodes in forward evaluation order.
 */
export function getOrderedEvaluationSet(unorderedEvaluationSet: Node[]):
    Node[] {
  /* A priority queue is used, where the priority is the remaining number of
   * unevaluated nodes whose inputs come from the element node. This guarantees
   * that all downstream nodes will be dequeued before their ancestors. */
  const set: Node[] = [];
  const nodeIndices: {[id: number]: number} = {};
  const pendingDependencies: {[id: number]: number} = {};

  /* The queue priority callback looks at the number of pending dependencies of
   * a given node. The queue index observer callback maintains the location of
   * each node in the array, for priority updates. */
  const nodeQueue = new PriorityQueue<Node>(
      (a: Node, b: Node) => priority_queue.defaultCompare(
          pendingDependencies[a.id], pendingDependencies[b.id]),
      (node: Node, newIndex: number) => nodeIndices[node.id] = newIndex);

  unorderedEvaluationSet.forEach(node => pendingDependencies[node.id] = 0);

  /* For every descendent of a node (output of ancestor is input to descendant),
   * increment the 'pending dependency count' for the ancestor. This prepares
   * the 'pending dependency count' as a priority map. */
  unorderedEvaluationSet.forEach(
      node => Object.keys(node.inputs)
                  .map(key => node.inputs[key])
                  .forEach(input => {
                    if (unorderedEvaluationSet.indexOf(input.node) !== -1) {
                      pendingDependencies[input.node.id]++;
                    }
                  }));

  unorderedEvaluationSet.forEach(node => nodeQueue.enqueue(node));

  while (!nodeQueue.empty()) {
    set.unshift(nodeQueue.dequeue());
    /* As each node is visited, decrement the 'pending dependency count' of
     * each ancestor, and tell the priority queue that the priority has changed.
     */
    Object.keys(set[0].inputs).map(key => set[0].inputs[key]).forEach(input => {
      if (unorderedEvaluationSet.indexOf(input.node) === -1) {
        return;
      }
      pendingDependencies[input.node.id]--;
      nodeQueue.update(input.node, nodeIndices[input.node.id]);
    });
  }

  return set;
}

/**
 * @return True iff the node is an input node.
 */
export function isInputNode(node: Node): boolean {
  return Object.keys(node.inputs).length === 0;
}

export function shouldBackProp(t: Tensor): boolean {
  return !(t.node instanceof ConstantNode);
}

export function isPassthroughNode(node: Node, map: TensorArrayMap): boolean {
  const keys = Object.keys(node.inputs);
  for (let i = 0; i < keys.length; i++) {
    const input = node.inputs[keys[i]];
    if (map.get(input, true) === map.get(node.output, true)) {
      return true;
    }
  }
  return false;
}


text:
[![Build Status][travis-image]][travis]

Convenient module for storing and querying time series statistics in Redis using Node.js.

The design (and even parts of the implementation) were picked from the [ApiAxle](http://blog.apiaxle.com/post/storing-near-realtime-stats-in-redis/) project.

You can find basic usage examples in `examples`. This module also powers a [real-time dashboard](https://github.com/tonyskn/node-dashboard) written in Node.js. Check the sources out for more insight.

## Dependencies

`redis-timeseries` has no dependencies, and will work along the `redis` module you'll install in your own project. `redis@~0.9.0` versions are compatible.

## Usage

```javascript
	var TimeSeries = require('redis-timeseries'),
		redis = require('redis').createClient();

	// Create the TimeSeries client
	//
	// "stats" is the Redis namespace which will be used
	// for storing all the TimeSeries related keys
    //
	// "granularities" encodes the granularities at which
	// you want to store statistics. More on that in the next section
	//
	var ts = new TimeSeries(redis, "stats", granularities);

	// Recording hits
	//
	// This increments the counters for the
	// stats keys you provide
	//
	// "timestamp" defaults to the current time
    // "increment" defaults to 1
	//
	ts.recordHit('your_stats_key')
	  .recordHit('another_stats_key', timestamp)
      .recordHit('another_stats_key', timestamp2, increment)
	  …
	  .exec();

    // Removing hits
    //
    // It's also possible to decrement the hits counter for
    // some key
    ts.removeHit('your_stats_key', [timestamp]).exec();

    // Recording values
	//
	// This sets the value for the
	// stats keys you provide
	//
	// "timestamp" defaults to the current time
    // "increment" defaults to 1
	//
	ts.recordValue('your_stats_key', value)
	  .recordValue('another_stats_key', value, timestamp)
      .recordValue('another_stats_key', value, timestamp2, increment)
	  …
	  .exec();

	// Querying statistics
	//
	// Returns "count" chunks of counters at the precision described by
	// "granularity_label"
	//
	ts.getHits('your_stats_key', granularity_label, count, function(err, data) {
		// data.length == count
		// data = [ [ts1, count1], [ts2, count2]... ]
	});

	// getValues is identical to getHits except that it returns a null value for unset timestamps
	ts.getValues('your_stats_key', granularity_label, count, function(err, data) {
		// data.length == count
		// data = [ [ts1, count1], [ts2, count2]... ]
	});
```

## Defining custom statistics granularities

For each key, `TimeSeries` stores statistics at different granularities. For further information about this, please refer to the detailed [blog post](http://blog.apiaxle.com/post/storing-near-realtime-stats-in-redis/) from the ApiAxle project.

The default granularities are:

```javascript
{
    '1second'  : { ttl: this.minutes(5), duration: 1 },
    '1minute'  : { ttl: this.hours(1)  , duration: this.minutes(1) },
    '5minutes' : { ttl: this.days(1)   , duration: this.minutes(5) },
    '10minutes': { ttl: this.days(1)   , duration: this.minutes(10) },
    '1hour'    : { ttl: this.days(7)   , duration: this.hours(1) },
    '1day'     : { ttl: this.weeks(52) , duration: this.days(1) }
}
```

This means that the number of `hits per second` will be stored for `5 minutes`, and the corresponding hashset will expire afterwards.  Likewise, the number of `hits per minute` for a given key will be kept for an `hour`.  `Daily` counters on the other hand are kept for a full year.

When querying for statistics, a granularity label is expected:

```javascript
	// Give me the hits/second for the last 3 minutes
	ts.getHits('your_stats_key', '1second', ts.minutes(3), callback);

	// Give me the number of hits per day for the last 2 weeks
	ts.getHits('your_stats_key', '1day', 14, callback);

	// And so on
```

When creating the `TimeSeries` client, you can override the default granularities with your own.

[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/tonyskn/node-redis-timeseries/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

[travis]: http://travis-ci.org/tonyskn/node-redis-timeseries
[travis-image]: https://travis-ci.org/tonyskn/node-redis-timeseries.png


text:
* Patch: Changed the session handling to use a mongo db instead of an in-memory store.
* Patch: Updated reference to grasshopper core to latest version
* Patch: #10 Fixed deprecated warnings from the sessions npm


text:
@implementation UIColor (extension)

+ (UIColor*) colorWithHex:(NSInteger)hexValue alpha:(CGFloat)alphaValue
{
    return [UIColor colorWithRed:((float)((hexValue & 0xFF0000) >> 16))/255.0
                           green:((float)((hexValue & 0xFF00) >> 8))/255.0
                            blue:((float)(hexValue & 0xFF))/255.0 alpha:alphaValue];
}

+ (UIColor*) colorWithHex:(NSInteger)hexValue
{
    return [UIColor colorWithHex:hexValue alpha:1.0];
}

+ (NSString *) hexFromUIColor: (UIColor*) color {
    if (CGColorGetNumberOfComponents(color.CGColor) < 4) {
        const CGFloat *components = CGColorGetComponents(color.CGColor);
        color = [UIColor colorWithRed:components[0]
                                green:components[0]
                                 blue:components[0]
                                alpha:components[1]];
    }

    if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {
        return [NSString stringWithFormat:@"#FFFFFF"];
    }

    return [NSString stringWithFormat:@"#%x%x%x", (int)((CGColorGetComponents(color.CGColor))[0]*255.0),
            (int)((CGColorGetComponents(color.CGColor))[1]*255.0),
            (int)((CGColorGetComponents(color.CGColor))[2]*255.0)];
}

@end


text:
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Model = Discord.API.Webhook;

namespace Discord.Webhook
{
    [DebuggerDisplay(@"{DebuggerDisplay,nq}")]
    internal class RestInternalWebhook : IWebhook
    {
        private DiscordWebhookClient _client;

        public ulong Id { get; }
        public ulong ChannelId { get; }
        public string Token { get; }

        public string Name { get; private set; }
        public string AvatarId { get; private set; }
        public ulong? GuildId { get; private set; }

        public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id);

        internal RestInternalWebhook(DiscordWebhookClient apiClient, Model model)
        {
            _client = apiClient;
            Id = model.Id;
            ChannelId = model.Id;
            Token = model.Token;
        }
        internal static RestInternalWebhook Create(DiscordWebhookClient client, Model model)
        {
            var entity = new RestInternalWebhook(client, model);
            entity.Update(model);
            return entity;
        }

        internal void Update(Model model)
        {
            if (model.Avatar.IsSpecified)
                AvatarId = model.Avatar.Value;
            if (model.GuildId.IsSpecified)
                GuildId = model.GuildId.Value;
            if (model.Name.IsSpecified)
                Name = model.Name.Value;
        }

        public string GetAvatarUrl(ImageFormat format = ImageFormat.Auto, ushort size = 128)
           => CDN.GetUserAvatarUrl(Id, AvatarId, size, format);

        public async Task ModifyAsync(Action<WebhookProperties> func, RequestOptions options = null)
        {
            var model = await WebhookClientHelper.ModifyAsync(_client, func, options).ConfigureAwait(false);
            Update(model);
        }

        public Task DeleteAsync(RequestOptions options = null)
            => WebhookClientHelper.DeleteAsync(_client, options);

        public override string ToString() => $"Webhook: {Name}:{Id}";
        private string DebuggerDisplay => $"Webhook: {Name} ({Id})";

        IUser IWebhook.Creator => null;
        ITextChannel IWebhook.Channel => null;
        IGuild IWebhook.Guild => null;
    }
}


text:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

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

/**
 * CodeIgniter HTML Helpers
 *
 * @package        CodeIgniter
 * @subpackage    Helpers
 * @category    Helpers
 * @author        EllisLab Dev Team
 * @link        http://codeigniter.com/user_guide/helpers/html_helper.html
 */

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

/**
 * Heading
 *
 * Generates an HTML heading tag.  First param is the data.
 * Second param is the size of the heading tag.
 *
 * @access    public
 * @param    string
 * @param    integer
 * @return    string
 */
if (!function_exists('heading')) {
    function heading($data = '', $h = '1', $attributes = '')
    {
        $attributes = ($attributes != '') ? ' ' . $attributes : $attributes;
        return "<h" . $h . $attributes . ">" . $data . "</h" . $h . ">";
    }
}

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

/**
 * Unordered List
 *
 * Generates an HTML unordered list from an single or multi-dimensional array.
 *
 * @access    public
 * @param    array
 * @param    mixed
 * @return    string
 */
if (!function_exists('ul')) {
    function ul($list, $attributes = '')
    {
        return _list('ul', $list, $attributes);
    }
}

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

/**
 * Ordered List
 *
 * Generates an HTML ordered list from an single or multi-dimensional array.
 *
 * @access    public
 * @param    array
 * @param    mixed
 * @return    string
 */
if (!function_exists('ol')) {
    function ol($list, $attributes = '')
    {
        return _list('ol', $list, $attributes);
    }
}

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

/**
 * Generates the list
 *
 * Generates an HTML ordered list from an single or multi-dimensional array.
 *
 * @access    private
 * @param    string
 * @param    mixed
 * @param    mixed
 * @param    integer
 * @return    string
 */
if (!function_exists('_list')) {
    function _list($type = 'ul', $list, $attributes = '', $depth = 0)
    {
        // If an array wasn't submitted there's nothing to do...
        if (!is_array($list)) {
            return $list;
        }

        // Set the indentation based on the depth
        $out = str_repeat(" ", $depth);

        // Were any attributes submitted?  If so generate a string
        if (is_array($attributes)) {
            $atts = '';
            foreach ($attributes as $key => $val) {
                $atts .= ' ' . $key . '="' . $val . '"';
            }
            $attributes = $atts;
        } elseif (is_string($attributes) AND strlen($attributes) > 0) {
            $attributes = ' ' . $attributes;
        }

        // Write the opening list tag
        $out .= "<" . $type . $attributes . ">\n";

        // Cycle through the list elements.  If an array is
        // encountered we will recursively call _list()

        static $_last_list_item = '';
        foreach ($list as $key => $val) {
            $_last_list_item = $key;

            $out .= str_repeat(" ", $depth + 2);
            $out .= "
";

            if (!is_array($val)) {
                $out .= $val;
            } else {
                $out .= $_last_list_item . "\n";
                $out .= _list($type, $val, '', $depth + 4);
                $out .= str_repeat(" ", $depth + 2);
            }

            $out .= "
\n";
        }

        // Set the indentation for the closing tag
        $out .= str_repeat(" ", $depth);

        // Write the closing list tag
        $out .= "</" . $type . ">\n";

        return $out;
    }
}

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

/**
 * Generates HTML BR tags based on number supplied
 *
 * @access    public
 * @param    integer
 * @return    string
 */
if (!function_exists('br')) {
    function br($num = 1)
    {
        return str_repeat("
", $num);
    }
}

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

/**
 * Image
 *
 * Generates an  element
 *
 * @access    public
 * @param    mixed
 * @return    string
 */
if (!function_exists('img')) {
    function img($src = '', $index_page = FALSE)
    {
        if (!is_array($src)) {
            $src = array('src' => $src);
        }

        // If there is no alt attribute defined, set it to an empty string
        if (!isset($src['alt'])) {
            $src['alt'] = '';
        }

        $img = ' $v) {

            if ($k == 'src' AND strpos($v, '://') === FALSE) {
                $CI =& get_instance();

                if ($index_page === TRUE) {
                    $img .= ' src="' . $CI->config->site_url($v) . '"';
                } else {
                    $img .= ' src="' . $CI->config->slash_item('base_url') . $v . '"';
                }
            } else {
                $img .= " $k=\"$v\"";
            }
        }

        $img .= '/>';

        return $img;
    }
}

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

/**
 * Doctype
 *
 * Generates a page document type declaration
 *
 * Valid options are xhtml-11, xhtml-strict, xhtml-trans, xhtml-frame,
 * html4-strict, html4-trans, and html4-frame.  Values are saved in the
 * doctypes config file.
 *
 * @access    public
 * @param    string    type    The doctype to be generated
 * @return    string
 */
if (!function_exists('doctype')) {
    function doctype($type = 'xhtml1-strict')
    {
        global $_doctypes;

        if (!is_array($_doctypes)) {
            if (defined('ENVIRONMENT') AND is_file(APPPATH . 'config/' . ENVIRONMENT . '/doctypes.php')) {
                include(APPPATH . 'config/' . ENVIRONMENT . '/doctypes.php');
            } elseif (is_file(APPPATH . 'config/doctypes.php')) {
                include(APPPATH . 'config/doctypes.php');
            }

            if (!is_array($_doctypes)) {
                return FALSE;
            }
        }

        if (isset($_doctypes[$type])) {
            return $_doctypes[$type];
        } else {
            return FALSE;
        }
    }
}

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

/**
 * Link
 *
 * Generates link to a CSS file
 *
 * @access    public
 * @param    mixed    stylesheet hrefs or an array
 * @param    string    rel
 * @param    string    type
 * @param    string    title
 * @param    string    media
 * @param    boolean    should index_page be added to the css path
 * @return    string
 */
if (!function_exists('link_tag')) {
    function link_tag($href = '', $rel = 'stylesheet', $type = 'text/css', $title = '', $media = '', $index_page = FALSE)
    {
        $CI =& get_instance();

        $link = '<link ';

        if (is_array($href)) {
            foreach ($href as $k => $v) {
                if ($k == 'href' AND strpos($v, '://') === FALSE) {
                    if ($index_page === TRUE) {
                        $link .= 'href="' . $CI->config->site_url($v) . '" ';
                    } else {
                        $link .= 'href="' . $CI->config->slash_item('base_url') . $v . '" ';
                    }
                } else {
                    $link .= "$k=\"$v\" ";
                }
            }

            $link .= "/>";
        } else {
            if (strpos($href, '://') !== FALSE) {
                $link .= 'href="' . $href . '" ';
            } elseif ($index_page === TRUE) {
                $link .= 'href="' . $CI->config->site_url($href) . '" ';
            } else {
                $link .= 'href="' . $CI->config->slash_item('base_url') . $href . '" ';
            }

            $link .= 'rel="' . $rel . '" type="' . $type . '" ';

            if ($media != '') {
                $link .= 'media="' . $media . '" ';
            }

            if ($title != '') {
                $link .= 'title="' . $title . '" ';
            }

            $link .= '/>';
        }

        return $link;
    }
}

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

/**
 * Generates meta tags from an array of key/values
 *
 * @access    public
 * @param    array
 * @return    string
 */
if (!function_exists('meta')) {
    function meta($name = '', $content = '', $type = 'name', $newline = "\n")
    {
        // Since we allow the data to be passes as a string, a simple array
        // or a multidimensional one, we need to do a little prepping.
        if (!is_array($name)) {
            $name = array(array('name' => $name, 'content' => $content, 'type' => $type, 'newline' => $newline));
        } else {
            // Turn single array into multidimensional
            if (isset($name['name'])) {
                $name = array($name);
            }
        }

        $str = '';
        foreach ($name as $meta) {
            $type = (!isset($meta['type']) OR $meta['type'] == 'name') ? 'name' : 'http-equiv';
            $name = (!isset($meta['name'])) ? '' : $meta['name'];
            $content = (!isset($meta['content'])) ? '' : $meta['content'];
            $newline = (!isset($meta['newline'])) ? "\n" : $meta['newline'];

            $str .= '<meta ' . $type . '="' . $name . '" content="' . $content . '" />' . $newline;
        }

        return $str;
    }
}

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

/**
 * Generates non-breaking space entities based on number supplied
 *
 * @access    public
 * @param    integer
 * @return    string
 */
if (!function_exists('nbs')) {
    function nbs($num = 1)
    {
        return str_repeat(" ", $num);
    }
}

/* End of file html_helper.php */
/* Location: ./system/helpers/html_helper.php */