text:
package org.nd4j.linalg;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.factory.Nd4jBackend;
import org.nd4j.linalg.util.ArrayUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.*;

/**
 * @author raver119@gmail.com
 */
@RunWith(Parameterized.class)
public class ShufflesTests extends BaseNd4jTest {

    public ShufflesTests(Nd4jBackend backend) {
        super(backend);
    }

    @Test
    public void testSimpleShuffle1() {
        INDArray array = Nd4j.zeros(10, 10);
        for (int x = 0; x < 10; x++) {
            array.getRow(x).assign(x);
        }

        System.out.println(array);

        OrderScanner2D scanner = new OrderScanner2D(array);

        assertArrayEquals(new float[] {0f, 1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f}, scanner.getMap(), 0.01f);

        System.out.println();

        Nd4j.shuffle(array, 1);

        System.out.println(array);

        ArrayUtil.argMin(new int[] {});

        assertTrue(scanner.compareRow(array));
    }

    @Test
    public void testSimpleShuffle2() {
        INDArray array = Nd4j.zeros(10, 10);
        for (int x = 0; x < 10; x++) {
            array.getColumn(x).assign(x);
        }

        System.out.println(array);

        OrderScanner2D scanner = new OrderScanner2D(array);

        assertArrayEquals(new float[] {0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f}, scanner.getMap(), 0.01f);

        System.out.println();

        Nd4j.shuffle(array, 0);

        System.out.println(array);

        assertTrue(scanner.compareColumn(array));
    }

    @Test
    public void testSimpleShuffle3() {
        INDArray array = Nd4j.zeros(11, 10);
        for (int x = 0; x < 11; x++) {
            array.getRow(x).assign(x);
        }

        System.out.println(array);

        OrderScanner2D scanner = new OrderScanner2D(array);

        assertArrayEquals(new float[] {0f, 1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 10f}, scanner.getMap(), 0.01f);

        System.out.println();

        Nd4j.shuffle(array, 1);

        System.out.println(array);

        ArrayUtil.argMin(new int[] {});

        assertTrue(scanner.compareRow(array));
    }

    @Test
    public void testSymmetricShuffle1() {
        INDArray features = Nd4j.zeros(10, 10);
        INDArray labels = Nd4j.zeros(10, 3);
        for (int x = 0; x < 10; x++) {
            features.getRow(x).assign(x);
            labels.getRow(x).assign(x);
        }

        System.out.println(features);

        OrderScanner2D scanner = new OrderScanner2D(features);

        assertArrayEquals(new float[] {0f, 1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f}, scanner.getMap(), 0.01f);

        System.out.println();

        List<INDArray> list = new ArrayList<>();
        list.add(features);
        list.add(labels);

        Nd4j.shuffle(list, 1);

        System.out.println(features);

        System.out.println();

        System.out.println(labels);

        ArrayUtil.argMin(new int[] {});

        assertTrue(scanner.compareRow(features));

        for (int x = 0; x < 10; x++) {
            double val = features.getRow(x).getDouble(0);
            INDArray row = labels.getRow(x);

            for (int y = 0; y < row.length(); y++) {
                assertEquals(val, row.getDouble(y), 0.001);
            }
        }
    }

    @Test
    public void testSymmetricShuffle2() throws Exception {
        INDArray features = Nd4j.zeros(10, 10, 20);
        INDArray labels = Nd4j.zeros(10, 10, 3);

        for (int x = 0; x < 10; x++) {
            features.slice(x).assign(x);
            labels.slice(x).assign(x);
        }

        System.out.println(features);

        OrderScanner3D scannerFeatures = new OrderScanner3D(features);
        OrderScanner3D scannerLabels = new OrderScanner3D(labels);

        System.out.println();

        List<INDArray> list = new ArrayList<>();
        list.add(features);
        list.add(labels);

        Nd4j.shuffle(list, 1, 2);

        System.out.println(features);

        System.out.println("------------------");

        System.out.println(labels);

        assertTrue(scannerFeatures.compareSlice(features));
        assertTrue(scannerLabels.compareSlice(labels));

        for (int x = 0; x < 10; x++) {
            double val = features.slice(x).getDouble(0);
            INDArray row = labels.slice(x);

            for (int y = 0; y < row.length(); y++) {
                assertEquals(val, row.getDouble(y), 0.001);
            }
        }
    }

    @Test
    public void testSymmetricShuffle3() throws Exception {
        INDArray features = Nd4j.zeros(10, 10, 20);
        INDArray featuresMask = Nd4j.zeros(10, 20);
        INDArray labels = Nd4j.zeros(10, 10, 3);
        INDArray labelsMask = Nd4j.zeros(10, 3);

        for (int x = 0; x < 10; x++) {
            features.slice(x).assign(x);
            featuresMask.slice(x).assign(x);
            labels.slice(x).assign(x);
            labelsMask.slice(x).assign(x);
        }

        OrderScanner3D scannerFeatures = new OrderScanner3D(features);
        OrderScanner3D scannerLabels = new OrderScanner3D(labels);
        OrderScanner3D scannerFeaturesMask = new OrderScanner3D(featuresMask);
        OrderScanner3D scannerLabelsMask = new OrderScanner3D(labelsMask);

        List<INDArray> arrays = new ArrayList<>();
        arrays.add(features);
        arrays.add(labels);
        arrays.add(featuresMask);
        arrays.add(labelsMask);

        List<int[]> dimensions = new ArrayList<>();
        dimensions.add(ArrayUtil.range(1, features.rank()));
        dimensions.add(ArrayUtil.range(1, labels.rank()));
        dimensions.add(ArrayUtil.range(1, featuresMask.rank()));
        dimensions.add(ArrayUtil.range(1, labelsMask.rank()));

        Nd4j.shuffle(arrays, new Random(11), dimensions);

        assertTrue(scannerFeatures.compareSlice(features));
        assertTrue(scannerLabels.compareSlice(labels));
        assertTrue(scannerFeaturesMask.compareSlice(featuresMask));
        assertTrue(scannerLabelsMask.compareSlice(labelsMask));

        for (int x = 0; x < 10; x++) {
            double val = features.slice(x).getDouble(0);
            INDArray sliceLabels = labels.slice(x);
            INDArray sliceLabelsMask = labelsMask.slice(x);
            INDArray sliceFeaturesMask = featuresMask.slice(x);

            for (int y = 0; y < sliceLabels.length(); y++) {
                assertEquals(val, sliceLabels.getDouble(y), 0.001);
            }

            for (int y = 0; y < sliceLabelsMask.length(); y++) {
                assertEquals(val, sliceLabelsMask.getDouble(y), 0.001);
            }

            for (int y = 0; y < sliceFeaturesMask.length(); y++) {
                assertEquals(val, sliceFeaturesMask.getDouble(y), 0.001);
            }
        }
    }

    /**
     * There's SMALL chance this test will randomly fail, since spread isn't too big
     * @throws Exception
     */
    @Test
    public void testHalfVectors1() throws Exception {
        int[] array1 = ArrayUtil.buildHalfVector(new Random(12), 20);
        int[] array2 = ArrayUtil.buildHalfVector(new Random(75), 20);

        assertFalse(Arrays.equals(array1, array2));

        assertEquals(20, array1.length);
        assertEquals(20, array2.length);

        for (int i = 0; i < array1.length; i++) {
            if (i >= array1.length / 2) {
                assertEquals("Failed on element [" + i + "]", -1, array1[i]);
                assertEquals("Failed on element [" + i + "]", -1, array2[i]);
            } else {
                assertNotEquals("Failed on element [" + i + "]", -1, array1[i]);
                assertNotEquals("Failed on element [" + i + "]", -1, array2[i]);
            }
        }
    }

    @Test
    public void testInterleavedVector1() throws Exception {
        int[] array1 = ArrayUtil.buildInterleavedVector(new Random(12), 20);
        int[] array2 = ArrayUtil.buildInterleavedVector(new Random(75), 20);

        assertFalse(Arrays.equals(array1, array2));

        assertEquals(20, array1.length);
        assertEquals(20, array2.length);

        for (int i = 0; i < array1.length; i++) {
            if (i % 2 != 0) {
                assertEquals("Failed on element [" + i + "]", -1, array1[i]);
                assertEquals("Failed on element [" + i + "]", -1, array2[i]);
            } else {
                assertNotEquals("Failed on element [" + i + "]", -1, array1[i]);
                assertNotEquals("Failed on element [" + i + "]", -1, array2[i]);
            }
        }
    }

    public static class OrderScanner3D {
        private float[] map;

        public OrderScanner3D(INDArray data) {
            map = measureState(data);
        }

        public float[] measureState(INDArray data) {
            // for 3D we save 0 element for each slice.
            // FIXME: int cast
            float[] result = new float[(int) data.shape()[0]];

            for (int x = 0; x < data.shape()[0]; x++) {
                result[x] = data.slice(x).getFloat(0);
            }

            return result;
        }

        public boolean compareSlice(INDArray data) {
            float[] newMap = measureState(data);

            if (newMap.length != map.length) {
                System.out.println("Different map lengths");
                return false;
            }

            if (Arrays.equals(map, newMap)) {
                System.out.println("Maps are equal");
                return false;
            }

            for (int x = 0; x < data.shape()[0]; x++) {
                INDArray slice = data.slice(x);

                for (int y = 0; y < slice.length(); y++) {
                    if (Math.abs(slice.getFloat(y) - newMap[x]) > Nd4j.EPS_THRESHOLD) {
                        System.out.print("Different data in a row");
                        return false;
                    }
                }
            }

            return true;
        }
    }

    public static class OrderScanner2D {
        private float[] map;

        public OrderScanner2D(INDArray data) {
            map = measureState(data);
        }

        public float[] measureState(INDArray data) {
            // FIXME: int cast
            float[] result = new float[(int) data.rows()];

            for (int x = 0; x < data.rows(); x++) {
                result[x] = data.getRow(x).getFloat(0);
            }

            return result;
        }

        public boolean compareRow(INDArray newData) {
            float[] newMap = measureState(newData);

            if (newMap.length != map.length) {
                System.out.println("Different map lengths");
                return false;
            }

            if (Arrays.equals(map, newMap)) {
                System.out.println("Maps are equal");
                return false;
            }

            for (int x = 0; x < newData.rows(); x++) {
                INDArray row = newData.getRow(x);
                for (int y = 0; y < row.lengthLong(); y++) {
                    if (Math.abs(row.getFloat(y) - newMap[x]) > Nd4j.EPS_THRESHOLD) {
                        System.out.print("Different data in a row");
                        return false;
                    }
                }
            }

            return true;
        }

        public boolean compareColumn(INDArray newData) {
            float[] newMap = measureState(newData);

            if (newMap.length != map.length) {
                System.out.println("Different map lengths");
                return false;
            }

            if (Arrays.equals(map, newMap)) {
                System.out.println("Maps are equal");
                return false;
            }

            for (int x = 0; x < newData.rows(); x++) {
                INDArray column = newData.getColumn(x);
                double val = column.getDouble(0);
                for (int y = 0; y < column.lengthLong(); y++) {
                    if (Math.abs(column.getFloat(y) - val) > Nd4j.EPS_THRESHOLD) {
                        System.out.print("Different data in a column: " + column.getFloat(y));
                        return false;
                    }
                }
            }

            return true;
        }

        public float[] getMap() {
            return map;
        }
    }

    @Override
    public char ordering() {
        return 'c';
    }
}


text:
package state;

public class QueueEmpty extends QueueState {
    public boolean insert(Object o) {
        return true;
    }
    public Object getFirst() {
        return null;
    }
    public boolean removeFirst() {
        return false;
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""Library that defines a panoramic transformer which rotates the world.

The panoramic transformer performs a yaw rotation about the camera's z-axis
by translating an equirectangular representation. We assume a camera convention
of z-axis up.

Below is a top-down view of the camera coordinate system. The +z-axis points
into this viewpoint. A positive yaw rotation corresponds to a CCW rotation about
the z-axis when looking down.

    y
    ^
    |
    |
    +-----> x

One thing to note is that a CCW rotation of the camera is equivalent to a
CW rotation of the scene. Therefore rotating the scene by an offset phi
is equivalent to rotating the camera by -phi.

Usage:
  pano_image = ... # a pano or a representation derived from a pano
  phi = ...        # a differentiable estimate of a yaw rotation that is
                   # predicted from pano_image. Units in radians.

  # Rotating the scene by phi is equivalent to rotating the camera by -phi.
  rotation_normalized_pano_image = shift_pano_by_rotation(pano_image, -phi)
  rotation_normalized_output = network(rotation_normalized_pano_image)

  # Optional inverse rotate to get restore pano_image's original orientation.
  output = shift_pano_by_rotation(rotation_normalized_output, alpha_phi)
"""

import numpy as np
import tensorflow.compat.v1 as tf
from tensorflow.contrib import resampler

def rotate_pano_horizontally(input_feature_map, yaw_angle):
  """Rotates input_feature_map by yaw_angle by horizontally translating pixels.

  The layer is differentiable with respect to yaw_angle and  input_feature_map.
  yaw_angle is positive for CCW rotation about the z-axis where the coordinates
  are constructed with z-axis facing up.

  Args:
    input_feature_map: panoramic image or neural feature maps of shape [B, H, W,
      C].
    yaw_angle: A tensor of shape `[B]` which represents the desired rotation of
      input_feature_map. yaw_angle is in units of radians. A positive yaw_angle
      rolls pixels left.

  Returns:
    A rotated feature map with dimensions `[B, H, W, C]`

  Reference:
  [1]: 'Spatial Transformer Networks', Jaderberg et. al,
       (https://arxiv.org/abs/1506.02025)
  """

  # Number of input dimensions.
  tfshape = tf.shape(input_feature_map)
  batch_size = tfshape[0]
  height = tfshape[1]
  width = tfshape[2]

  float32_width = tf.cast(width, dtype=tf.float32)
  float32_height = tf.cast(height, dtype=tf.float32)

  x_offset = (yaw_angle / 2 / np.pi) * float32_width

  x_grid = tf.linspace(0., float32_width - 1, width)  # (W)
  # 0.5 * original_image_width to match the convention described in comment
  x_pixel_coord = x_grid[tf.newaxis] + x_offset[:, tf.newaxis]  # (B, W)

  x_pixel_coord = tf.tile(x_pixel_coord[:, tf.newaxis, :],
                          [1, height, 1])  # (B, H, W)
  y_pixel_coord = tf.linspace(0., float32_height - 1,
                              height)[tf.newaxis, :, tf.newaxis]  # (1, H, 1)
  y_pixel_coord = tf.tile(y_pixel_coord, [batch_size, 1, width])
  wrapped_x_pixel_coord = tf.floormod(x_pixel_coord, float32_width)

  # Because these are panoramas, we can concatenate the first column to the
  # right side. This allows us to interpolate values for coordinates that
  # correspond to pixels that connects the left and right edges of the
  # panorama.
  input_feature_map = tf.concat(
      [input_feature_map, input_feature_map[:, :, :1]], axis=2)

  return resampler.resampler(
      input_feature_map,
      tf.stack([wrapped_x_pixel_coord, y_pixel_coord], axis=-1))


text:
set -e

K8S_CLUSTER=mycluster vector validate --no-environment ./files/vector-config.yaml ./files/vector-transforms.yaml


text:
using System;

using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace Fluid.Controls
{
    /// <summary>
    /// Implements the IColorGroupHeader interface:
    /// A Group Header that can specify a color for it's background.
    /// If set to Color.Empty, the default header color is used.
    /// </summary>
    public class ColorGroupHeader : GroupHeader, IColorGroupHeader
    {
        public ColorGroupHeader(string title, Color color)
            : base(title)
        {
            this.BackColor = color;
        }

        public ColorGroupHeader()
            : base()
        {
        }

        #region IColorGroupHeader Members

        private Color backColor = Color.Empty;

        public System.Drawing.Color BackColor
        {
            get
            {
                return backColor;
            }
            set
            {
                backColor = value;
            }
        }

        #endregion
    }
}


text:
namespace RemindMe
{
    partial class MaterialRemindMeBox
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MaterialRemindMeBox));
            this.pnlFooterButtons = new System.Windows.Forms.Panel();
            this.materialProgressBar1 = new MaterialSkin.Controls.MaterialProgressBar();
            this.btnOk = new MaterialSkin.Controls.MaterialButton();
            this.pnlRemind = new System.Windows.Forms.Panel();
            this.cbDontRemind = new MaterialSkin.Controls.MaterialCheckbox();
            this.btnYes = new MaterialSkin.Controls.MaterialButton();
            this.btnNo = new MaterialSkin.Controls.MaterialButton();
            this.tmrFadeIn = new System.Windows.Forms.Timer(this.components);
            this.pnlMainGradient = new System.Windows.Forms.Panel();
            this.lblText = new System.Windows.Forms.LinkLabel();
            this.pbIcon = new System.Windows.Forms.PictureBox();
            this.pnlFooterButtons.SuspendLayout();
            this.pnlRemind.SuspendLayout();
            this.pnlMainGradient.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pbIcon)).BeginInit();
            this.SuspendLayout();
            //
            // pnlFooterButtons
            //
            this.pnlFooterButtons.Controls.Add(this.materialProgressBar1);
            this.pnlFooterButtons.Controls.Add(this.btnOk);
            this.pnlFooterButtons.Controls.Add(this.pnlRemind);
            this.pnlFooterButtons.Controls.Add(this.btnYes);
            this.pnlFooterButtons.Controls.Add(this.btnNo);
            this.pnlFooterButtons.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.pnlFooterButtons.Location = new System.Drawing.Point(0, 188);
            this.pnlFooterButtons.Name = "pnlFooterButtons";
            this.pnlFooterButtons.Size = new System.Drawing.Size(374, 70);
            this.pnlFooterButtons.TabIndex = 0;
            //
            // materialProgressBar1
            //
            this.materialProgressBar1.Depth = 0;
            this.materialProgressBar1.Dock = System.Windows.Forms.DockStyle.Top;
            this.materialProgressBar1.Location = new System.Drawing.Point(0, 0);
            this.materialProgressBar1.MouseState = MaterialSkin.MouseState.HOVER;
            this.materialProgressBar1.Name = "materialProgressBar1";
            this.materialProgressBar1.Size = new System.Drawing.Size(374, 5);
            this.materialProgressBar1.TabIndex = 10;
            this.materialProgressBar1.Value = 100;
            //
            // btnOk
            //
            this.btnOk.AutoSize = false;
            this.btnOk.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.btnOk.Depth = 0;
            this.btnOk.DrawShadows = true;
            this.btnOk.HighEmphasis = true;
            this.btnOk.Icon = null;
            this.btnOk.Location = new System.Drawing.Point(272, 21);
            this.btnOk.Margin = new System.Windows.Forms.Padding(4, 6, 4, 6);
            this.btnOk.MouseState = MaterialSkin.MouseState.HOVER;
            this.btnOk.Name = "btnOk";
            this.btnOk.Size = new System.Drawing.Size(79, 30);
            this.btnOk.TabIndex = 9;
            this.btnOk.Text = "OK";
            this.btnOk.Type = MaterialSkin.Controls.MaterialButton.MaterialButtonType.Contained;
            this.btnOk.UseAccentColor = false;
            this.btnOk.UseVisualStyleBackColor = true;
            this.btnOk.Visible = false;
            this.btnOk.Click += new System.EventHandler(this.btnOk_Click);
            //
            // pnlRemind
            //
            this.pnlRemind.Controls.Add(this.cbDontRemind);
            this.pnlRemind.Location = new System.Drawing.Point(4, 16);
            this.pnlRemind.Name = "pnlRemind";
            this.pnlRemind.Size = new System.Drawing.Size(175, 36);
            this.pnlRemind.TabIndex = 8;
            this.pnlRemind.Visible = false;
            //
            // cbDontRemind
            //
            this.cbDontRemind.AutoSize = true;
            this.cbDontRemind.Depth = 0;
            this.cbDontRemind.Font = new System.Drawing.Font("Microsoft Sans Serif", 6F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.cbDontRemind.Location = new System.Drawing.Point(0, 0);
            this.cbDontRemind.Margin = new System.Windows.Forms.Padding(0);
            this.cbDontRemind.MouseLocation = new System.Drawing.Point(-1, -1);
            this.cbDontRemind.MouseState = MaterialSkin.MouseState.HOVER;
            this.cbDontRemind.Name = "cbDontRemind";
            this.cbDontRemind.Ripple = true;
            this.cbDontRemind.Size = new System.Drawing.Size(169, 37);
            this.cbDontRemind.TabIndex = 0;
            this.cbDontRemind.Text = "Don\'t remind again";
            this.cbDontRemind.UseVisualStyleBackColor = true;
            //
            // btnYes
            //
            this.btnYes.AutoSize = false;
            this.btnYes.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.btnYes.Depth = 0;
            this.btnYes.DrawShadows = true;
            this.btnYes.HighEmphasis = true;
            this.btnYes.Icon = null;
            this.btnYes.Location = new System.Drawing.Point(272, 21);
            this.btnYes.Margin = new System.Windows.Forms.Padding(4, 6, 4, 6);
            this.btnYes.MouseState = MaterialSkin.MouseState.HOVER;
            this.btnYes.Name = "btnYes";
            this.btnYes.Size = new System.Drawing.Size(79, 30);
            this.btnYes.TabIndex = 2;
            this.btnYes.Text = "Yes";
            this.btnYes.Type = MaterialSkin.Controls.MaterialButton.MaterialButtonType.Contained;
            this.btnYes.UseAccentColor = false;
            this.btnYes.UseVisualStyleBackColor = true;
            this.btnYes.Visible = false;
            this.btnYes.Click += new System.EventHandler(this.btnYes_Click);
            //
            // btnNo
            //
            this.btnNo.AutoSize = false;
            this.btnNo.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.btnNo.Depth = 0;
            this.btnNo.DrawShadows = true;
            this.btnNo.HighEmphasis = true;
            this.btnNo.Icon = null;
            this.btnNo.Location = new System.Drawing.Point(185, 21);
            this.btnNo.Margin = new System.Windows.Forms.Padding(4, 6, 4, 6);
            this.btnNo.MouseState = MaterialSkin.MouseState.HOVER;
            this.btnNo.Name = "btnNo";
            this.btnNo.Size = new System.Drawing.Size(79, 30);
            this.btnNo.TabIndex = 1;
            this.btnNo.Text = "No";
            this.btnNo.Type = MaterialSkin.Controls.MaterialButton.MaterialButtonType.Contained;
            this.btnNo.UseAccentColor = false;
            this.btnNo.UseVisualStyleBackColor = true;
            this.btnNo.Visible = false;
            this.btnNo.Click += new System.EventHandler(this.btnNo_Click);
            //
            // tmrFadeIn
            //
            this.tmrFadeIn.Interval = 10;
            this.tmrFadeIn.Tick += new System.EventHandler(this.tmrFadeIn_Tick_1);
            //
            // pnlMainGradient
            //
            this.pnlMainGradient.Controls.Add(this.lblText);
            this.pnlMainGradient.Controls.Add(this.pbIcon);
            this.pnlMainGradient.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.pnlMainGradient.Location = new System.Drawing.Point(0, 43);
            this.pnlMainGradient.Name = "pnlMainGradient";
            this.pnlMainGradient.Size = new System.Drawing.Size(374, 145);
            this.pnlMainGradient.TabIndex = 1;
            //
            // lblText
            //
            this.lblText.AutoSize = true;
            this.lblText.LinkArea = new System.Windows.Forms.LinkArea(0, 0);
            this.lblText.Location = new System.Drawing.Point(103, 24);
            this.lblText.Name = "lblText";
            this.lblText.Size = new System.Drawing.Size(28, 13);
            this.lblText.TabIndex = 7;
            this.lblText.Text = "Text";
            //
            // pbIcon
            //
            this.pbIcon.BackColor = System.Drawing.Color.Transparent;
            this.pbIcon.BackgroundImage = global::RemindMe.Properties.Resources.RemindMe;
            this.pbIcon.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            this.pbIcon.Location = new System.Drawing.Point(12, 14);
            this.pbIcon.Name = "pbIcon";
            this.pbIcon.Size = new System.Drawing.Size(62, 58);
            this.pbIcon.TabIndex = 6;
            this.pbIcon.TabStop = false;
            //
            // MaterialRemindMeBox
            //
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
            this.ClientSize = new System.Drawing.Size(374, 258);
            this.ControlBox = false;
            this.Controls.Add(this.pnlMainGradient);
            this.Controls.Add(this.pnlFooterButtons);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "MaterialRemindMeBox";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.StatusBarHeight = 0;
            this.Text = "Attention!";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MaterialRemindMeBox_FormClosing);
            this.Load += new System.EventHandler(this.MaterialRemindMeBox_Load);
            this.pnlFooterButtons.ResumeLayout(false);
            this.pnlRemind.ResumeLayout(false);
            this.pnlRemind.PerformLayout();
            this.pnlMainGradient.ResumeLayout(false);
            this.pnlMainGradient.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pbIcon)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Panel pnlFooterButtons;
        private MaterialSkin.Controls.MaterialCheckbox cbDontRemind;
        private MaterialSkin.Controls.MaterialButton btnNo;
        private MaterialSkin.Controls.MaterialButton btnYes;
        private System.Windows.Forms.Panel pnlRemind;
        private MaterialSkin.Controls.MaterialButton btnOk;
        private System.Windows.Forms.Timer tmrFadeIn;
        private System.Windows.Forms.Panel pnlMainGradient;
        private System.Windows.Forms.PictureBox pbIcon;
        private MaterialSkin.Controls.MaterialProgressBar materialProgressBar1;
        private System.Windows.Forms.LinkLabel lblText;
    }
}


text:
require 'active_record'

class CreateFemaleRespondentsTable < ActiveRecord::Migration
  def self.up
    create_table :female_respondents do |t|
      t.column 'caseid', :int
    end
  end

  def self.down
    drop_table :female_respondents
  end
end


text:
The `md-table` provides a Material Design styled data-table that can be used to display rows of
data.

This table builds on the foundation of the CDK data-table and uses a similar interface for its
data source input and template, except that its element and attribute selectors will be prefixed
with `md-` instead of `cdk-`.

For more information on the interface and how it works, see the
[guide covering the CDK data-table](https://material.angular.io/guide/cdk-table).

<!-- example(table-basic) -->

### Features

The `<md-table>` itself only deals with the rendering of a table structure (rows and cells).
Additional features can be built on top of the table by adding behavior inside cell templates
(e.g., sort headers) or next to the table (e.g. a paginator). Interactions that affect the
rendered data (such as sorting and pagination) should be propagated through the table's data source.

#### Pagination

The `<md-paginator>` adds a pagination UI that can be used in conjunction with the `<md-table>`. The
paginator emits events that can be used to trigger an update via the table's data source.

<!-- example(table-pagination) -->

#### Sorting

Use the `mdSort` directive and `<md-sort-header>` adds a sorting UI the table's column headers. The
sort headers emit events that can be used to trigger an update via the table's data source.

<!-- example(table-sorting) -->

#### Filtering

While Angular Material does not offer a specific component for filtering tabular data, the table's
data source can be updated based on any custom filter UI. Any filtering pattern need only trigger
an update via the table's data source.

<!--- example(table-filtering) -->

### Simple Table

In the near future, we will provide a simplified version of the data-table with an easy-to-use
interface, material styling, array input, and more out-of-the-box features (sorting, pagination,
and selection).

### Accessibility
Tables without text or labels should be given a meaningful label via `aria-label` or
`aria-labelledby`. The `aria-readonly` defaults to `true` if it's not set.

Table's default role is `grid`, and it can be changed to `treegrid` through `role` attribute.

`md-table` does not manage any focus/keyboard interaction on its own. Users can add desired
focus/keyboard interactions in their application.


text:
static const char name[] = "Test Name";

typedef bluetoe::extend_server<
    small_temperature_service,
    bluetoe::server_name< name >
> named_temperature_service;

BOOST_AUTO_TEST_CASE( named_server )
{
    std::uint8_t buffer[ 100 ];
    named_temperature_service service;

    static const std::uint8_t expected_advertising[] = {
        0x02, 0x01, 0x06,
        0x0A, 0x09, 'T', 'e', 's', 't', ' ', 'N', 'a', 'm', 'e'
    };

    const std::size_t size = service.advertising_data( buffer, sizeof( buffer ) );

    BOOST_CHECK_EQUAL_COLLECTIONS( std::begin( buffer ), std::begin( buffer ) + size, std::begin( expected_advertising ), std::end( expected_advertising ) );
}

BOOST_AUTO_TEST_CASE( short_named_server )
{
    std::uint8_t buffer[ 10 ];
    named_temperature_service service;

    static const std::uint8_t expected_advertising[] = {
        0x02, 0x01, 0x06,
        0x06, 0x08, 'T', 'e', 's', 't', ' '
    };

    const std::size_t size = service.advertising_data( buffer, sizeof( buffer ) );

    BOOST_CHECK_EQUAL_COLLECTIONS( std::begin( buffer ), std::begin( buffer ) + size, std::begin( expected_advertising ), std::end( expected_advertising ) );
}

BOOST_AUTO_TEST_CASE( unnamed_server )
{
    std::uint8_t buffer[ 31 ];
    small_temperature_service service;

    static const std::uint8_t expected_advertising[] = {
        0x02, 0x01, 0x06
    };

    const std::size_t size = service.advertising_data( buffer, sizeof( buffer ) );

    BOOST_CHECK_EQUAL_COLLECTIONS( std::begin( buffer ), std::begin( buffer ) + size, std::begin( expected_advertising ), std::end( expected_advertising ) );
}


text:
package tls

import (
	"math/rand"
	"reflect"
	"testing"
	"testing/quick"
)

var tests = []interface{}{
	&ClientHelloMsg{},
	&serverHelloMsg{},
	&finishedMsg{},

	&certificateMsg{},
	&certificateRequestMsg{},
	&certificateVerifyMsg{},
	&certificateStatusMsg{},
	&clientKeyExchangeMsg{},
	&nextProtoMsg{},
	&newSessionTicketMsg{},
	&sessionState{},
}

type testMessage interface {
	marshal() []byte
	unmarshal([]byte) bool
	equal(interface{}) bool
}

func TestMarshalUnmarshal(t *testing.T) {
	rand := rand.New(rand.NewSource(0))

	for i, iface := range tests {
		ty := reflect.ValueOf(iface).Type()

		n := 100
		if testing.Short() {
			n = 5
		}
		for j := 0; j < n; j++ {
			v, ok := quick.Value(ty, rand)
			if !ok {
				t.Errorf("#%d: failed to create value", i)
				break
			}

			m1 := v.Interface().(testMessage)
			marshaled := m1.marshal()
			m2 := iface.(testMessage)
			if !m2.unmarshal(marshaled) {
				t.Errorf("#%d failed to unmarshal %#v %x", i, m1, marshaled)
				break
			}
			m2.marshal() // to fill any marshal cache in the message

			if !m1.equal(m2) {
				t.Errorf("#%d got:%#v want:%#v %x", i, m2, m1, marshaled)
				break
			}

			if i >= 3 {
				// The first three message types (ClientHello,
				// ServerHello and Finished) are allowed to
				// have parsable prefixes because the extension
				// data is optional and the length of the
				// Finished varies across versions.
				for j := 0; j < len(marshaled); j++ {
					if m2.unmarshal(marshaled[0:j]) {
						t.Errorf("#%d unmarshaled a prefix of length %d of %#v", i, j, m1)
						break
					}
				}
			}
		}
	}
}

func TestFuzz(t *testing.T) {
	rand := rand.New(rand.NewSource(0))
	for _, iface := range tests {
		m := iface.(testMessage)

		for j := 0; j < 1000; j++ {
			len := rand.Intn(100)
			bytes := randomBytes(len, rand)
			// This just looks for crashes due to bounds errors etc.
			m.unmarshal(bytes)
		}
	}
}

func randomBytes(n int, rand *rand.Rand) []byte {
	r := make([]byte, n)
	for i := 0; i < n; i++ {
		r[i] = byte(rand.Int31())
	}
	return r
}

func randomString(n int, rand *rand.Rand) string {
	b := randomBytes(n, rand)
	return string(b)
}

func (*ClientHelloMsg) Generate(rand *rand.Rand, size int) reflect.Value {
	m := &ClientHelloMsg{}
	m.vers = uint16(rand.Intn(65536))
	m.random = randomBytes(32, rand)
	m.sessionId = randomBytes(rand.Intn(32), rand)
	m.CipherSuites = make([]uint16, rand.Intn(63)+1)
	for i := 0; i < len(m.CipherSuites); i++ {
		m.CipherSuites[i] = uint16(rand.Int31())
	}
	m.CompressionMethods = randomBytes(rand.Intn(63)+1, rand)
	if rand.Intn(10) > 5 {
		m.nextProtoNeg = true
	}
	if rand.Intn(10) > 5 {
		m.serverName = randomString(rand.Intn(255), rand)
	}
	m.ocspStapling = rand.Intn(10) > 5
	m.supportedPoints = randomBytes(rand.Intn(5)+1, rand)
	m.supportedCurves = make([]uint16, rand.Intn(5)+1)
	for i := range m.supportedCurves {
		m.supportedCurves[i] = uint16(rand.Intn(30000))
	}
	if rand.Intn(10) > 5 {
		m.TicketSupported = true
		if rand.Intn(10) > 5 {
			m.sessionTicket = randomBytes(rand.Intn(300), rand)
		}
	}
	if rand.Intn(10) > 5 {
		m.signatureAndHashes = supportedSKXSignatureAlgorithms
	}

	return reflect.ValueOf(m)
}

func (*serverHelloMsg) Generate(rand *rand.Rand, size int) reflect.Value {
	m := &serverHelloMsg{}
	m.vers = uint16(rand.Intn(65536))
	m.random = randomBytes(32, rand)
	m.sessionId = randomBytes(rand.Intn(32), rand)
	m.cipherSuite = uint16(rand.Int31())
	m.compressionMethod = uint8(rand.Intn(256))

	if rand.Intn(10) > 5 {
		m.nextProtoNeg = true

		n := rand.Intn(10)
		m.nextProtos = make([]string, n)
		for i := 0; i < n; i++ {
			m.nextProtos[i] = randomString(20, rand)
		}
	}

	if rand.Intn(10) > 5 {
		m.ocspStapling = true
	}
	if rand.Intn(10) > 5 {
		m.TicketSupported = true
	}

	return reflect.ValueOf(m)
}

func (*certificateMsg) Generate(rand *rand.Rand, size int) reflect.Value {
	m := &certificateMsg{}
	numCerts := rand.Intn(20)
	m.certificates = make([][]byte, numCerts)
	for i := 0; i < numCerts; i++ {
		m.certificates[i] = randomBytes(rand.Intn(10)+1, rand)
	}
	return reflect.ValueOf(m)
}

func (*certificateRequestMsg) Generate(rand *rand.Rand, size int) reflect.Value {
	m := &certificateRequestMsg{}
	m.certificateTypes = randomBytes(rand.Intn(5)+1, rand)
	numCAs := rand.Intn(100)
	m.certificateAuthorities = make([][]byte, numCAs)
	for i := 0; i < numCAs; i++ {
		m.certificateAuthorities[i] = randomBytes(rand.Intn(15)+1, rand)
	}
	return reflect.ValueOf(m)
}

func (*certificateVerifyMsg) Generate(rand *rand.Rand, size int) reflect.Value {
	m := &certificateVerifyMsg{}
	m.signature = randomBytes(rand.Intn(15)+1, rand)
	return reflect.ValueOf(m)
}

func (*certificateStatusMsg) Generate(rand *rand.Rand, size int) reflect.Value {
	m := &certificateStatusMsg{}
	if rand.Intn(10) > 5 {
		m.statusType = statusTypeOCSP
		m.response = randomBytes(rand.Intn(10)+1, rand)
	} else {
		m.statusType = 42
	}
	return reflect.ValueOf(m)
}

func (*clientKeyExchangeMsg) Generate(rand *rand.Rand, size int) reflect.Value {
	m := &clientKeyExchangeMsg{}
	m.ciphertext = randomBytes(rand.Intn(1000)+1, rand)
	return reflect.ValueOf(m)
}

func (*finishedMsg) Generate(rand *rand.Rand, size int) reflect.Value {
	m := &finishedMsg{}
	m.verifyData = randomBytes(12, rand)
	return reflect.ValueOf(m)
}

func (*nextProtoMsg) Generate(rand *rand.Rand, size int) reflect.Value {
	m := &nextProtoMsg{}
	m.proto = randomString(rand.Intn(255), rand)
	return reflect.ValueOf(m)
}

func (*newSessionTicketMsg) Generate(rand *rand.Rand, size int) reflect.Value {
	m := &newSessionTicketMsg{}
	m.ticket = randomBytes(rand.Intn(4), rand)
	return reflect.ValueOf(m)
}

func (*sessionState) Generate(rand *rand.Rand, size int) reflect.Value {
	s := &sessionState{}
	s.vers = uint16(rand.Intn(10000))
	s.cipherSuite = uint16(rand.Intn(10000))
	s.masterSecret = randomBytes(rand.Intn(100), rand)
	numCerts := rand.Intn(20)
	s.certificates = make([][]byte, numCerts)
	for i := 0; i < numCerts; i++ {
		s.certificates[i] = randomBytes(rand.Intn(10)+1, rand)
	}
	return reflect.ValueOf(s)
}


text:
![logo](./tokbox-logo.png)

# OpenTok SIP Interconnect Sample App for JavaScript
Version 1.0

This document describes how to use the OpenTok SIP Interconnect Sample App for JavaScript. Through the exploration of this sample application, you will learn best practices for adding audio from a SIP call directly into your website and mobile applications.

The standard way to connect to the OpenTok platform is with the OpenTok client SDKs that use proprietary signaling interfaces provided by TokBox. However, it is sometimes useful to interconnect with other RTC platforms such as PSTN, IMS, PBX, and Call Centers. For such cases, TokBox exposes a SIP interface that enables access to existing 3rd party PSTN functionality. This interface enables users, who are connected via such 3rd party PSTN platforms, to participate in the audio portion of an OpenTok session.
_OpenTok SIP Interconnect provides support to dial out from an OpenTok session to any SIP URI._ For example, your OpenTok SIP Interconnect application would make a SIP call to a customer contact center, which routes the call to an agent. The agent accepts the phone call and participates by voice in the session in order to speak with the customer. In addition, the agent could still optionally join with video via a laptop. To make such functionality available, the OpenTok cloud infrastructure includes signaling and media gateways, as well as REST APIs, to allow you to trigger the SIP calls from OpenTok sessions as needed for your business logic.

The OpenTok SIP Interconnect Sample App allows you to start and end SIP calls, and its UI displays the participants using both WebRTC streams and SIP streams. WebRTC participants include video, while SIP participants are displayed with audio only.

You can configure and run this sample app within just a few minutes!
_**NOTE**: OpenTok SIP Interconnect supports only audio through the SIP interface, and does not currently support video. All the existing functionality of OpenTok, such as multiparty sessions and archiving, are compatible with OpenTok SIP Interconnect. OpenTok SIP Interconnect does not include any built-in PSTN functionality._

This guide has the following sections:

* [Architecture](#architecture): This section describes how the OpenTok SIP Interconnect feature
  works with gateways for third-party SIP platforms.
* [Prerequisites](#prerequisites): A checklist of everything you need to get started.
* [Quick start](#quick-start): A step-by-step tutorial to help you quickly run the sample app.
* [Exploring the code](#exploring-the-code): This describes the sample app code design, which uses recommended best practices to implement the OpenTok SIP Interconnect app features.

## Architecture

The OpenTok SIP Interconnect Gateway exposes a SIP Interface and REST APIs that trigger and customize the calls via third-party SIP platforms. The OpenTok SIP Interconnect Gateway is composed of two parts: the SIP Interface and the OpenTok Interface:

![logo](./Infographic.jpg)

This architecture enables a SIP participant to appear in an OpenTok session like any other client. All that is required to enable this behavior is to pass an OpenTok **Session ID** and **Token** when initiating the SIP call the makes use of the OpenTok Dial REST API.

OpenTok identifies a SIP Gateway in the same region of the Media Server where the session is allocated. You can use the existing OpenTok capabilities if the default Media Server allocation is not ideal for your use (making use of the location hint when creating the session).
The SIP Gateway terminates the SIP Dialogs and RTP flows. The protocols and capabilities supported in both interfaces are described in the next sections.
The SIP Gateway is comprised of a session border controller (SBC), a Signaling Gateway, and a Media Mixer. The SBC component handles security as well as the protocol and codec adaptation. The Signaling Gateway converts the SIP primitives into the corresponding OpenTok primitives. The Media Mixer mixes the audio flows from multiple participants in OpenTok session in order to forward them as a single composite audio flow.

_**NOTE**: If media inactivity lasts for more than 5 minutes, the call will be automatically closed unless session timers are used at the SIP level. As a security measure, any SIP call longer than 6 hours will be automatically closed by OpenTok._

### Security considerations

There are some best practices recommended by TokBox when using this new SIP Interface with
your SIP Servers. They try to mitigate the possible attacks by providing the mechanisms to
authenticate and authorize that the SIP calls received in your server are legitimate and to
encrypt all the signaling and media:

* Use TLS and enable secure calls (SRTP) for signaling to avoid the possibility of
  intercepting the communications.

* Enable SIP authentication on your server. Otherwise, anyone who knows your SIP URI could
  send calls to your server.

If required, you can also block the traffic not coming from the IP addresses of the OpenTok
SIP gateway, which uses the following IP blocks:

* 52.200.60.16 – 52.200.60.31
* 52.41.63.240 – 52.41.63.255
* 52.51.63.16 – 52.51.63.31

Be aware that TokBox can add new IP blocks in the future, and you
will need to change your configuration.

### Technical details

**RFC3550 (RTP/RTCP) support:** Media traffic can be encrypted (SRTP) or non-encrypted
(plain RTP). In case of encryption, both DTLS and SDES protocols are supported.

**Codec support:** The OpenTok SIP gateway supports the OPUS, G.711, and G.722 audio codecs.

**Signaling:** The OpenTok SIP gateway supports RFC3561 (SIP) over UDP, TCP, and TLS.
Contact TokBox if you need information or support for any specific extension.

The OpenTok SIP gateway will not accept any SIP message coming from a third-party SIP
platform unless it is part of a SIP dialog initiated by the OpenTok SIP gateway.
Calls initiated with the OpenTok SIP gateway can be put on hold using either a `re-INVITE`
with the `sendonly/inactive` direction in the SDP or a `re-INVITE` with port 0 in the SDP.

**Other considerations:** Early media is disabled, and DTMFs are not currently supported.

### Additional Information

For additional information see [SIP Interconnect](https://www.tokbox.com/developer/guides/sip/) at the TokBox Developer Center.

## Prerequisites

To be prepared to develop your OpenTok SIP Interconnect app:

1. Review the [OpenTok.js](https://tokbox.com/developer/sdks/js/) requirements.
2. Your app will need **Token** and **API Key**, which you can get at the [OpenTok Developer Dashboard](https://dashboard.tokbox.com/). Set the API Key and API Secret in [config.js](./config.js).

To install the OpenTok SIP Interconnect Sample App, run the following commands:

```
npm install
npm start
```

_**IMPORTANT:** In order to deploy an OpenTok SPI Interconnect app, your web domain must use HTTPS._

## Quick start

The web page that loads the sample app for JavaScript must be served over HTTP/HTTPS. Browser security limitations prevent you from publishing video using a `file://` path, as discussed in the OpenTok.js [Release Notes](https://www.tokbox.com/developer/sdks/js/release-notes.html#knownIssues). To support clients running [Chrome 47 or later](https://groups.google.com/forum/#!topic/discuss-webrtc/sq5CVmY69sc), HTTPS is required. A web server such as [MAMP](https://www.mamp.info/) or [XAMPP](https://www.apachefriends.org/index.html) will work, or you can use a cloud service such as [Heroku](https://www.heroku.com/) to host the application.

## Exploring the code

This section describes how the sample app code design uses recommended best practices to deploy the SIP Interconnect features.

For detail about the APIs used to develop this sample, see the [OpenTok.js Reference](https://tokbox.com/developer/sdks/js/reference/).

  - [Web page design](#web-page-design)
  - [SIP Call](#sip-call)

_**NOTE:** The sample app contains logic used for logging. This is used to submit anonymous usage data for internal TokBox purposes only. We request that you do not modify or remove any logging code in your use of this sample application._

### Web page design

While TokBox hosts [OpenTok.js](https://tokbox.com/developer/sdks/js/), you must host the sample app yourself. This allows you to customize the app as desired. For details about the one-to-one communication audio-video aspects of the design, see the [OpenTok One-to-One Communication Sample App](https://github.com/opentok/one-to-one-sample-apps/tree/master/one-to-one-sample-app/js) and [OpenTok Common Accelerator Session Pack](https://github.com/opentok/acc-pack-common/).

* **[index.ejs](./views/index.ejs)**: This defines the container defining the publisher and layout for the sample app, including the buttons to start and end the SIP call. This file contains the business logic that initiates the OpenTok session and handles the SIP call click events.

* **[config.js](./config.js)**: Configures the participant's **Session ID**, **Token**, and **API Key** used to create the OpenTok session in [app.js](./app.js), and specifies the SIP headers and credentials required to start the SIP call.

* **[app.js](./app.js)**: Creates the OpenTok session, serves the app, and listens for the POST request for starting the SIP call using the credentials specified in [config.js](./config.js).

### SIP Call

A SIP call is made by clicking the **Start SIP Call** button, which results in a call to the `OpenTok.dial()` method.

The `opentok.dial()` method in [app.js](./app.js) creates a REST request to OpenTok to start the SIP call. `opentok.dial()` takes the following arguments:

  - Session ID and session token
  - SIP URI
  - SIP username and password (optional)
  - A `secure` field indicating whether TLS encryption is applied (optional)
  - SIP headers to be added to the SIP INVITE request (optional)

In this sample application, a SIP token is defined by part of its metadata, which may be be useful for embedding UI metadata for the SIP audio participant. The token is generated with the metadata `{data: "sip=true"}` as the OpenTok session is created:

```javascript
opentok.createSession({ mediaMode:"routed" }, function(error, session) {
  if (error) {
    throw new Error("Error creating session:"+error);
  } else {
    sessionId = session.sessionId;

    // For web tokens, moderator role is used to force disconnect SIP calls.
    // For SIP tokens, an identifying SIP flag is embedded in the metadata.
    webrtcToken = opentok.generateToken(sessionId, {role: "moderator"});
    sipToken = opentok.generateToken(sessionId, {data: "sip=true"});
  }
});
```

This metadata can be viewed in the `event.stream.connection.data` property of [ConnectionEvents](https://www.tokbox.com/developer/sdks/js/reference/ConnectionEvent.html).

**NOTE:** Such metadata is not actually necessary to start a SIP call, though it has advantages as shown in this sample app. It is also possible to simply call `OpenTok.dial(sessionID, token, sipUri, callback)` to start the SIP call.

The `streamCreated` listener, as shown here in [index.ejs](./views/index.ejs), inspects this token metadata to determine if the new participant is joining via a SIP call:

```javascript
var session = OT.initSession(sessionId);
session.on("streamCreated", function (event) {
  var tokenData = event.stream.connection.data;
    if (tokenData && tokenData.includes("sip=true")) {
      var element = "sipPublisherContainer";
    } else {
      var element = "webrtcPublisherContainer";
     }

  . . .

});
```

Once the session has been established and the SIP token (`sipToken`) has been generated, the `OpenTok.dial()` method passes that information to the SIP call endpoint:

```javascript
  opentok.dial(sessionId, sipToken, config.sipUri, {
    auth: {
      username: config.sipUsername,
      password: config.sipPassword
    }
  }, function (err, sipCall) {
    console.error(err);
    if (err) return res.status(500).send('Platform error starting SIP Call:'+err);
    res.send(sipCall);
  });
});
```


text:
<?php
namespace ssdb;

class Exception extends \Exception
{
}


text:
	<title>Material CSS theme!</title>
	<link href='http://fonts.googleapis.com/css?family=Roboto:100' rel='stylesheet' type='text/css'>
	<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
	<link rel="stylesheet" type="text/css" href="style/light - blue.css">

	menu

	more_vert

nav1

nav2

nav3

nav4

Header!

test
description

test
description

test
description

test
description

test
description

UI Elements!

Input Fields

Check Box

Radio Button

Buttons

List view

Main Header 1!
Lorem Ipsum is simply dummy text of the printing
<content>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</content>

Buttons!

<content>
Dark Button
<input type="submit" value="Dark enabled!" class="submitdark"></input><input type="submit" value="Dark disabled!" class="submitdark" disabled></input>
Light Button
<input type="submit" value="Light enabled!" class="submitlight"></input><input type="submit" value="Light disabled!" class="submitlight" disabled></input></content>

Input Fields!

<content>
Single line text
<input type="text" value="single line!" class="text"></input>
Multi line text
<textarea cols='' rows='' value="multi line!" class="text"></textarea></content>


text:
from ctypes import windll, Structure, byref, c_uint
from ctypes.wintypes import HWND, UINT, LPCWSTR, BOOL
import os.path as op

shell32 = windll.shell32
SHFileOperationW = shell32.SHFileOperationW

class SHFILEOPSTRUCTW(Structure):
    _fields_ = [
        ("hwnd", HWND),
        ("wFunc", UINT),
        ("pFrom", LPCWSTR),
        ("pTo", LPCWSTR),
        ("fFlags", c_uint),
        ("fAnyOperationsAborted", BOOL),
        ("hNameMappings", c_uint),
        ("lpszProgressTitle", LPCWSTR),
        ]

FO_MOVE = 1
FO_COPY = 2
FO_DELETE = 3
FO_RENAME = 4

FOF_MULTIDESTFILES = 1
FOF_SILENT = 4
FOF_NOCONFIRMATION = 16
FOF_ALLOWUNDO = 64
FOF_NOERRORUI = 1024

def send2trash(path):
    # if not isinstance(path, str):
    #     path = str(path, 'mbcs')
    if not op.isabs(path):
        path = op.abspath(path)
    fileop = SHFILEOPSTRUCTW()
    fileop.hwnd = 0
    fileop.wFunc = FO_DELETE
    fileop.pFrom = LPCWSTR(path + '\0')
    fileop.pTo = None
    fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT
    fileop.fAnyOperationsAborted = 0
    fileop.hNameMappings = 0
    fileop.lpszProgressTitle = None
    result = SHFileOperationW(byref(fileop))
    if result:
        msg = "Couldn't perform operation. Error code: %d" % result
        raise OSError(msg)


text:
<?php
namespace content_crm\member\billing;

class view
{
	public static function config()
	{
		\dash\data::page_title(T_("Billing information"));
		\dash\data::page_desc(T_("Billing"));

		\content_crm\member\main\view::dataRowMember();

		$user_id = \dash\coding::decode(\dash\request::get('id'));

		$user_unit    = \dash\app\units::find_user_unit($user_id, true);
		$user_unit_id = \dash\app\units::get_id($user_unit);
		$user_unit_id = (int) $user_unit_id;

		if($user_unit == 'dollar')
		{
			$user_unit             = '$';
		}

		\dash\data::userUnit(T_($user_unit));

		$user_cash_all = \dash\db\transactions::budget($user_id, ['unit' => 'all']);

		\dash\data::userCash($user_cash_all);

		$meta            = [];
		$meta['user_id'] = $user_id;
		$meta['verify']  = 1;
		$billing_history = \dash\db\transactions::search(null, $meta);
		\dash\data::history($billing_history);
	}
}
?>


text:
(function (global, factory) {
    if (typeof define === "function" && define.amd) {
        define(["exports"], factory);
    } else if (typeof exports !== "undefined") {
        factory(exports);
    } else {
        var mod = {
            exports: {}
        };
        factory(mod.exports);
        global.loadingModalUi = mod.exports;
    }
})(this, function (exports) {
    "use strict";

    Object.defineProperty(exports, "__esModule", {
        value: true
    });
    // Copyright (c) CBC/Radio-Canada. All rights reserved.
    // Licensed under the MIT license. See LICENSE file in the project root for full license information.

    var ViewModel = function ViewModel(context /*, componentInfo*/) {
        this.message = context.params.message;
    };

    exports.default = ViewModel;
});


text:
extern amic_status_t amic_ast_banner(const char *banner);
extern amic_status_t amic_ast_success(const char *response);
extern amic_status_t amic_ast_check_auth(const char *response);
extern amic_status_t amic_ast_event(const char *resp);
extern void remove_carriage_return(char *str);
extern void get_event_param(char *str, char *key, char *value);
extern void get_event_name(char *str, char *ev);

amic_status_t amic_init_conn(amic_conn_t **conn,
                             char *ip_addr,
                             unsigned int port)
{
    amic_status_t status = AMIC_STATUS_SUCCESS;
    amic_conn_t *new_conn = 0;
    new_conn = (amic_conn_t*) malloc(sizeof(amic_conn_t));

    if (!new_conn)
        return AMIC_STATUS_BAD_ALLOC;

    new_conn->ip_addr = strdup(ip_addr);
    new_conn->port = port;
    new_conn->loop = uv_default_loop();
    new_conn->state = AMIC_STATE_INIT;
    new_conn->ev_map = hashmap_new();

#ifndef NDEBUG
    AMIC_DBG("Created amic_conn [%s:%d]", new_conn->ip_addr, new_conn->port);
#endif

    //TODO: Check if is ipv4 or ipv6 connection
    uv_tcp_init(new_conn->loop, &new_conn->handler);
    status = uv_ip4_addr(new_conn->ip_addr,
                         new_conn->port,
                         &new_conn->t.addr4);

    if (status != 0) {
        AMIC_ERR("Get ip status %d:%s", status, uv_strerror(status));
        return AMIC_STATUS_CONNECTION_FAILED;
    }

    *conn = new_conn;
    return status;
}

typedef struct {
    amic_conn_t *conn;
    char *data;
} process_event_pair_t;

void process_event(uv_work_t *req)
{
    assert(req);
    assert(req->data);

    process_event_pair_t *pep = 0;
    pep = (process_event_pair_t*) req->data;

    amic_conn_t *conn = 0;
    conn = pep->conn;
    char *data = pep->data;

    char *cur_line = data;
    int count = 0;
    amic_ev_cb cb;
    map_t map_keys = 0;
    int map_err = MAP_MISSING;
    while (cur_line) {
        char *key = 0, *value = 0;
        if (!cur_line) break;

        char *next_line = strchr(cur_line, '\n');
        if (next_line) *next_line = '\0';

        if (cur_line != '\0' && *cur_line != '\r' && strlen(cur_line) > 0) {
            const size_t kv_size = strlen(cur_line);
            key = (char*) malloc(kv_size);
            value = (char*) malloc(kv_size);

            remove_carriage_return(cur_line);
            get_event_param(cur_line, key, value);

            if (!strncmp("Event", key, strlen(key))) {
                count++;
                if (count > 1) break;

                map_err = hashmap_get(conn->ev_map, value, (void**) (&cb));
                if (map_err != MAP_OK) {
                    free(key); free(value);
                    break;
                }
            }

            if (map_err == MAP_OK) {
                if (!map_keys)
                    map_keys = hashmap_new();
                    //TODO: Must delete key and value from mem someday
                int put_err = hashmap_put(map_keys, key, value);
                if (put_err != MAP_OK) {
                    AMIC_ERR("Error on put key %s", key);
                }
            }
        }

        if (next_line) *next_line = '\n';
        cur_line = next_line ? (next_line+1) : NULL;
    }

    if (map_err == MAP_OK && map_keys) {
        cb(conn, map_keys);
        int index = 0;
        hashmap_free(map_keys);
    }

    free(pep->data);
    free(pep);
}

void after_process_event(uv_work_t *req, int status)
{
    assert(req);
    assert(req->data);
    free(req);
}

void on_read(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf)
{
    if (nread <= -1) {
        if (nread != UV_EOF)
            AMIC_ERR("Read error %s", uv_strerror(nread));
        return;
    }

    amic_conn_t *conn = (amic_conn_t*) stream->data;
    assert(conn != NULL);

    char *data = (char*) malloc(sizeof(char) * (nread+1));
    data[nread] = '\0';
    memcpy(data, buf->base, nread+1);

    switch (conn->state) {
        case AMIC_STATE_INIT: {
            if (amic_ast_banner(data) == AMIC_STATUS_SUCCESS) {
                conn->state = AMIC_STATE_OPEN;
                conn->conn_cb((struct amic_conn_t*)conn, AMIC_STATUS_SUCCESS);
            } else {
                conn->state = AMIC_STATE_CLOSE;
                conn->conn_cb((struct amic_conn_t*)conn, AMIC_STATUS_CONNECTION_FAILED);
                uv_read_stop(stream);
            }
        } break;
        case AMIC_STATE_OPEN: {
            switch (conn->cmd) {
                case AMIC_CMD_NONE:
                    break;
                case AMIC_CMD_LOGIN: {
                    if (amic_ast_check_auth(data) == AMIC_STATUS_SUCCESS)
                        conn->cmd_cb((struct amic_conn_t*)conn, AMIC_STATUS_SUCCESS);
                    else
                        conn->cmd_cb((struct amic_conn_t*)conn, AMIC_STATUS_CONNECTION_FAILED);
                } break;
                case AMIC_CMD_QUEUE_STATUS: {
                    AMIC_DBG("DATA: %s", data);
                } break;
            }

            if (strstr(data, "Event:")) {
               uv_work_t *queue_req = 0;
               queue_req = (uv_work_t*) malloc(sizeof(uv_work_t));

               if (!queue_req) {
                    AMIC_DBG("Cannot alloc work queue");
               } else {
                   process_event_pair_t *pep = 0;
                   pep = (process_event_pair_t*) malloc(sizeof(process_event_pair_t));
                   pep->conn = conn;
                   pep->data = data;
                   queue_req->data = (void*) pep;
                   uv_queue_work(conn->loop, queue_req, process_event, after_process_event);
               }
            }

            conn->cmd = AMIC_CMD_NONE;

        } break;
        case AMIC_STATE_CLOSE:
            break;
        default:
            AMIC_ERR("Unknow state %d", conn->state);
            break;
    }

    free(buf->base);
}

void alloc_buffer(uv_handle_t *handle, size_t size, uv_buf_t *buf) {
    *buf = uv_buf_init((char*) malloc(size), size);
}

void on_connect(uv_connect_t *req, int status)
{
    if (status < 0) {
        AMIC_ERR("Connected status %d:%s", status, uv_strerror(status));
        return;
    }

    req->handle->data = req->data;
    uv_read_start(req->handle, alloc_buffer, on_read);
}

amic_status_t amic_open(amic_conn_t *conn,
                        amic_conn_cb conn_cb)
{
    amic_status_t status = AMIC_STATUS_SUCCESS;

    if (!conn)
        return AMIC_STATUS_NULL_PTR;

#ifndef NDEBUG
    AMIC_DBG("Will connect to %s:%d", conn->ip_addr, conn->port);
#endif

    conn->conn_cb = conn_cb;
    conn->tunnel.data = (void*) conn;

    status = uv_tcp_connect(&conn->tunnel,
                            &conn->handler,
                            &conn->t.addr,
                            on_connect);

    if (status != 0) {
#ifndef NDEBUG
        AMIC_DBG("Get tcp connect status %d:%s", status, uv_strerror(status));
#endif
        return AMIC_STATUS_CONNECTION_FAILED;
    }

    return status;
}

void on_amic_close(uv_handle_t *handle)
{
    amic_conn_t *conn = (amic_conn_t*) handle->data;
    if (!conn)
        return;

    free(conn->ip_addr);
    hashmap_free(conn->ev_map);
    free(conn);
}

void amic_close(amic_conn_t *conn)
{
    if (!conn)
        return;

    conn->handler.data = (void*) conn;
    uv_close((uv_handle_t*) &conn->handler, on_amic_close);
}

#endif


text:
class PlaydatesController < ApplicationController

  def index
    if logged_in?
      @user = User.find(params[:user_id])
      if current_user.id == @user.id
        @attending = User.find(params[:user_id]).all_playdates
        @pending = User.find(params[:user_id]).pending_playdates
        render 'index'
      else
        redirect_to no_access_path
      end
    else
      redirect_to login_path
    end
  end

  def new
    @playdate = Playdate.new
  end

  def create
    @user = User.find(params[:user_id])
    @playdate = Playdate.new(playdate_params)
    if @playdate.save
      send_cal_event(@playdate, current_user) if current_user.provider == "google"
      redirect_to new_user_playdate_attendee_path(@user.id, @playdate.id)
    else
      render 'new'
    end
  end

  def show
    @playdate = Playdate.find(params[:id])
    key = ENV['GOOGLE_MAP']
    @google_api_search = "https://www.google.com/maps/embed/v1/search?q=  #{sanitize_search_term(@playdate.location)}&key=#{key}"
  end

  def destroy
    @user = User.find(params[:user_id])
    @playdate = Playdate.find(params[:id])
    flash[:confirm] = "You have deleted #{@playdate.title}"
    @playdate.destroy
    redirect_to user_playdates_path(@user)
  end

  private
  def playdate_params
    params.require(:playdate).permit(:title, :time, :description, :date,:location).merge(host_id: current_user.id)
  end

end


text:
package org.rioproject.system.capability.platform;

import org.rioproject.system.capability.PlatformCapability;

/**
 * The OperatingSystem class defines attributes describing the operating system.
 *
 * @author Dennis Reedy
 */
public class OperatingSystem extends PlatformCapability {
    private static final long serialVersionUID = 1L;
    static final String DEFAULT_DESCRIPTION = "Operating System";
    public static final String ID = "OperatingSystem";

    /**
     * Create a OperatingSystem object
     */
    public OperatingSystem() {
        this(DEFAULT_DESCRIPTION);
    }

    /**
     * Create a OperatingSystem object with a description
     *
     * @param description The description
     */
    public OperatingSystem(final String description) {
        this.description = description;
        define(NAME, System.getProperty("os.name"));
        define(VERSION, System.getProperty("os.version"));
    }
}


text:
<?php

class ServiceConfigurationPresetChangedEvent extends Event
{

    public $ServiceConfiguration;

    public $ResetToDefaults;

    public function __construct(Scalr_ServiceConfiguration $serviceConfiguration, $resetToDefaults = false)
    {
        parent::__construct();
        $this->ServiceConfiguration = $serviceConfiguration;
        $this->ResetToDefaults = $resetToDefaults;
    }
}


text:
from lxml import objectify
from pyvcloud.vcd.client import EntityType
from pyvcloud.vcd.client import QueryResultFormat
from pyvcloud.vcd.client import RelationType
from pyvcloud.vcd.utils import to_dict

Ext = objectify.ElementMaker(
    annotate=False,
    namespace='http://www.vmware.com/vcloud/extension/v1.5',
    nsmap={None: "http://www.vmware.com/vcloud/v1.5",
           'vmext': 'http://www.vmware.com/vcloud/extension/v1.5'})

class Extension(object):

    TYPE_NAME = 'adminService'
    ATTRIBUTES = ['name', 'namespace', 'enabled',
                  'exchange', 'routingKey', 'priority',
                  'isAuthorizationEnabled', 'href', 'id']

    def __init__(self, client):
        self.client = client

    def list_extensions(self):
        query = self.client.get_typed_query(
            self.TYPE_NAME,
            query_result_format=QueryResultFormat.ID_RECORDS)
        return [to_dict(r, self.ATTRIBUTES) for r in query.execute()]

    def get_extension(self, name):
        ext = self.client.get_typed_query(
            self.TYPE_NAME,
            equality_filter=('name', name),
            query_result_format=QueryResultFormat.ID_RECORDS).find_unique()
        return to_dict(ext, self.ATTRIBUTES)

    def add_extension(self, name, namespace, routing_key, exchange, patterns):
        params = Ext.Service({'name': name})
        params.append(Ext.Namespace(namespace))
        params.append(Ext.Enabled('true'))
        params.append(Ext.RoutingKey(routing_key))
        params.append(Ext.Exchange(exchange))
        filters = Ext.ApiFilters()
        for pattern in patterns:
            filters.append(Ext.ApiFilter(Ext.UrlPattern(pattern.strip())))
        params.append(filters)
        ext = self.client.get_extension()
        ext_services = self.client.get_linked_resource(
            ext,
            RelationType.DOWN,
            EntityType.EXTENSION_SERVICES.value)
        return self.client.post_linked_resource(
            ext_services,
            RelationType.ADD,
            EntityType.ADMIN_SERVICE.value,
            params)

    def enable_extension(self, name, enabled=True):
        ext = self.client.get_typed_query(
            self.TYPE_NAME,
            equality_filter=('name', name),
            query_result_format=QueryResultFormat.RECORDS).find_unique()
        params = Ext.Service({'name': name})
        params.append(Ext.Namespace(ext.get('namespace')))
        params.append(Ext.Enabled('true' if enabled else 'false'))
        params.append(Ext.RoutingKey(ext.get('routingKey')))
        params.append(Ext.Exchange(ext.get('exchange')))
        self.client.put_resource(ext.get('href'), params, None)
        return ext.get('href')

    def delete_extension(self, name):
        href = self.enable_extension(name, enabled=False)
        return self.client.delete_resource(href)


text:
package org.workcraft.plugins.mpsat.tasks;

import java.util.List;

import org.workcraft.plugins.mpsat.MpsatParameters;
import org.workcraft.plugins.shared.tasks.ExternalProcessResult;
import org.workcraft.tasks.Result;

public class MpsatCombinedChainResult {
    private Result<? extends Object> exportResult;
    private Result<? extends ExternalProcessResult> pcompResult;
    private Result<? extends ExternalProcessResult> punfResult;
    private List<Result<? extends ExternalProcessResult>> mpsatResultList;
    private List<MpsatParameters> mpsatSettingsList;
    private String message;

    public MpsatCombinedChainResult(Result<? extends Object> exportResult,
            Result<? extends ExternalProcessResult> pcompResult,
            Result<? extends ExternalProcessResult> punfResult,
            List<Result<? extends ExternalProcessResult>> mpsatResultList,
            List<MpsatParameters> mpsatSettingsList, String message) {

        this.exportResult = exportResult;
        this.pcompResult = pcompResult;
        this.punfResult = punfResult;
        this.mpsatResultList = mpsatResultList;
        this.mpsatSettingsList = mpsatSettingsList;
        this.message = message;
    }

    public MpsatCombinedChainResult(Result<? extends Object> exportResult,
            Result<? extends ExternalProcessResult> pcompResult,
            Result<? extends ExternalProcessResult> punfResult,
            List<Result<? extends ExternalProcessResult>> mpsatResultList,
            List<MpsatParameters> mpsatSettingsList) {

        this(exportResult, pcompResult, punfResult, mpsatResultList, mpsatSettingsList, null);
    }

    public List<MpsatParameters> getMpsatSettingsList() {
        return mpsatSettingsList;
    }

    public Result<? extends Object> getExportResult() {
        return exportResult;
    }

    public Result<? extends ExternalProcessResult> getPcompResult() {
        return pcompResult;
    }

    public Result<? extends ExternalProcessResult> getPunfResult() {
        return punfResult;
    }

    public List<Result<? extends ExternalProcessResult>> getMpsatResultList() {
        return mpsatResultList;
    }

    public String getMessage() {
        return message;
    }

}


text:
//-*-c++-*-
//                     Array Scalarization
//                     -------------------
//
// Description:
//
// 	In loops, convert things that look like
//	do i
//	  a[i] = ...
//	  ... = a[i]
//
//	into
//
//	do i
//	  t = ...
//	  a[i] = t
//	  ... = t
//
//	This is useful because
//	  1) It gets rid of loads
//	  2) If it gets rid of all the loads to a local array then
//	     the array equivalencing algorithm will get rid of the array
//
//	Because SWP will do 1 as well as we do, we'll only apply this
//	algorithm to local arrays (Although it's trivial to change this).
//
// Exported functions:
//
// void Scalarize_Arrays(ARRAY_DIRECTED_GRAPH16 *dep_graph,
//	BOOL do_variants, BOOL do_invariants)
//
//
//
//

/**
*** $Source: bitbucket.org:berkeleylab/upc-translator.git/open64/osprey1.0/be/lno/sclrze.h $
**/

#ifndef SCLRZE_RCS_ID
#define SCLRZE_RCS_ID
#ifdef _KEEP_RCS_ID
static char *sclrze = "$Source: bitbucket.org:berkeleylab/upc-translator.git/open64/osprey1.0/be/lno/sclrze.h $ $Revision: 1.2 $";
#endif /* _KEEP_RCS_ID */
#endif

#ifndef SCLRZE_DECLARE

void Scalarize_Arrays(ARRAY_DIRECTED_GRAPH16 *dep_graph,
	BOOL do_variants, BOOL do_invariants, REDUCTION_MANAGER *red_manager);

#endif  // SCLRZE_DECLARE


text:
<?php

namespace App\Tests\Unit\Pipes\Account\Store;

use App\Http\Requests\Account\Store as RequestStore;
use App\Models\Account;
use App\Passables\Account\Store;
use App\Pipes\Account\Store\Create;
use App\Tests\Unit\Pipes\Store\Create as StoreCreate;
use Exception;

/**
 * Class SearchTest
 * @package App\Tests\Unit\Pipes\Account\Store
 */
class CreateTest extends StoreCreate
{
    /**
     * SearchTest constructor.
     *
     * @param null   $name
     * @param array  $data
     * @param string $dataName
     */
    public function __construct($name = null, array $data = [], $dataName = '')
    {
        parent::__construct(
            $name,
            $data,
            $dataName
        );

        $this->setPassable(Store::class);
        $this->setRequest(RequestStore::class);
        $this->setPipe(Create::class);
    }

    /**
     * @group App
     * @group App.Pipes
     * @group App.Pipes.Account
     * @group App.Pipes.Account.Store
     * @group App.Pipes.Account.Store.Create
     * @group App.Pipes.Account.Store.Create.Success
     */
    public function testCreateSuccess()
    {
        $params = [
            'name' => 'Testing',
            'description' => 'An account built for testing',
        ];
        $this->setParams($params);

        $responseModel = $this->createSuccess();
        $dbModel = Account::find($responseModel->id);

        $this->assertEquals(
            $params['name'],
            $responseModel->name
        );
        $this->assertEquals(
            $params['name'],
            $dbModel->name
        );

        $this->assertEquals(
            $params['description'],
            $responseModel->description
        );
        $this->assertEquals(
            $params['description'],
            $dbModel->description
        );
    }

    /**
     * @group                    App
     * @group                    App.Pipes
     * @group                    App.Pipes.Account
     * @group                    App.Pipes.Account.Store
     * @group                    App.Pipes.Account.Store.Create
     * @group                    App.Pipes.Account.Store.Create.Failure
     * @expectedExceptionCode    500
     * @expectedException Exception
     * @expectedExceptionMessage Account create failed.
     */
    public function testCreateFailure()
    {
        $this->createFailure();
    }
}


text:
import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';

const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;

export default class Icon extends Component {
  render () {
    const { className, colorIndex } = this.props;
    let { a11yTitle, size, responsive } = this.props;
    let { intl } = this.context;

    const classes = classnames(
      CLASS_ROOT,
      `${CLASS_ROOT}-refresh`,
      className,
      {
        [`${CLASS_ROOT}--${size}`]: size,
        [`${CLASS_ROOT}--responsive`]: responsive,
        [`${COLOR_INDEX}-${colorIndex}`]: colorIndex
      }
    );

    a11yTitle = a11yTitle || Intl.getMessage(intl, 'refresh');

    return <svg version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000000" strokeWidth="2" d="M20,8 C18.5974037,5.04031171 15.536972,3 12,3 C7.02943725,3 3,7.02943725 3,12 C3,16.9705627 7.02943725,21 12,21 L12,21 C16.9705627,21 21,16.9705627 21,12 M21,3 L21,9 L15,9"/></svg>;
  }
};

Icon.contextTypes = {
  intl: PropTypes.object
};

Icon.defaultProps = {
  responsive: true
};

Icon.displayName = 'Refresh';

Icon.icon = true;

Icon.propTypes = {
  a11yTitle: PropTypes.string,
  colorIndex: PropTypes.string,
  size: PropTypes.oneOf(['small', 'medium', 'large', 'xlarge', 'huge']),
  responsive: PropTypes.bool
};


text:
Getting Started
===============

Compatibility
-------------

Play:  2.4.6
sbt:   0.13.9
Scala: 2.11.7

Add the dependency to your build
-----------------------------------

    resolvers += "Guardian Github Snapshots" at "http://guardian.github.com/maven/repo-releases"
    libraryDependencies += "com.gu" %% "management-play" % "8.0"

Look at the example!
-----------------------

The [example project](https://github.com/guardian/guardian-management-play/tree/master/example) has
management routes set up and uses some switches and timing metrics.

    $ git clone git@github.com:guardian/guardian-management-play.git
    $ cd guardian-management-play
    $ sbt
    > project example
    > run

Try the following URLs locally:

 * http://localhost:9000/scala-app
 * http://localhost:18080/management
 * http://localhost:18080/management/switchboard

Also, enable the `take-it-down` switch and retry `/scala-app`.

Using the internal server in Play 2
===================================

Configure your dependencies
---------------------------

    resolvers += "Guardian Github Snapshots" at "http://guardian.github.com/maven/repo-releases"
    libraryDependencies += "com.gu" %% "management-play" % "8.0"

Add to the play configuration
-----------------------------

Add the following line to `conf/application.conf`:

    play.modules.enabled += "com.gu.management.play.InternalManagementModule"

Bind the management pages
-------------------------

The module must have the pages and application name set in your Global onStart function.

Create a scala Object that mixes in the `com.gu.management.play.Management` trait to
provide the list of pages and your application name to the plugin:

```scala
package conf

object YourApplicationManagement extends Management {
  val applicationName = "your-application-name"

  lazy val pages = List(
    new ManifestPage,
    new HealthcheckManagementPage,
    new Switchboard(applicationName, Switches.all),
    StatusPage(applicationName, Metrics.all),
    new LogbackLevelPage(applicationName)
  )
}
```

If Global.scala doesn't exist in your project then create it with the
skeleton provided below. Otherwise add a call to `InternalManagementServer.start(...)`
to your onStart method.

```scala
import com.gu.management.play.InternalManagementServer
import conf.YourApplicationManagement
import play.api.Application

object Global {
  override def onStart(app: Application): Unit = {
    InternalManagementServer.start(app, YourApplicationManagement)
  }
}
```


text:
'use strict';

var resultController = angular.module('resultController', []);

resultController.controller('ResultController', ['$scope',
  function($scope) {
    var vm = this;

    vm.results = [];

    vm.clearResult = function() {
      vm.results = [];
    };

    $scope.$on('result', function(event, data) {
      vm.results.unshift(data.result);
      // We also have data.promise, but we don't need to do anything for now
    });

  }]);


text:
<?php
/**
 * User
 *
 *     作者: Tony (yanzhe@huoban.com)
 * 创建时间: 2016-xx-xx xx:xx
 * 修改记录:
 *
 */

namespace frontend\models;

use Yii;
use yii\base\Exception;
use yii\base\Security;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

class User extends ActiveRecord implements IdentityInterface {

    const ACTIVE = '已激活';
    const DELETED = '已删除';

    /**
     * @var string
     */
    private $_auth_key;

    /**
     * @return array
     */
    public function rules() {
        return array(
            ['id', 'required', 'message' => 'ID不能为空', 'on' => 'create'],
            ['email', 'email', 'message' => '请输入正确格式的邮箱', 'on' => 'create'],
            ['name', 'required', 'message' => '姓名不能为空', 'on' => 'create'],
            ['password', 'required', 'message' => '密码不能为空', 'on' => 'create'],
            ['salt', 'string'],
            ['status', 'default', 'value' => self::ACTIVE],
            ['status', 'in', 'range' => [self::ACTIVE, self::DELETED]],
            ['type', 'in', 'range' => [Admin::TYPE_ADMIN, Teacher::TYPE_TEACHER, Assistant::TYPE_ASSISTANT, Student::TYPE_STUDENT, 'on' => 'create']]
        );
    }

    /**
     * @return array
     */
    public function scenarios() {
        return [
            'create' => ['id', 'password', 'email', 'name', 'type'],
            'get' => ['id', 'name', 'email', 'type', 'status'],
            'update' => ['name', 'email', 'type', 'status'],
            'delete' => ['status']
        ];
    }

    /**
     * @return string
     */
    public static function tableName() {
        return 'users';
    }

    /**
     * @param string $password
     *
     * @return bool
     */
    public function validatePassword($password) {
        if (md5($password . $this->getAttribute('salt')) != $this->getAttribute('password')) {
            return false;
        }
        return true;
    }

    /**
     * @param string $username
     *
     * @return object
     */
    public static function findByUsername($username) {

        return self::findOne(['name' => $username, 'status' => self::ACTIVE]);
    }

    /**
     * @param $ID
     *
     * @return User
     */
    public static function findByID($ID) {

        return self::findOne(['id' => $ID]);
    }

    /**
     * @inheritdoc
     *
     * @return User
     */
    public static function findIdentity($id) {
        return static::findOne(['id' => $id, 'status' => self::ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey() {
        return $this->_auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey) {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * @inheritdoc
     */
    public function getID() {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null) {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     *
     * @return bool
     */
    public function create() {
        try {
            $salt_builder = new Security();
            $this->salt = $salt_builder->generateRandomString(10);
            $this->password = md5($this->password . $this->salt);
            $type = $this->type;
            $this->status = self::ACTIVE;

            if ($type == Teacher::TYPE_TEACHER) {
                $teacher = new Teacher();
                $teacher->id = $this->getID();
                $teacher->save();

            } elseif ($type == Assistant::TYPE_ASSISTANT) {
                $assistant = new Assistant();
                $assistant->id = $this->getID();
                $assistant->save();

            } elseif ($type == Student::TYPE_STUDENT) {
                $student = new Student();
                $student->id = $this->getID();
                $student->save();
            }

            $this->save();
            return true;

        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * delete
     */
    public function delete() {
        try {
            $this->status = self::DELETED;
            $this->save();
            $type = $this->getAttribute('type');
            $user_id = $this->getID();

            if ($type == Teacher::TYPE_TEACHER) {
                $teacher = Teacher::findByID($user_id);
                $teacher->delete();

            } elseif ($type == Assistant::TYPE_ASSISTANT) {
                $assistant = Assistant::findByID($user_id);
                $assistant->delete();

            } elseif ($type == Student::TYPE_STUDENT) {
                $student = Student::findByID($user_id);
                $student->delete();
                $grades = Grade::findAll(['student_id' => $user_id]);

                if ($grades) {
                    foreach ($grades as $grade) {
                        $grade->delete();
                    }
                }
            }

            return true;
        } catch (Exception $e) {
            var_dump($e);exit;
            return false;
        }
    }

}


text:
@class MYZStatusPic;

@interface MYZStatusPicView : UIImageView

@property (nonatomic, strong) MYZStatusPic * picData;

@end