text:
using OpenTK;
using OpenTK.Graphics.OpenGL;
using System;

namespace SmashForge.Rendering
{
    public static class ShapeDrawing
    {
        #region Taken from Brawllib render TKContext.cs
        public static void DrawSphere(Vector3 center, float radius, uint precision, bool useWireframe = false)
        {
            DrawSphereTransformed(center, radius, precision, Matrix4.Identity, useWireframe);
        }

        public static void DrawWireframeSphere(Vector3 center, float radius, uint precision)
        {
            DrawSphere(center, radius, precision, true);
        }

        public static void BeginTopLevelStencil()
        {
            GL.Enable(EnableCap.StencilTest);

            GL.StencilFunc(StencilFunction.Always, 1, 0xFF);
            GL.StencilMask(0xFF);
            GL.Disable(EnableCap.DepthTest);
            GL.Clear(ClearBufferMask.StencilBufferBit);
            GL.ColorMask(false, false, false, false);
        }

        // The same as beginTopLevelStencil but writes 0s instead of 1s
        // Also it does not clear the stencil buffer
        public static void BeginTopLevelAntiStencil()
        {
            GL.Enable(EnableCap.StencilTest);

            GL.StencilFunc(StencilFunction.Always, 0, 0xFF);
            GL.StencilMask(0xFF);
            GL.Disable(EnableCap.DepthTest);
            GL.ColorMask(false, false, false, false);
        }

        public static void EndTopLevelStencilAndDraw()
        {
            GL.ColorMask(true, true, true, true);
            GL.StencilFunc(StencilFunction.Equal, 1, 0xFF);
            GL.StencilMask(0x00);

            DrawSphere(Vector3.Zero, 100, 10);

            GL.StencilMask(0xFF);
            GL.Clear(ClearBufferMask.StencilBufferBit);
            GL.Disable(EnableCap.StencilTest);
            GL.Enable(EnableCap.DepthTest);
        }

        public static void ResetStencil()
        {
            GL.Enable(EnableCap.StencilTest);

            GL.StencilFunc(StencilFunction.Always, 1, 0xFF);
            GL.StencilMask(0xFF);
            GL.Disable(EnableCap.DepthTest);
            GL.Clear(ClearBufferMask.StencilBufferBit);
            GL.ColorMask(false, false, false, false);

            GL.ColorMask(true, true, true, true);
            GL.StencilFunc(StencilFunction.Equal, 1, 0xFF);
            GL.StencilMask(0x00);

            GL.StencilMask(0xFF);
            GL.Clear(ClearBufferMask.StencilBufferBit);
            GL.Disable(EnableCap.StencilTest);
            GL.Enable(EnableCap.DepthTest);
        }

        public static void DrawSphereTransformedVisible(Vector3 center, float radius, uint precision, Matrix4 transform)
        {
            GL.Enable(EnableCap.StencilTest);

            GL.StencilFunc(StencilFunction.Always, 1, 0xFF);
            GL.StencilMask(0xFF);
            GL.Disable(EnableCap.DepthTest);
            GL.Clear(ClearBufferMask.StencilBufferBit);
            GL.ColorMask(false, false, false, false);

            DrawSphereTransformed(center, radius, precision, transform);

            GL.ColorMask(true, true, true, true);
            GL.StencilFunc(StencilFunction.Equal, 1, 0xFF);
            GL.StencilMask(0x00);
            GL.Disable(EnableCap.CullFace);

            DrawSphere(Vector3.Zero, 100, 10);

            GL.StencilMask(0xFF);
            GL.Clear(ClearBufferMask.StencilBufferBit);
            GL.Enable(EnableCap.StencilTest);
            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.CullFace);
        }

        public static void DrawWireframeSphereTransformedVisible(Vector3 center, float radius, uint precision, Matrix4 transform)
        {
            GL.Enable(EnableCap.StencilTest);

            GL.StencilFunc(StencilFunction.Always, 1, 0xFF);
            GL.StencilMask(0xFF);
            GL.Disable(EnableCap.DepthTest);
            GL.Clear(ClearBufferMask.StencilBufferBit);
            GL.ColorMask(false, false, false, false);

            DrawWireframeSphereTransformed(center, radius, precision, transform);

            GL.ColorMask(true, true, true, true);
            GL.StencilFunc(StencilFunction.Equal, 1, 0xFF);
            GL.StencilMask(0x00);
            GL.Disable(EnableCap.CullFace);

            DrawSphere(Vector3.Zero, 100, 10);

            GL.StencilMask(0xFF);
            GL.Clear(ClearBufferMask.StencilBufferBit);
            GL.Enable(EnableCap.StencilTest);
            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.CullFace);
        }

        public static void DrawSphereTransformed(Vector3 center, float radius, uint precision, Matrix4 transform, bool useWireframe = false)
        {
            PrimitiveType primitiveType = PrimitiveType.TriangleStrip;
            if (useWireframe)
                primitiveType = PrimitiveType.LineStrip;

            if (radius < 0.0f)
                radius = -radius;

            if (radius == 0.0f)
                return;

            if (precision == 0)
                return;

            float halfPi = (float)(Math.PI * 0.5);
            float oneThroughPrecision = 1.0f / precision;
            float twoPiThroughPrecision = (float)(Math.PI * 2.0 * oneThroughPrecision);

            float theta1, theta2, theta3;
            Vector3 norm = new Vector3(), pos = new Vector3();

            for (uint j = 0; j < precision / 2; j++)
            {
                theta1 = (j * twoPiThroughPrecision) - halfPi;
                theta2 = ((j + 1) * twoPiThroughPrecision) - halfPi;

                GL.Begin(primitiveType);
                for (uint i = 0; i <= precision; i++)
                {
                    theta3 = i * twoPiThroughPrecision;

                    norm.X = (float)(Math.Cos(theta2) * Math.Cos(theta3));
                    norm.Y = (float)Math.Sin(theta2);
                    norm.Z = (float)(Math.Cos(theta2) * Math.Sin(theta3));
                    pos.X = center.X + radius * norm.X;
                    pos.Y = center.Y + radius * norm.Y;
                    pos.Z = center.Z + radius * norm.Z;

                    GL.Normal3(norm.X, norm.Y, norm.Z);
                    GL.TexCoord2(i * oneThroughPrecision, 2.0f * (j + 1) * oneThroughPrecision);
                    GL.Vertex3(Vector3.TransformPosition(new Vector3(pos.X, pos.Y, pos.Z), transform));

                    norm.X = (float)(Math.Cos(theta1) * Math.Cos(theta3));
                    norm.Y = (float)Math.Sin(theta1);
                    norm.Z = (float)(Math.Cos(theta1) * Math.Sin(theta3));
                    pos.X = center.X + radius * norm.X;
                    pos.Y = center.Y + radius * norm.Y;
                    pos.Z = center.Z + radius * norm.Z;

                    GL.Normal3(norm.X, norm.Y, norm.Z);
                    GL.TexCoord2(i * oneThroughPrecision, 2.0f * j * oneThroughPrecision);
                    GL.Vertex3(Vector3.TransformPosition(new Vector3(pos.X, pos.Y, pos.Z), transform));
                }
                GL.End();
            }
        }

        public static void DrawWireframeSphereTransformed(Vector3 center, float radius, uint precision, Matrix4 transform)
        {
            if (radius < 0.0f)
                radius = -radius;

            if (radius == 0.0f)
                return;

            if (precision == 0)
                return;

            float halfPi = (float)(Math.PI * 0.5);
            float oneThroughPrecision = 1.0f / precision;
            float twoPiThroughPrecision = (float)(Math.PI * 2.0 * oneThroughPrecision);

            float theta1, theta2, theta3;
            Vector3 norm = new Vector3(), pos = new Vector3();

            for (uint j = 0; j < precision / 2; j++)
            {
                theta1 = (j * twoPiThroughPrecision) - halfPi;
                theta2 = ((j + 1) * twoPiThroughPrecision) - halfPi;

                GL.Begin(PrimitiveType.LineStrip);
                for (uint i = 0; i <= precision; i++)
                {
                    theta3 = i * twoPiThroughPrecision;

                    norm.X = (float)(Math.Cos(theta2) * Math.Cos(theta3));
                    norm.Y = (float)Math.Sin(theta2);
                    norm.Z = (float)(Math.Cos(theta2) * Math.Sin(theta3));
                    pos.X = center.X + radius * norm.X;
                    pos.Y = center.Y + radius * norm.Y;
                    pos.Z = center.Z + radius * norm.Z;

                    GL.Normal3(norm.X, norm.Y, norm.Z);
                    GL.TexCoord2(i * oneThroughPrecision, 2.0f * (j + 1) * oneThroughPrecision);
                    GL.Vertex3(Vector3.TransformPosition(new Vector3(pos.X, pos.Y, pos.Z), transform));

                    norm.X = (float)(Math.Cos(theta1) * Math.Cos(theta3));
                    norm.Y = (float)Math.Sin(theta1);
                    norm.Z = (float)(Math.Cos(theta1) * Math.Sin(theta3));
                    pos.X = center.X + radius * norm.X;
                    pos.Y = center.Y + radius * norm.Y;
                    pos.Z = center.Z + radius * norm.Z;

                    GL.Normal3(norm.X, norm.Y, norm.Z);
                    GL.TexCoord2(i * oneThroughPrecision, 2.0f * j * oneThroughPrecision);
                    GL.Vertex3(Vector3.TransformPosition(new Vector3(pos.X, pos.Y, pos.Z), transform));
                }
                GL.End();
            }
        }

        public static void DrawReducedCylinderTransformed(Vector3 p1, Vector3 p2, float r, Matrix4 transform)
        {
            Vector3 yAxis = new Vector3(0, 1, 0);
            Vector3 d = p2 - p1;
            float height = (float)Math.Sqrt(d.X * d.X + d.Y * d.Y + d.Z * d.Z) / 2;

            Vector3 mid = (p1 + p2) / 2;

            Vector3 axis = Vector3.Cross(d, yAxis);
            float angle = (float)Math.Acos(Vector3.Dot(d.Normalized(), yAxis));

            GL.Enable(EnableCap.StencilTest);

            GL.StencilFunc(StencilFunction.Always, 1, 0xFF);
            GL.StencilMask(0xFF);
            GL.Disable(EnableCap.DepthTest);
            GL.Clear(ClearBufferMask.StencilBufferBit);
            GL.ColorMask(false, false, false, false);

            DrawSphereTransformed(p1, r, 20, transform);
            DrawSphereTransformed(p2, r, 20, transform);

            //  sides
            GL.PushMatrix();

            GL.MultMatrix(ref transform);
            GL.Translate(mid);
            GL.Rotate(-(float)(angle * (180 / Math.PI)), axis);

            GL.Begin(PrimitiveType.QuadStrip);
            for (int j = 0; j <= 8 * 3; j += 1)
            {
                GL.Vertex3((float)Math.Cos(j) * r, +height, (float)Math.Sin(j) * r);
                GL.Vertex3((float)Math.Cos(j) * r, -height, (float)Math.Sin(j) * r);
            }
            GL.End();

            GL.PopMatrix();

            GL.ColorMask(true, true, true, true);
            GL.StencilFunc(StencilFunction.Equal, 1, 0xFF);
            GL.StencilMask(0x00);
            GL.Disable(EnableCap.CullFace);

            DrawSphere(Vector3.Zero, 100, 10);

            GL.StencilMask(0xFF);
            GL.Clear(ClearBufferMask.StencilBufferBit);
            GL.Enable(EnableCap.StencilTest);
            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.CullFace);
        }

        public static void DrawWireframeCylinderTransformed(Vector3 p1, Vector3 p2, float r, Matrix4 transform)
        {
            Vector3 yAxis = new Vector3(0, 1, 0);
            Vector3 d = p2 - p1;
            float height = (float)Math.Sqrt(d.X * d.X + d.Y * d.Y + d.Z * d.Z) / 2;

            Vector3 mid = (p1 + p2) / 2;

            Vector3 axis = Vector3.Cross(d, yAxis);
            float angle = (float)Math.Acos(Vector3.Dot(d.Normalized(), yAxis));

            GL.Enable(EnableCap.StencilTest);

            GL.StencilFunc(StencilFunction.Always, 1, 0xFF);
            GL.StencilMask(0xFF);
            GL.Disable(EnableCap.DepthTest);
            GL.Clear(ClearBufferMask.StencilBufferBit);
            GL.ColorMask(false, false, false, false);

            DrawWireframeSphereTransformed(p1, r, 10, transform);
            DrawWireframeSphereTransformed(p2, r, 10, transform);

            //  sides
            GL.PushMatrix();

            double[] f = new double[] {
                transform.M11, transform.M12, transform.M13, transform.M14,
                transform.M21, transform.M22, transform.M23, transform.M24,
                transform.M31, transform.M32, transform.M33, transform.M34,
                transform.M41, transform.M42, transform.M43, transform.M44,
            };
            GL.MultMatrix(f);
            GL.Translate(mid);
            GL.Rotate(-(float)(angle * (180 / Math.PI)), axis);

            GL.Begin(PrimitiveType.LineStrip);
            for (int j = 0; j <= 8 * 3; j += 1)
            {
                GL.Vertex3((float)Math.Cos(j) * r, +height, (float)Math.Sin(j) * r);
                GL.Vertex3((float)Math.Cos(j) * r, -height, (float)Math.Sin(j) * r);
            }
            GL.End();

            GL.PopMatrix();

            GL.ColorMask(true, true, true, true);
            GL.StencilFunc(StencilFunction.Equal, 1, 0xFF);
            GL.StencilMask(0x00);
            GL.Disable(EnableCap.CullFace);

            DrawSphere(Vector3.Zero, 100, 10);

            GL.StencilMask(0xFF);
            GL.Clear(ClearBufferMask.StencilBufferBit);
            GL.Enable(EnableCap.StencilTest);
            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.CullFace);
        }

        public static void DrawCylinder(Vector3 p1, Vector3 p2, float r, bool useWireFrame = false)
        {
            PrimitiveType primitiveType = PrimitiveType.TriangleStrip;
            PrimitiveType sidePrimitiveType = PrimitiveType.QuadStrip;
            int sideIterations = 360;

            if (useWireFrame)
            {
                primitiveType = PrimitiveType.LineStrip;
                sidePrimitiveType = PrimitiveType.LineStrip;
                sideIterations = 45;
            }

            int q = 8;
            int p = 20;

            Vector3 yAxis = new Vector3(0, 1, 0);
            Vector3 d = p2 - p1;
            float height = (float)Math.Sqrt(d.X * d.X + d.Y * d.Y + d.Z * d.Z) / 2;

            Vector3 mid = (p1 + p2) / 2;

            Vector3 axis = Vector3.Cross(d, yAxis);
            float angle = (float)Math.Acos(Vector3.Dot(d.Normalized(), yAxis));

            GL.PushMatrix();
            GL.Translate(p1);
            GL.Rotate(-(float)((angle) * (180 / Math.PI)), axis);
            for (int j = 0; j < q; j++)
            {
                GL.Begin(primitiveType);
                for (int i = 0; i <= p; i++)
                {
                    GL.Vertex3(r * Math.Cos((float)(j + 1) / q * Math.PI / 2.0) * Math.Cos(2.0 * (float)i / p * Math.PI),
                        -r * Math.Sin((float)(j + 1) / q * Math.PI / 2.0),
                        r * Math.Cos((float)(j + 1) / q * Math.PI / 2.0) * Math.Sin(2.0 * (float)i / p * Math.PI));
                    GL.Vertex3(r * Math.Cos((float)j / q * Math.PI / 2.0) * Math.Cos(2.0 * (float)i / p * Math.PI),
                        -r * Math.Sin((float)j / q * Math.PI / 2.0),
                        r * Math.Cos((float)j / q * Math.PI / 2.0) * Math.Sin(2.0 * (float)i / p * Math.PI));
                }
                GL.End();
            }
            GL.PopMatrix();

            GL.PushMatrix();
            GL.Translate(p2);
            GL.Rotate(-(float)(angle * (180 / Math.PI)), axis);
            for (int j = 0; j < q; j++)
            {
                GL.Begin(primitiveType);
                for (int i = 0; i <= p; i++)
                {
                    GL.Vertex3(r * Math.Cos((float)(j + 1) / q * Math.PI / 2.0) * Math.Cos(2.0 * (float)i / p * Math.PI),
                        r * Math.Sin((float)(j + 1) / q * Math.PI / 2.0),
                        r * Math.Cos((float)(j + 1) / q * Math.PI / 2.0) * Math.Sin(2.0 * (float)i / p * Math.PI));
                    GL.Vertex3(r * Math.Cos((float)j / q * Math.PI / 2.0) * Math.Cos(2.0 * (float)i / p * Math.PI),
                        r * Math.Sin((float)j / q * Math.PI / 2.0),
                        r * Math.Cos((float)j / q * Math.PI / 2.0) * Math.Sin(2.0 * (float)i / p * Math.PI));
                }
                GL.End();
            }
            GL.PopMatrix();

            /*  sides */
            GL.PushMatrix();

            GL.Translate(mid);
            GL.Rotate(-(float)(angle * (180 / Math.PI)), axis);

            GL.Begin(sidePrimitiveType);
            for (int j = 0; j <= sideIterations; j += 1)
            {
                GL.Vertex3((float)Math.Cos(j) * r, +height, (float)Math.Sin(j) * r);
                GL.Vertex3((float)Math.Cos(j) * r, -height, (float)Math.Sin(j) * r);
            }
            GL.End();

            GL.PopMatrix();
        }

        public static void DrawWireframeCylinder(Vector3 p1, Vector3 p2, float r)
        {
            DrawCylinder(p1, p2, r, true);
        }

        public static void DrawCircle(float x, float y, float z, float radius, uint precision)
        {
            DrawCircle(new Vector3(x, y, z), radius, precision);
        }

        public static void DrawCircle(Vector3 center, float radius, uint precision)
        {
            float theta = 2.0f * (float)Math.PI / precision;
            float cosine = (float)Math.Cos(theta);
            float sine = (float)Math.Sin(theta);

            float x = radius;
            float y = 0;

            GL.Begin(PrimitiveType.TriangleFan);
            for (int i = 0; i < precision; i++)
            {
                GL.Vertex2(x + center.X, y + center.Y);

                //apply the rotation matrix
                var temp = x;
                x = cosine * x - sine * y;
                y = sine * temp + cosine * y;
            }
            GL.End();
        }

        public static void DrawCircleOutline(Vector3 center, float radius, uint precision)
        {
            float theta = 2.0f * (float)Math.PI / precision;
            float cosine = (float)Math.Cos(theta);
            float sine = (float)Math.Sin(theta);

            float x = radius;
            float y = 0;

            GL.Begin(PrimitiveType.LineStrip);
            for (int i = 0; i < precision + 1; i++)
            {
                GL.Vertex3(x + center.X, y + center.Y, center.Z);

                //apply the rotation matrix
                var temp = x;
                x = cosine * x - sine * y;
                y = sine * temp + cosine * y;
            }
            GL.End();
        }

        public static void DrawCube(Vector3 center, float size, bool useWireFrame = false)
        {
            DrawRectangularPrism(center, size, size, size, useWireFrame);
        }

        public static void DrawRectangularPrism(Vector3 center, float sizeX, float sizeY, float sizeZ, bool useWireFrame = false)
        {
            PrimitiveType primitiveType = PrimitiveType.Quads;
            if (useWireFrame)
            {
                GL.LineWidth(2);
                primitiveType = PrimitiveType.LineLoop;
            }

            GL.Begin(primitiveType);
            GL.Vertex3(center.X + sizeX, center.Y + sizeY, center.Z - sizeZ);
            GL.Vertex3(center.X - sizeX, center.Y + sizeY, center.Z - sizeZ);
            GL.Vertex3(center.X - sizeX, center.Y + sizeY, center.Z + sizeZ);
            GL.Vertex3(center.X + sizeX, center.Y + sizeY, center.Z + sizeZ);
            GL.End();

            GL.Begin(primitiveType);
            GL.Vertex3(center.X + sizeX, center.Y - sizeY, center.Z + sizeZ);
            GL.Vertex3(center.X - sizeX, center.Y - sizeY, center.Z + sizeZ);
            GL.Vertex3(center.X - sizeX, center.Y - sizeY, center.Z - sizeZ);
            GL.Vertex3(center.X + sizeX, center.Y - sizeY, center.Z - sizeZ);
            GL.End();

            GL.Begin(primitiveType);
            GL.Vertex3(center.X + sizeX, center.Y + sizeY, center.Z + sizeZ);
            GL.Vertex3(center.X - sizeX, center.Y + sizeY, center.Z + sizeZ);
            GL.Vertex3(center.X - sizeX, center.Y - sizeY, center.Z + sizeZ);
            GL.Vertex3(center.X + sizeX, center.Y - sizeY, center.Z + sizeZ);
            GL.End();

            GL.Begin(primitiveType);
            GL.Vertex3(center.X + sizeX, center.Y - sizeY, center.Z - sizeZ);
            GL.Vertex3(center.X - sizeX, center.Y - sizeY, center.Z - sizeZ);
            GL.Vertex3(center.X - sizeX, center.Y + sizeY, center.Z - sizeZ);
            GL.Vertex3(center.X + sizeX, center.Y + sizeY, center.Z - sizeZ);
            GL.End();

            GL.Begin(primitiveType);
            GL.Vertex3(center.X - sizeX, center.Y + sizeY, center.Z + sizeZ);
            GL.Vertex3(center.X - sizeX, center.Y + sizeY, center.Z - sizeZ);
            GL.Vertex3(center.X - sizeX, center.Y - sizeY, center.Z - sizeZ);
            GL.Vertex3(center.X - sizeX, center.Y - sizeY, center.Z + sizeZ);
            GL.End();

            GL.Begin(primitiveType);
            GL.Vertex3(center.X + sizeX, center.Y + sizeY, center.Z - sizeZ);
            GL.Vertex3(center.X + sizeX, center.Y + sizeY, center.Z + sizeZ);
            GL.Vertex3(center.X + sizeX, center.Y - sizeY, center.Z + sizeZ);
            GL.Vertex3(center.X + sizeX, center.Y - sizeY, center.Z - sizeZ);
            GL.End();
        }
        #endregion
    }
}


text:
#ifndef __PVRUSB2_IOREAD_H
#define __PVRUSB2_IOREAD_H

#include "pvrusb2-io.h"

struct pvr2_ioread;

struct pvr2_ioread *pvr2_ioread_create(void);
void pvr2_ioread_destroy(struct pvr2_ioread *);
int pvr2_ioread_setup(struct pvr2_ioread *,struct pvr2_stream *);
struct pvr2_stream *pvr2_ioread_get_stream(struct pvr2_ioread *);
void pvr2_ioread_set_sync_key(struct pvr2_ioread *,
			      const char *sync_key_ptr,
			      unsigned int sync_key_len);
int pvr2_ioread_set_enabled(struct pvr2_ioread *,int fl);
int pvr2_ioread_read(struct pvr2_ioread *,void __user *buf,unsigned int cnt);
int pvr2_ioread_avail(struct pvr2_ioread *);

#endif /* __PVRUSB2_IOREAD_H */

/*
  Stuff for Emacs to see, in order to encourage consistent editing style:
  *** Local Variables: ***
  *** mode: c ***
  *** fill-column: 75 ***
  *** tab-width: 8 ***
  *** c-basic-offset: 8 ***
  *** End: ***
  */

redpajama_set_name: RedPajamaGithub


text:
package com.googlecode.wickedcharts.highcharts.jackson;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.googlecode.wickedcharts.highcharts.options.series.RangeCoordinate;

/**
 * Serializer for {@link RangeCoordinate}s.
 *
 * @author Tom Hombergs (tom.hombergs@gmail.com)
 *
 * @param <X>
 *          Type of x coordinate
 * @param <Y1>
 *          Type of y1 coordinate
 * @param <Y2>
 *          Type of y2 coordinate
 */
public class RangeCoordinateSerializer<X, Y1, Y2> extends JsonSerializer<RangeCoordinate<X, Y1, Y2>> {

	@Override
	public void serialize(final RangeCoordinate<X, Y1, Y2> value, final JsonGenerator jgen,
	    final SerializerProvider provider) throws IOException, JsonProcessingException {

		jgen.writeRawValue("[" + value.getX() + ", " + value.getY1() + ", " + value.getY2() + "]");
	}
}


text:
using CanInjectCrossAssemblies.Common;
using Stiletto;

namespace CanInjectCrossAssemblies.Main
{
    [Module(Injects = new[] { typeof(Injectable) })]
    public class MainModule
    {
        [Provides]
        public string ProvideString()
        {
            return "";
        }

        [Provides]
        public int ProvideInt()
        {
            return 0;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/mini_webview_forward_disable" android:state_pressed="true"></item>
    <item android:drawable="@drawable/mini_webview_forward" android:state_enabled="true"></item>
    <item android:drawable="@drawable/mini_webview_forward_disable" android:state_enabled="false"></item>

</selector>


text:
package com.amazonaws.services.kendra.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.kendra.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * OneDriveConfiguration JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class OneDriveConfigurationJsonUnmarshaller implements Unmarshaller<OneDriveConfiguration, JsonUnmarshallerContext> {

    public OneDriveConfiguration unmarshall(JsonUnmarshallerContext context) throws Exception {
        OneDriveConfiguration oneDriveConfiguration = new OneDriveConfiguration();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("TenantDomain", targetDepth)) {
                    context.nextToken();
                    oneDriveConfiguration.setTenantDomain(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("SecretArn", targetDepth)) {
                    context.nextToken();
                    oneDriveConfiguration.setSecretArn(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("OneDriveUsers", targetDepth)) {
                    context.nextToken();
                    oneDriveConfiguration.setOneDriveUsers(OneDriveUsersJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("InclusionPatterns", targetDepth)) {
                    context.nextToken();
                    oneDriveConfiguration.setInclusionPatterns(new ListUnmarshaller<String>(context.getUnmarshaller(String.class))

                    .unmarshall(context));
                }
                if (context.testExpression("ExclusionPatterns", targetDepth)) {
                    context.nextToken();
                    oneDriveConfiguration.setExclusionPatterns(new ListUnmarshaller<String>(context.getUnmarshaller(String.class))

                    .unmarshall(context));
                }
                if (context.testExpression("FieldMappings", targetDepth)) {
                    context.nextToken();
                    oneDriveConfiguration.setFieldMappings(new ListUnmarshaller<DataSourceToIndexFieldMapping>(DataSourceToIndexFieldMappingJsonUnmarshaller
                            .getInstance())

                    .unmarshall(context));
                }
                if (context.testExpression("DisableLocalGroups", targetDepth)) {
                    context.nextToken();
                    oneDriveConfiguration.setDisableLocalGroups(context.getUnmarshaller(Boolean.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return oneDriveConfiguration;
    }

    private static OneDriveConfigurationJsonUnmarshaller instance;

    public static OneDriveConfigurationJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new OneDriveConfigurationJsonUnmarshaller();
        return instance;
    }
}


text:
<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Cordova CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval' data: blob: filesystem: mediastream:;">
    <!-- Unicode is great -->
    <meta charset="utf-8" />
    <title>gokart - Loading</title>
    <!-- Disable awful IE compatibility mode -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <!-- Force fit-to-viewport sizing on mobile -->
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
    <!-- favicon -->
    <link rel="icon" href="dist/static/images/favicon.svg" sizes="any" type="image/svg+xml" />
    <link rel="icon" href="dist/static/images/favicon-256.png" sizes="16x16 32x32 64x64 128x128 256x256" type="image/png" />
    <!-- manually packaged copy of Font Awesome (for mobile) -->
    <link rel="stylesheet" type="text/css" href="dist/static/css/font-awesome/css/font-awesome.css" />
  </head>
  <body>
    <script type="text/javascript">
        var _env = {
            {%- if weatherforecast_url -%}
            "weatherForecastUrl":"{{weatherforecast_url}}",
            {% endif %}
        }
    </script>
    <!-- main global styles down here to load after all packaged styles -->
    <link rel="stylesheet" property="stylesheet" type="text/css" href="dist/static/css/style.css?version={{profile["dependents"]["styleMD5"]}}" />
    <app v-ref:app></app>
    <script src="dist/static/js/{{ envType }}.env.js?version={{profile["dependents"]["envMD5"]}}"></script>
    <script src="dist/vendor.js?version={{profile["dependents"]["vendorMD5"]}}"></script>
    <script src="dist/sss.js?version={{profile["build"]["md5"]}}"></script>
  </body>
</html>


text:
import {
    compareStringsCaseSensitive,
    Comparison,
    createTextSpan,
    DiagnosticMessage,
    Diagnostics,
    endsWith,
    every,
    Extension,
    fileExtensionIs,
    find,
    getAdjustedRenameLocation,
    getContextualTypeFromParentOrAncestorTypeNode,
    getLocaleSpecificMessage,
    getPathComponents,
    getTextOfIdentifierOrLiteral,
    getTextOfNode,
    getTouchingPropertyName,
    ImportSpecifier,
    isExternalModuleNameRelative,
    isIdentifier,
    isImportOrExportSpecifierName,
    isImportSpecifier,
    isInsideNodeModules,
    isLabelName,
    isLiteralNameOfPropertyDeclarationOrIndexAccess,
    isSourceFile,
    isStringLiteralLike,
    isStringOrNumericLiteralLike,
    Node,
    NumericLiteral,
    Path,
    Program,
    removeFileExtension,
    RenameInfo,
    RenameInfoFailure,
    RenameInfoSuccess,
    ScriptElementKind,
    ScriptElementKindModifier,
    some,
    SourceFile,
    StringLiteralLike,
    stripQuotes,
    Symbol,
    SymbolDisplay,
    SymbolFlags,
    SyntaxKind,
    tryGetImportFromModuleSpecifier,
    tryRemoveSuffix,
    TypeChecker,
    TypeFlags,
    UnionType,
    UserPreferences,
} from "./_namespaces/ts";

/** @internal */
export function getRenameInfo(program: Program, sourceFile: SourceFile, position: number, preferences: UserPreferences): RenameInfo {
    const node = getAdjustedRenameLocation(getTouchingPropertyName(sourceFile, position));
    if (nodeIsEligibleForRename(node)) {
        const renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, preferences);
        if (renameInfo) {
            return renameInfo;
        }
    }
    return getRenameInfoError(Diagnostics.You_cannot_rename_this_element);
}

function getRenameInfoForNode(
    node: Node,
    typeChecker: TypeChecker,
    sourceFile: SourceFile,
    program: Program,
    preferences: UserPreferences): RenameInfo | undefined {
    const symbol = typeChecker.getSymbolAtLocation(node);
    if (!symbol) {
        if (isStringLiteralLike(node)) {
            const type = getContextualTypeFromParentOrAncestorTypeNode(node, typeChecker);
            if (type && ((type.flags & TypeFlags.StringLiteral) || (
                (type.flags & TypeFlags.Union) && every((type as UnionType).types, type => !!(type.flags & TypeFlags.StringLiteral))
            ))) {
                return getRenameInfoSuccess(node.text, node.text, ScriptElementKind.string, "", node, sourceFile);
            }
        }
        else if (isLabelName(node)) {
            const name = getTextOfNode(node);
            return getRenameInfoSuccess(name, name, ScriptElementKind.label, ScriptElementKindModifier.none, node, sourceFile);
        }
        return undefined;
    }
    // Only allow a symbol to be renamed if it actually has at least one declaration.
    const { declarations } = symbol;
    if (!declarations || declarations.length === 0) return;

    // Disallow rename for elements that are defined in the standard TypeScript library.
    if (declarations.some(declaration => isDefinedInLibraryFile(program, declaration))) {
        return getRenameInfoError(Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library);
    }

    // Cannot rename `default` as in `import { default as foo } from "./someModule";
    if (isIdentifier(node) && node.originalKeywordKind === SyntaxKind.DefaultKeyword && symbol.parent && symbol.parent.flags & SymbolFlags.Module) {
        return undefined;
    }

    if (isStringLiteralLike(node) && tryGetImportFromModuleSpecifier(node)) {
        return preferences.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined;
    }

    // Disallow rename for elements that would rename across `*/node_modules/*` packages.
    const wouldRenameNodeModules = wouldRenameInOtherNodeModules(sourceFile, symbol, typeChecker, preferences);
    if (wouldRenameNodeModules) {
        return getRenameInfoError(wouldRenameNodeModules);
    }

    const kind = SymbolDisplay.getSymbolKind(typeChecker, symbol, node);
    const specifierName = (isImportOrExportSpecifierName(node) || isStringOrNumericLiteralLike(node) && node.parent.kind === SyntaxKind.ComputedPropertyName)
        ? stripQuotes(getTextOfIdentifierOrLiteral(node))
        : undefined;
    const displayName = specifierName || typeChecker.symbolToString(symbol);
    const fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol);
    return getRenameInfoSuccess(displayName, fullDisplayName, kind, SymbolDisplay.getSymbolModifiers(typeChecker,symbol), node, sourceFile);
}

function isDefinedInLibraryFile(program: Program, declaration: Node) {
    const sourceFile = declaration.getSourceFile();
    return program.isSourceFileDefaultLibrary(sourceFile) && fileExtensionIs(sourceFile.fileName, Extension.Dts);
}

function wouldRenameInOtherNodeModules(
    originalFile: SourceFile,
    symbol: Symbol,
    checker: TypeChecker,
    preferences: UserPreferences
): DiagnosticMessage | undefined {
    if (!preferences.providePrefixAndSuffixTextForRename && symbol.flags & SymbolFlags.Alias) {
        const importSpecifier = symbol.declarations && find(symbol.declarations, decl => isImportSpecifier(decl));
        if (importSpecifier && !(importSpecifier as ImportSpecifier).propertyName) {
            symbol = checker.getAliasedSymbol(symbol);
        }
    }
    const { declarations } = symbol;
    if (!declarations) {
        return undefined;
    }
    const originalPackage = getPackagePathComponents(originalFile.path);
    if (originalPackage === undefined) { // original source file is not in node_modules
        if (some(declarations, declaration => isInsideNodeModules(declaration.getSourceFile().path))) {
            return Diagnostics.You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder;
        }
        else {
            return undefined;
        }
    }
    // original source file is in node_modules
    for (const declaration of declarations) {
        const declPackage = getPackagePathComponents(declaration.getSourceFile().path);
        if (declPackage) {
            const length = Math.min(originalPackage.length, declPackage.length);
            for (let i = 0; i <= length; i++) {
                if (compareStringsCaseSensitive(originalPackage[i], declPackage[i]) !== Comparison.EqualTo) {
                    return Diagnostics.You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder;
                }
            }
        }
    }
    return undefined;
}

function getPackagePathComponents(filePath: Path): string[] | undefined {
    const components = getPathComponents(filePath);
    const nodeModulesIdx = components.lastIndexOf("node_modules");
    if (nodeModulesIdx === -1) {
        return undefined;
    }
    return components.slice(0, nodeModulesIdx + 2);
}

function getRenameInfoForModule(node: StringLiteralLike, sourceFile: SourceFile, moduleSymbol: Symbol): RenameInfo | undefined {
    if (!isExternalModuleNameRelative(node.text)) {
        return getRenameInfoError(Diagnostics.You_cannot_rename_a_module_via_a_global_import);
    }

    const moduleSourceFile = moduleSymbol.declarations && find(moduleSymbol.declarations, isSourceFile);
    if (!moduleSourceFile) return undefined;
    const withoutIndex = endsWith(node.text, "/index") || endsWith(node.text, "/index.js") ? undefined : tryRemoveSuffix(removeFileExtension(moduleSourceFile.fileName), "/index");
    const name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex;
    const kind = withoutIndex === undefined ? ScriptElementKind.moduleElement : ScriptElementKind.directory;
    const indexAfterLastSlash = node.text.lastIndexOf("/") + 1;
    // Span should only be the last component of the path. + 1 to account for the quote character.
    const triggerSpan = createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash);
    return {
        canRename: true,
        fileToRename: name,
        kind,
        displayName: name,
        fullDisplayName: name,
        kindModifiers: ScriptElementKindModifier.none,
        triggerSpan,
    };
}

function getRenameInfoSuccess(displayName: string, fullDisplayName: string, kind: ScriptElementKind, kindModifiers: string, node: Node, sourceFile: SourceFile): RenameInfoSuccess {
    return {
        canRename: true,
        fileToRename: undefined,
        kind,
        displayName,
        fullDisplayName,
        kindModifiers,
        triggerSpan: createTriggerSpanForNode(node, sourceFile)
    };
}

function getRenameInfoError(diagnostic: DiagnosticMessage): RenameInfoFailure {
    return { canRename: false, localizedErrorMessage: getLocaleSpecificMessage(diagnostic) };
}

function createTriggerSpanForNode(node: Node, sourceFile: SourceFile) {
    let start = node.getStart(sourceFile);
    let width = node.getWidth(sourceFile);
    if (isStringLiteralLike(node)) {
        // Exclude the quotes
        start += 1;
        width -= 2;
    }
    return createTextSpan(start, width);
}

/** @internal */
export function nodeIsEligibleForRename(node: Node): boolean {
    switch (node.kind) {
        case SyntaxKind.Identifier:
        case SyntaxKind.PrivateIdentifier:
        case SyntaxKind.StringLiteral:
        case SyntaxKind.NoSubstitutionTemplateLiteral:
        case SyntaxKind.ThisKeyword:
            return true;
        case SyntaxKind.NumericLiteral:
            return isLiteralNameOfPropertyDeclarationOrIndexAccess(node as NumericLiteral);
        default:
            return false;
    }
}


text:
package com.eljavatar.swingutils.core.components;

import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;

/**
 *
 * @author ElJavatar - Andres Mauricio (http://www.eljavatar.com)
 */
public class JPanelImage extends JPanel {

    private Image imagen;

    @Override
    public void paint(Graphics g) {
        if (imagen != null) {
            g.drawImage(imagen, 0, 0, getWidth(), getHeight(), this);
            this.setOpaque(false);
            super.paint(g);
        }
    }

    public void setImagen(Image nuevaImagen) {
        this.imagen = nuevaImagen;
        repaint();
    }

}


text:
import { connect } from 'react-redux';
import Tab from '../components/Tab';

const mapStateToProps = (state) => {
  const isUpdating = (state.allGoods.isFetched && state.allGoods.isFetching)
                  || (state.my.biddings.isFetched && state.my.biddings.isFetching)
                  || (state.my.goods.isFetched && state.my.goods.isFetching)
                  || state.graph.isFetching
                  || false;
  return {
    isUpdating,
  };
};

const TabContainer = connect(mapStateToProps)(Tab);

export default TabContainer;


text:
using System;
using FluentAssertions;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using RethinkDb.Driver.Net;
using System.Linq;
using Templates.Utils;

namespace RethinkDb.Driver.Tests
{
    [TestFixture]
    public class ConnectionTest
    {
        private const string DbName = "CSharpDriverTests";
        private const string TableName = "TableA";

        public static RethinkDB r = RethinkDB.r;

        private Connection conn;

        private void EnsureConnection()
        {
            if( conn == null )
            {
                this.conn = r.connection()
                    .hostname("192.168.0.11")
                    .port(RethinkDBConstants.DEFAULT_PORT)
                    .connect();
            }
        }

        [TestFixtureSetUp]
        public void BeforeRunningTestSession()
        {
            EnsureConnection();
            //try
            //{
            //    r.dbCreate(DbName).run(conn);

            //    r.db(DbName).wait_().run(conn);
            //    r.db(DbName).tableCreate(TableName).run(conn);
            //    r.db(DbName).table(TableName).wait_().run(conn);
            //}
            //catch
            //{
            //}
        }

        [TestFixtureTearDown]
        public void AfterRunningTestSession()
        {
            //try
            //{
            //    r.db(DbName).tableDrop(TableName).run(conn);
            //    r.dbDrop(DbName).run(conn);
            //    conn.close();
            //}
            //catch { }
        }

        [Test]
        [Explicit]
        public void create_table()
        {
            r.dbCreate(DbName).run(conn);

            r.db(DbName).wait_().run(conn);
            r.db(DbName).tableCreate(TableName).run(conn);
            r.db(DbName).table(TableName).wait_().run(conn);
        }

        [Test]
        [Explicit]
        public void delete_table()
        {
            r.db(DbName).tableDrop(TableName).run(conn);
            r.dbDrop(DbName).run(conn);
            conn.close();
        }

        [Test]
        public void can_connect()
        {
            var c = r.connection()
                .hostname("192.168.0.11")
                .port(RethinkDBConstants.DEFAULT_PORT)
                .timeout(60)
                .connect();

            var result = r.random(1, 9).add(r.random(1, 9)).run<int>(c);
            Console.WriteLine(result);
            result.Should().BeGreaterOrEqualTo(2).And.BeLessThan(18);
        }

        [Test]
        public void test_booleans()
        {
            bool t = r.expr(true).run<bool>(conn);
            t.Should().Be(true);
        }

        [Test]
        public void test_time_pesudo_type()
        {
            var t = r.now().run<DateTimeOffset>(conn);
            //ten minute limit for clock drift.
            t.Should().BeCloseTo(DateTimeOffset.UtcNow, 600000);
        }

        [Test]
        public void test_jvalue()
        {
            var t = r.now().run<JValue>(conn);
            //ten minute limit for clock drift.
            t.Dump();
        }

    }

}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, browserHistory } from 'react-router';
import { Provider } from 'react-redux';

import configStore from './store';

import routes from './routes';

import '../assets/favicon.ico';

require('../styles/main.sass');
require('./vendor.js');

console.clear();
ReactDOM.render((
  <Provider store={configStore()}>
    <Router history={browserHistory}>
      {routes}
    </Router>
  </Provider>
  ),
  document
)


text:
@interface UAFScrollView : UIScrollView

<UAFObject>

@property (nonatomic) UAFViewState viewState;

@end


text:
/* global AFRAME */
(function(){
  "use strict";

  AFRAME.registerComponent('wvrtd-goal', {
    dependencies: ["wvrtd-game-dynamics-parameters"],
    schema: {
      life: { type: "number", default: 10 }
	// overwritten by the game dynamics parameters component
    },
    init: function() {
      //var parameters = AFRAME.scenes[0].components["wvrtd-game-dynamics-parameters"].data;
      // despite the dependencies the scene at the time has no available components
      var that = this;

      this.mesh = document.createElement("a-entity")
      this.mesh.setAttribute("id", "goal-mesh");
      this.mesh.setAttribute("scale", "0.15 0.15 0.15");
      this.setModel("public/assets/models/castle/");
      this.el.appendChild(this.mesh);

      this.el.setAttribute("wvrtd-life-bar", {life : this.data.life, height : 0.2, radius : 0.01, position: "-0.124 0.225 -0.113"});

      NAF.connection.subscribeToDataChannel("goalHitNetwork", this.onGoalHitNetwork.bind(this));

      // could have also used a component function
      this.el.addEventListener('enemy-entered', this.onEnemyEntered.bind(this));
      this.el.addEventListener('killed', this.onKilled.bind(this));
    },
    setModel: function(modelPath){
      this.mesh.setAttribute("gltf-model", modelPath + "scene.gltf");
      console.log("[WVRTD-Goal]", "Castle degrading to", modelPath);
    },
    onEnemyEntered: function(data){
      NAF.connection.broadcastDataGuaranteed("goalHitNetwork", {type : "broadcast", gameState : this.gameState});
      this.el.emit("hit", data.detail);
    },
    onHit: function(){
      console.log("[WVRTD-Goal]", "============I WAS HIT!!!============");

      if (this.currentLife < 6) {
        this.setModel("public/assets/models/castle_lvl1/");
      }
      else if (this.currentLife < 3) {
        this.life.setAttribute("color", "red")
        this.setModel("public/assets/models/castle_lvl2/");
      }
      else if (this.currentLife < 1) {
        this.life.setAttribute("color", "red")
        this.setModel("public/assets/models/castle_lvl3/");
      }
    },
    onKilled: function(){
      document.querySelector("[wvrtd-enemy-wave]").emit("goal-destroyed");
    },
    onGoalHitNetwork: function(senderID, msg, data){
      this.onHit();
    }
  });

})();


text:
"use strict";

var buildComprehension = require("../../helpers/build-comprehension");
var traverse           = require("../../../traverse");
var util               = require("../../../util");
var t                  = require("../../../types");

exports.experimental = true;

exports.ComprehensionExpression = function (node, parent, scope, context, file) {
  var callback = array;
  if (node.generator) callback = generator;
  return callback(node, parent, scope, file);
};

var generator = function (node) {
  var body = [];
  var container = t.functionExpression(null, [], t.blockStatement(body), true);
  container._aliasFunction = true;

  body.push(buildComprehension(node, function () {
    return t.expressionStatement(t.yieldExpression(node.body));
  }));

  return t.callExpression(container, []);
};

var array = function (node, parent, scope, file) {
  var uid = scope.generateUidBasedOnNode(parent, file);

  var container = util.template("array-comprehension-container", {
    KEY: uid
  });
  container.callee._aliasFunction = true;

  var block = container.callee.body;
  var body  = block.body;

  if (traverse.hasType(node, scope, "YieldExpression", t.FUNCTION_TYPES)) {
    container.callee.generator = true;
    container = t.yieldExpression(container, true);
  }

  var returnStatement = body.pop();

  body.push(buildComprehension(node, function () {
    return util.template("array-push", {
      STATEMENT: node.body,
      KEY:       uid
    }, true);
  }));
  body.push(returnStatement);

  return container;
};


text:
cwd=`dirname $0`
. $cwd/common.sh

echo
echo "--------------------------------------------------------------------------------"
echo "This step will set up the u-boot variables for booting the EVM."

ipdefault=`ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1 }'`
platform=`grep PLATFORM= $cwd/../Rules.make | cut -d= -f2`
prompt="EVM >"

echo "Autodetected the following ip address of your host, correct it if necessary"
read -p "[ $ipdefault ] " ip
echo

if [ ! -n "$ip" ]; then
    ip=$ipdefault
fi

if [ -f $cwd/../.targetfs ]; then
    rootpath=`cat $cwd/../.targetfs`
else
    echo "Where is your target filesystem extracted?"
    read -p "[ ${HOME}/targetfs ]" rootpath

    if [ ! -n "$rootpath" ]; then
        rootpath="${HOME}/targetfs"
    fi
    echo
fi

uimagesrc=`ls -1 $cwd/../psp/prebuilt-images/uImage*.bin`
uimagedefault=`basename $uimagesrc`

baseargs="console=ttyS0,115200n8 rw mem=59M"
videoargs1="video=davincifb:vid0=OFF:vid1=OFF:osd0=720x576x16,4050K"
videoargs2="dm365_imp.oper_mode=0 davinci_capture.device_type=4"
videoargs3="davinci_display.cont2_bufsize=6291456"
videoargs4="vpfe_capture.cont_bufoffset=6291456"
videoargs5="vpfe_capture.cont_bufsize=6291456"
videoargs6="davinci_enc_mngr.ch0_output=COMPONENT"
videoargs7="davinci_enc_mngr.ch0_mode=480P-60"
videoargs="$videoargs1 $videoargs2 $videoargs3 $videoargs4 $videoargs5 $videoargs6 $videoargs7"
fssdargs="root=/dev/mmcblk0p2 rootwait"
fsnfsargs="root=/dev/nfs nfsroot=$ip:$rootpath"

#echo "Select UBL location:"
#echo " 1: flash"
#echo " 2: SD card"
#echo
#read -p "[ 1 ] " ubl

#if [ ! -n "$ubl" ]; then
#    ubl="1"
#fi

echo "Select Linux kernel location:"
echo " 1: TFTP"
echo " 2: SD card"
echo
read -p "[ 1 ] " kernel

if [ ! -n "$kernel" ]; then
    kernel="1"
fi

echo
echo "Select root file system location:"
echo " 1: NFS"
echo " 2: SD card"
echo
read -p "[ 1 ] " fs

if [ ! -n "$fs" ]; then
    fs="1"
fi

if [ "$kernel" -eq "1" ]; then
    echo
    echo "Available kernel images in /tftproot:"
    for file in /tftpboot/*; do
        basefile=`basename $file`
        echo "    $basefile"
    done
    echo
    echo "Which kernel image do you want to boot from TFTP?"
    read -p "[ $uimagedefault ] " uimage

    if [ ! -n "$uimage" ]; then
        uimage=$uimagedefault
    fi

    bootcmd="setenv bootcmd 'dhcp;setenv serverip $ip;tftpboot;bootm'"
    serverip="setenv serverip $ip"
    bootfile="setenv bootfile $uimage"

    if [ "$fs" -eq "1" ]; then
        bootargs="setenv bootargs $baseargs $videoargs $fsnfsargs ip=dhcp"
        cfg="uimage-tftp_fs-nfs"
    else
        bootargs="setenv bootargs $baseargs $videoargs $fssdargs ip=off"
        cfg="uimage-tftp_fs-sd"
    fi
else
    if [ "$fs" -eq "1" ]; then
        bootargs="setenv bootargs $baseargs $videoargs $fsnfsargs ip=dhcp"
        bootcmd="setenv bootcmd 'bootm 0x80700000'"
        cfg="uimage-sd_fs-nfs"
    else
        bootargs="setenv bootargs $baseargs $videoargs $fssdargs ip=off"
        bootcmd="setenv bootcmd 'bootm 0x80700000'"
        cfg="uimage-sd_fs-sd"
    fi
fi

echo
echo "Resulting u-boot variable settings:"
echo
echo "setenv bootdelay 4"
echo "setenv baudrate 115200"
echo $bootargs
echo $bootcmd

if [ -n "$serverip" ]; then
    echo "setenv autoload no"
    echo $serverip
fi

if [ -n "$bootfile" ]; then
    echo $bootfile
fi
echo "--------------------------------------------------------------------------------"

do_expect() {
    echo "expect {" >> $3
    check_status
    echo "    $1" >> $3
    check_status
    echo "}" >> $3
    check_status
    echo $2 >> $3
    check_status
    echo >> $3
}

echo
echo "--------------------------------------------------------------------------------"
echo "Would you like to create a minicom script with the above parameters (y/n)?"
read -p "[ y ] " minicom
echo

if [ ! -n "$minicom" ]; then
    minicom="y"
fi

if [ "$minicom" == "y" ]; then
    minicomfile=setup_$platform_$cfg.minicom
    minicomfilepath=$cwd/../$minicomfile

    if [ -f $minicomfilepath ]; then
        echo "Moving existing $minicomfile to $minicomfile.old"
        mv $minicomfilepath $minicomfilepath.old
        check_status
    fi

    timeout=300
    echo "timeout $timeout" >> $minicomfilepath
    echo "verbose on" >> $minicomfilepath
    echo >> $minicomfilepath
#if [ "$ubl" -eq "2" ]; then
#    do_expect "\"\ > \"" "send \"1\"" $minicomfilepath
#fi
    do_expect "\"stop autoboot:\"" "send \"\"" $minicomfilepath
    do_expect "\"$prompt\"" "send \"setenv bootdelay 4\"" $minicomfilepath
    do_expect "\"$prompt\"" "send \"setenv baudrate 115200\"" $minicomfilepath
    do_expect "\"ENTER ...\"" "send \"\"" $minicomfilepath
    do_expect "\"$prompt\"" "send \"setenv oldbootargs \$\{bootargs\}\"" $minicomfilepath
    do_expect "\"$prompt\"" "send \"setenv bootargs $baseargs \c\"" $minicomfilepath
    echo "send \"$videoargs1 \c\"" >> $minicomfilepath
    echo "send \"$videoargs2 \c\"" >> $minicomfilepath
    echo "send \"$videoargs3 \c\"" >> $minicomfilepath
    echo "send \"$videoargs4 \c\"" >> $minicomfilepath
    echo "send \"$videoargs5 \c\"" >> $minicomfilepath
    echo "send \"$videoargs6 \c\"" >> $minicomfilepath
    echo "send \"$videoargs7 \c\"" >> $minicomfilepath
    if [ "$fs" -eq "1" ]; then
        echo "send \"$fsnfsargs \c\"" >> $minicomfilepath
        echo "send \"ip=dhcp\"" >> $minicomfilepath
    else
        echo "send \"$fssdargs \c\"" >> $minicomfilepath
        echo "send \"ip=off\"" >> $minicomfilepath
    fi
    if [ "$kernel" -eq "1" ]; then
        do_expect "\"$prompt\"" "send \"setenv autoload no\"" $minicomfilepath
        do_expect "\"$prompt\"" "send \"setenv oldserverip \$\{serverip\}\"" $minicomfilepath
        do_expect "\"$prompt\"" "send \"$serverip\"" $minicomfilepath
        do_expect "\"$prompt\"" "send \"setenv oldbootfile \$\{bootfile\}\"" $minicomfilepath
        do_expect "\"$prompt\"" "send \"$bootfile\"" $minicomfilepath
    fi
    do_expect "\"$prompt\"" "send \"setenv oldbootcmd \$\{bootcmd\}\"" $minicomfilepath
    do_expect "\"$prompt\"" "send \"$bootcmd\"" $minicomfilepath
    do_expect "\"$prompt\"" "send \"saveenv\"" $minicomfilepath
    do_expect "\"$prompt\"" "! killall -s SIGHUP minicom" $minicomfilepath

    echo "Successfully wrote $minicomfile"
    echo
    echo "Would you like to run the setup script now (y/n)? This requires you to connect"
    echo "the RS-232 cable between your host and EVM as well as your ethernet cable as"
    echo "described in the Quick Start Guide. Once answering 'y' on the prompt below"
    echo "you will have $timeout seconds to connect the board and power cycle it"
    echo "before the setup times out"
    echo
    echo "After successfully executing this script, your EVM will be set up. You will be "
    echo "able to connect to it by executing 'minicom -w' or if you prefer a windows host"
    echo "you can set up Tera Term as explained in the Software Developer's Guide."
    echo "If you connect minicom or Tera Term and power cycle the board Linux will boot."
    echo
    read -p "[ y ] " minicomsetup

    if [ ! -n "$minicomsetup" ]; then
        minicomsetup="y"
    fi

    if [ "$minicomsetup" == "y" ]; then
        pushd $cwd/..
        check_status
        minicom -S $minicomfile
        popd >> /dev/null
        check_status

    fi

    echo "You can manually run minicom in the future with this setup script using: minicom -S $minicomfile"
fi
echo "--------------------------------------------------------------------------------"


text:
package org.michenux.yourappidea.restaurante.pedido;

import android.content.Context;
import android.content.res.Resources;
import android.support.v4.app.FragmentActivity;
import android.support.v4.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.michenux.drodrolib.ui.navdrawer.NavigationDrawerFragment;
import org.michenux.yourappidea.R;
import org.michenux.yourappidea.home.YourAppMainActivity;
import org.michenux.yourappidea.restaurante.cardapio.CardapioItem;

import java.util.List;

/**
 * Created by alessandro.gurgel on 7/21/15.
 */
public class PedidoAdapter extends ArrayAdapter<Pair<CardapioItem, Integer>> {

    public PedidoAdapter(Context context, List<Pair<CardapioItem, Integer>> items) {
        super(context, 0, items);
    }

    @Override
    public View getView(int position, View itemView, ViewGroup parent)
    {
        final Pair<CardapioItem, Integer> item = getItem(position);

        if (itemView == null ){
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            itemView = inflater.inflate(R.layout.pedido_item_list, null);
        }

        TextView pedido =  (TextView)itemView.findViewById(R.id.text_pedido_item);

        pedido.setText(String.format("%s %s", item.second, item.first.getName()));

        TextView total = (TextView)itemView.findViewById(R.id.text_pedido_item_total);
        total.setText(String.format("R$ %.2f", item.first.getPrice() * item.second));

        final TextView totalList = (TextView )((View) parent.getParent()).findViewById(R.id.text_pedido_total);
        final com.rey.material.widget.Button confirmarButton = (com.rey.material.widget.Button)((View) parent.getParent()).findViewById(R.id.button_confirmar_pedido);

        final Resources resources = getContext().getResources();

        ImageView image = (ImageView)itemView.findViewById(R.id.image_pedido_item_delete);
        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!PedidoAbertoManager.getInstance().hasConta()) {
                    remove(item);
                    totalList.setText(PedidoAbertoManager.getInstance().getTotal());

                    if (PedidoAbertoManager.getInstance().getItems().isEmpty())
                    {
                        confirmarButton.setEnabled(false);
                        confirmarButton.setBackgroundColor(resources.getColor(R.color.disable_color));
                        confirmarButton.setTextColor(resources.getColor(R.color.secondary_text));
                    }
                }
            }
        });

        return itemView;
    }
}


text:
var url = require('url');
var querystring = require('querystring');

function urlBuilder(baseUrl) {
    var baseUrl = 'http://www.sejm.gov.pl/',
            urlSuffix = 'Sejm7.nsf/agent.xsp';

    return {
        votingStartUrl: function (NrKadencji) {
            var p = {
                symbol: 'posglos',
                NrKadencji: NrKadencji || 7
            };
            return [baseUrl, urlSuffix, '?', querystring.stringify(p)].join('');
        },
        votingDayUrl: function (IdDnia, NrPosiedzenia, NrKadencji) {
            var p = {
                symbol: 'listaglos',
                IdDnia: IdDnia,
                NrPosiedzenia: NrPosiedzenia,
                NrKadencji: NrKadencji || 7
            };
            return [baseUrl, urlSuffix, '?', querystring.stringify(p)].join('');
        },
        votingSingleUrl: function (NrPosiedzenia, NrGlosowania) {
            var p = {
                symbol: 'glosowania',
                NrKadencji: 7,
                NrPosiedzenia: NrPosiedzenia,
                NrGlosowania: NrGlosowania
            };
            return [baseUrl, urlSuffix, '?', querystring.stringify(p)].join('');

        }
    };
}

module.exports = new urlBuilder();


text:
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Language Lines
    |--------------------------------------------------------------------------
    |
    | The following language lines are used during authentication for various
    | messages that we need to display to the user. You are free to modify
    | these language lines according to your application's requirements.
    |
    */

    'failed'   => 'اطلاعات ورود صحیح نمی‌باشد.',
    'throttle' => 'تعداد دفعات تلاش برای ورود از حد مجاز بیشتر است. لطفا پس از  :seconds ثانیه مجددا تلاش فرمایید.',

];


text:
<?php
namespace DjThossi\SmokeTestingPhp\Test\Example;

use DjThossi\SmokeTestingPhp\Collection\UrlCollection;
use DjThossi\SmokeTestingPhp\Options\SmokeTestOptions;
use DjThossi\SmokeTestingPhp\Result\Result;
use DjThossi\SmokeTestingPhp\SmokeTestTrait;
use DjThossi\SmokeTestingPhp\ValueObject\BasicAuth;
use DjThossi\SmokeTestingPhp\ValueObject\BodyLength;
use DjThossi\SmokeTestingPhp\ValueObject\Concurrency;
use DjThossi\SmokeTestingPhp\ValueObject\FollowRedirect;
use DjThossi\SmokeTestingPhp\ValueObject\Header;
use DjThossi\SmokeTestingPhp\ValueObject\HeaderKey;
use DjThossi\SmokeTestingPhp\ValueObject\RequestTimeout;
use DjThossi\SmokeTestingPhp\ValueObject\TimeToFirstByte;
use PHPUnit_Framework_TestCase;

class FileExampleTest extends PHPUnit_Framework_TestCase
{
    use SmokeTestTrait;

    /**
     * @dataProvider myDataProvider
     *
     * @param Result $result
     */
    public function testExample(Result $result)
    {
        $this->assertSuccess($result);
        $this->assertTimeToFirstByteBelow(new TimeToFirstByte(2000), $result);
        $this->assertBodyNotEmpty($result);
        $this->assertHasHeaderKey(new HeaderKey('Status-Line'), $result);
        $this->assertHasHeader(Header::fromPrimitives('Status-Line', 'HTTP/1.1 200 OK'), $result);
    }

    /**
     * @return array
     */
    public function myDataProvider()
    {
        $options = new SmokeTestOptions(
            UrlCollection::fromFile(__DIR__ . '/data/urls.txt'),
            new RequestTimeout(2),
            new FollowRedirect(true),
            new Concurrency(10),
            new BodyLength(500),
            new BasicAuth('username', 'password')
        );

        return $this->runSmokeTests($options);
    }
}


text:
require "hashable"

module CurrencyLayer

  class ListRequest

    include Hashable

    attr_accessor :query

    def initialize(query = {})

      self.query = query

    end

  end
end


text:
var nodeExternals = require('webpack-node-externals');
var webpack = require('webpack');

module.exports = {
  target: 'node', // in order to ignore built-in modules like path, fs, etc.
  externals: nodeExternals(),
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader?plugins=rewire',
        exclude: /node_modules/
      }
    ]
  },
  plugins: [
  ],
  devtool: 'inline-source-map'
};


text:
(function() {
  var Declaration, FlexBasis, flexSpec,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  flexSpec = require('./flex-spec');

  Declaration = require('../declaration');

  FlexBasis = (function(_super) {
    __extends(FlexBasis, _super);

    function FlexBasis() {
      return FlexBasis.__super__.constructor.apply(this, arguments);
    }

    FlexBasis.names = ['flex-basis'];

    FlexBasis.prototype.normalize = function() {
      return 'flex';
    };

    FlexBasis.prototype.prefixed = function(prop, prefix) {
      var spec, _ref;
      _ref = flexSpec(prefix), spec = _ref[0], prefix = _ref[1];
      if (spec === 2012) {
        return prefix + 'flex';
      } else {
        return FlexBasis.__super__.prefixed.apply(this, arguments);
      }
    };

    FlexBasis.prototype.set = function(decl, prefix) {
      var spec, _ref;
      _ref = flexSpec(prefix), spec = _ref[0], prefix = _ref[1];
      if (spec === 2012) {
        decl.prop = prefix + 'flex';
        decl.value = '0 1 ' + decl.value;
        return decl;
      } else if (spec === 'final') {
        return FlexBasis.__super__.set.apply(this, arguments);
      }
    };

    return FlexBasis;

  })(Declaration);

  module.exports = FlexBasis;

}).call(this);


text:
import cl.mockito.sample.User;
import cl.mockito.sample.UserDao;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ChangePasswordTest {

    private UserDao userDao;

    @Before
    public void init(){

        userDao = mock(UserDao.class);

    }

    @Test
    public void testFindUserByName(){

        User user = new User("carlos", "12345");
        when(userDao.findByName("carlos")).thenReturn(user);

        String newPassword = "646383";
        user.changePassword(newPassword);

        assertTrue(user.checkPassword(newPassword));

    }

    @Test
    public void testFindAllUsers(){

        List<User> users = new ArrayList<User>();
        User user;

        for(int i=0; i<5;i++){
            user = new User("nombre"+i, "1234"+i);
            users.add(user);
        }

        when(userDao.getAll()).thenReturn(users);

        assertEquals(userDao.getAll().size(),5);

    }

    @Test
    public void test(){
        boolean isOk = true;
        when(userDao.findByName("")).thenThrow(new IllegalArgumentException());

        try{
            userDao.findByName("");
        }catch (IllegalArgumentException ex){
            isOk = false;
            assertTrue(true);
        }

        if(isOk){
            fail();
        }
    }

}


text:
#include <linux/input.h>
#include <linux/cdev.h>
#include <linux/hrtimer.h>
#include "si_fw_macros.h"
#include "si_infoframe.h"
#include "si_edid.h"
#include "si_mhl_defs.h"
#include "si_mhl2_edid_3d_api.h"
#include "si_mhl_tx_hw_drv_api.h"
#ifdef MEDIA_DATA_TUNNEL_SUPPORT
#include "si_mdt_inputdev.h"
#endif
#include "mhl_linux_tx.h"
#include "platform.h"
#include "mhl_rbp_inputdev.h"

enum rbp_state_e {
	ph0_idle,
	ph3_press_and_hold_button,
	ph8_hold_mode,
	num_rbp_states
};

static char *state_strings[num_rbp_states] = {
	"idle",
	"press_and_hold_button",
	"hold_mode"
};

enum rbp_event_e {
	rbp_normal_button_press,
	rbp_normal_button_press_same,
	rbp_normal_button_release,
	rbp_normal_button_release_same,
	rbp_press_and_hold_button_press,
	rbp_press_and_hold_button_press_same,
	rbp_press_and_hold_button_release,
	rbp_press_and_hold_button_release_same,
	rbp_T_hold_maintain_expired,
	rbp_T_press_mode_expired,
	num_rbp_events
};

static char *event_strings[num_rbp_events] = {
	"normal_button_press",
	"normal_button_press_same",
	"normal_button_release",
	"normal_button_release_same",
	"press_and_hold_button_press",
	"press_and_hold_button_press_same",
	"press_and_hold_button_release",
	"press_and_hold_button_release_same",
	"rbp_T_hold_maintain_expired",
	"rbp_T_press_mode_expired"
};

enum rbp_state_e current_rbp_state = ph0_idle;
uint8_t rbp_previous_button = 0, rbp_current_button = 0;

static int rbp_trigger_button_action(struct mhl_dev_context *dev_context,
				     uint8_t index, bool press_release)
{
	int status = -EINVAL;

	if (dev_context->rbp_input_dev) {
		input_report_key(dev_context->rbp_input_dev, index,
				 press_release);
		input_sync(dev_context->rbp_input_dev);
		status = 0;
	}
	return status;
}

static int handle_rbp_event(struct mhl_dev_context *dev_context,
	uint8_t current_button, uint8_t prev_button, enum rbp_event_e event)
{
	int status = 0;
	uint8_t current_index = current_button & MHL_RBP_BUTTON_ID_MASK;
	uint8_t prev_index = prev_button & MHL_RBP_BUTTON_ID_MASK;

	MHL_TX_DBG_ERR("received 0x%02x: %s(%d) in state: %s(%d)\n",
		       current_button, event_strings[event], event,
		       state_strings[current_rbp_state], current_rbp_state);
	/* now process the event according to the current state */
	switch (current_rbp_state) {
	case ph0_idle:
		switch (event) {
		case rbp_normal_button_press:
		case rbp_normal_button_press_same:
			status =
			    rbp_trigger_button_action(dev_context,
						      current_index, 1);
			/* no update for current_rbp_state */
			break;
		case rbp_normal_button_release:
		case rbp_normal_button_release_same:
			status =
			    rbp_trigger_button_action(dev_context,
						      current_index, 0);
			/* no update for current_rbp_state */
			break;
		case rbp_press_and_hold_button_press:
		case rbp_press_and_hold_button_press_same:
			mhl_tx_start_timer(dev_context,
					   dev_context->timer_T_press_mode,
					   T_PRESS_MODE);
			current_rbp_state = ph3_press_and_hold_button;
			break;

		case rbp_press_and_hold_button_release:
		case rbp_press_and_hold_button_release_same:
			MHL_TX_DBG_ERR("unexpected %s(%d) in state: %s(%d)\n",
				       event_strings[event], event,
				       state_strings[current_rbp_state],
				       current_rbp_state);
			break;
		default:
			MHL_TX_DBG_ERR("unexpected event: %d in state: %d\n",
				       event, current_rbp_state);
			/* no update for current_rbp_state */
			status = -EINVAL;
		}
		break;
	case ph3_press_and_hold_button:
		switch (event) {
		case rbp_normal_button_press:
		case rbp_normal_button_press_same:
			mhl_tx_stop_timer(dev_context,
					  dev_context->timer_T_press_mode);
			rbp_trigger_button_action(dev_context, prev_index, 0);
			/* OK to overwrite status */
			status =
			    rbp_trigger_button_action(dev_context,
						      current_index, 1);
			current_rbp_state = ph0_idle;
			break;
		case rbp_normal_button_release:
		case rbp_normal_button_release_same:
			mhl_tx_stop_timer(dev_context,
					  dev_context->timer_T_press_mode);
			rbp_trigger_button_action(dev_context, prev_index, 0);
			rbp_trigger_button_action(dev_context, current_index,
						  1);
			status =
			    rbp_trigger_button_action(dev_context,
						      current_index, 0);
			current_rbp_state = ph0_idle;
			break;
		case rbp_press_and_hold_button_press:
			mhl_tx_start_timer(dev_context,
					   dev_context->timer_T_press_mode,
					   T_PRESS_MODE);
			status =
			    rbp_trigger_button_action(dev_context, prev_index,
						      1);
			/* no update for current_rbp_state */
			break;
		case rbp_press_and_hold_button_press_same:
			mhl_tx_stop_timer(dev_context,
					  dev_context->timer_T_press_mode);
			mhl_tx_start_timer(dev_context,
					   dev_context->timer_T_hold_maintain,
					   T_HOLD_MAINTAIN);
			status =
			    rbp_trigger_button_action(dev_context, prev_index,
						      1);
			current_rbp_state = ph8_hold_mode;
			break;
		case rbp_press_and_hold_button_release:
		case rbp_press_and_hold_button_release_same:
			mhl_tx_stop_timer(dev_context,
					  dev_context->timer_T_press_mode);
			status =
			    rbp_trigger_button_action(dev_context, prev_index,
						      0);
			current_rbp_state = ph0_idle;
			break;
		case rbp_T_press_mode_expired:
			mhl_tx_start_timer(dev_context,
					   dev_context->timer_T_hold_maintain,
					   T_HOLD_MAINTAIN);
			status =
			    rbp_trigger_button_action(dev_context, prev_index,
						      0);
			current_rbp_state = ph8_hold_mode;
			break;
		default:
			MHL_TX_DBG_ERR("unexpected event: %d in state: %d\n",
				       event, current_rbp_state);
			/* no update for current_rbp_state */
			status = -EINVAL;
		}
		break;
	case ph8_hold_mode:
		switch (event) {
		case rbp_normal_button_press:
		case rbp_normal_button_press_same:
			mhl_tx_stop_timer(dev_context,
					  dev_context->timer_T_hold_maintain);
			rbp_trigger_button_action(dev_context, prev_index, 0);
			status =
			    rbp_trigger_button_action(dev_context,
						      current_index, 1);
			current_rbp_state = ph0_idle;
			break;
		case rbp_normal_button_release:
		case rbp_normal_button_release_same:
			mhl_tx_stop_timer(dev_context,
					  dev_context->timer_T_hold_maintain);
			rbp_trigger_button_action(dev_context, prev_index, 0);
			rbp_trigger_button_action(dev_context, current_index,
						  1);
			status =
			    rbp_trigger_button_action(dev_context,
						      current_index, 0);
			current_rbp_state = ph0_idle;
			break;
		case rbp_press_and_hold_button_press:
			mhl_tx_stop_timer(dev_context,
					  dev_context->timer_T_hold_maintain);
			mhl_tx_start_timer(dev_context,
					   dev_context->timer_T_press_mode,
					   T_PRESS_MODE);
			status =
			    rbp_trigger_button_action(dev_context, prev_index,
						      1);
			current_rbp_state = ph3_press_and_hold_button;
			break;
		case rbp_press_and_hold_button_press_same:
			mhl_tx_start_timer(dev_context,
					   dev_context->timer_T_hold_maintain,
					   T_HOLD_MAINTAIN);
			status =
			    rbp_trigger_button_action(dev_context, prev_index,
						      1);
			/* no update for current_rbp_state */
			break;
		case rbp_press_and_hold_button_release:
			mhl_tx_stop_timer(dev_context,
					  dev_context->timer_T_hold_maintain);
			rbp_trigger_button_action(dev_context, prev_index, 0);
			rbp_trigger_button_action(dev_context, current_index,
						  1);
			status =
			    rbp_trigger_button_action(dev_context,
						      current_index, 0);
			current_rbp_state = ph0_idle;
			break;
		case rbp_press_and_hold_button_release_same:
			mhl_tx_stop_timer(dev_context,
					  dev_context->timer_T_hold_maintain);
			status =
			    rbp_trigger_button_action(dev_context, prev_index,
						      0);
			current_rbp_state = ph0_idle;
			break;
		case rbp_T_hold_maintain_expired:
			status =
			    rbp_trigger_button_action(dev_context, prev_index,
						      0);
			current_rbp_state = ph0_idle;
			break;
		default:
			MHL_TX_DBG_ERR("unexpected event: %d in state: %d\n",
				       event, current_rbp_state);
			/* no update for current_rbp_state */
			status = -EINVAL;
		}
		break;
	default:
		MHL_TX_DBG_ERR("irrational state value:%d\n",
			current_rbp_state);
	}
	return status;
}

int generate_rbp_input_event(struct mhl_dev_context *dev_context,
	uint8_t rbp_buttoncode)
{
	/*
	   Since, in MHL, bit 7 == 1 indicates button release,
	   and, in Linux, zero means button release,
	   we use XOR (^) to invert the sense.
	 */
	enum rbp_event_e event;
	int mhl_button_press;
	int status = -EINVAL;
	int index = rbp_buttoncode & MHL_RBP_BUTTON_ID_MASK;

	switch (index) {
	case RBP_CALL_ANSWER:
	case RBP_CALL_END:
	case RBP_CALL_TOGGLE:
	case RBP_CALL_MUTE:
	case RBP_CALL_DECLINE:
	case RBP_OCTOTHORPE:
	case RBP_ASTERISK:
	case RBP_ROTATE_CLKWISE:
	case RBP_ROTATE_COUNTERCLKWISE:
	case RBP_SCREEN_PAGE_NEXT:
	case RBP_SCREEN_PAGE_PREV:
	case RBP_SCREEN_PAGE_UP:
	case RBP_SCREEN_PAGE_DN:
	case RBP_SCREEN_PAGE_LEFT:
	case RBP_SCREEN_PAGE_RIGHT:
		break;
	default:
		return 1;
	}

	mhl_button_press =
		(rbp_buttoncode & MHL_RBP_BUTTON_RELEASED_MASK) ? 0 : 1;

	if (mhl_button_press) {
		if (index == rbp_previous_button)
			event = rbp_press_and_hold_button_press_same;
		else
			event = rbp_press_and_hold_button_press;
	} else {
		if (index == rbp_previous_button)
			event = rbp_press_and_hold_button_release_same;
		else
			event = rbp_press_and_hold_button_release;
	}

	status = handle_rbp_event(dev_context, rbp_buttoncode,
		rbp_current_button, event);

	rbp_previous_button = rbp_current_button;
	rbp_current_button = rbp_buttoncode;

	return status;
}


text:
import numpy
import six

from chainer import backend
from chainer.backends import cuda
from chainer.dataset import convert
from chainer.dataset import iterator as iterator_module
from chainer.training import _updater

class StandardUpdater(_updater.Updater):

    """Standard implementation of Updater.

    This is the standard implementation of :class:`~chainer.training.Updater`.
    It accepts one or more training datasets and one or more optimizers.
    The default update routine assumes that there is only one training dataset
    and one optimizer. Users can override this update routine by inheriting
    this class and overriding the :meth:`update_core` method. Each batch is
    converted to input arrays by :func:`chainer.dataset.concat_examples` by
    default, which can also be manually set by ``converter`` argument.

    Args:
        iterator: Dataset iterator for the training dataset. It can also be a
            dictionary that maps strings to iterators.
            If this is just an iterator, then the
            iterator is registered by the name ``'main'``.
        optimizer: Optimizer to update parameters. It can also be a dictionary
            that maps strings to optimizers.
            If this is just an optimizer, then the optimizer is
            registered by the name ``'main'``.
        converter: Converter function to build input arrays. Each batch
            extracted by the main iterator and the ``device`` option are passed
            to this function. :func:`chainer.dataset.concat_examples` is used
            by default.
        device: Device to which the training data is sent. Negative value
            indicates the host memory (CPU).
        loss_func: Loss function. The target link of the main optimizer is used
            by default.
        loss_scale (float): Loss scaling factor. Loss scaling is a usefull
            technique to mitigate vanishing gradient issue that tends to happen
            when low precision data type like float16 is used during training.
            If you set loss scaling factor, gradients of loss values are to be
            multiplied by the factor before backprop starts. The factor is
            propagated to whole gradients in a computational graph along the
            backprop. The gradients of parameters are divided by the factor
            just before the parameters are to be updated.
        auto_new_epoch (bool): If ``True``,
            :meth:`~chainer.Optimizer.new_epoch` of the main optimizer is
            automatically called when the ``is_new_epoch`` attribute of the
            main iterator is ``True``.

    Attributes:
        converter: Converter function.
        loss_func: Loss function. If it is ``None``, the target link of the
                   main optimizer is used instead.
        device: Device to which the training data is sent.
        iteration: Current number of completed updates.
        auto_new_epoch: If ``True``, :meth:`~chainer.Optimizer.new_epoch` is
            automatically called by :meth:`update_core`. In this case, the
            :attr:`~chainer.Optimizer.use_auto_new_epoch` attribute of each
            optimizer is also set to ``True``. If :meth:`update_core` is
            overridden, the implementation should correctly call
            :meth:`~chainer.Optimizer.new_epoch` of each optimizer.

    """

    def __init__(self, iterator, optimizer, converter=convert.concat_examples,
                 device=None, loss_func=None, loss_scale=None,
                 auto_new_epoch=True):
        if device is not None:
            device = backend._get_device_compat(device)

        if isinstance(iterator, iterator_module.Iterator):
            iterator = {'main': iterator}
        self._iterators = iterator

        if not isinstance(optimizer, dict):
            optimizer = {'main': optimizer}
        self._optimizers = optimizer

        if device is not None:
            for optimizer in six.itervalues(self._optimizers):
                optimizer.target._to_device(
                    device, skip_between_cupy_devices=True)

        self.converter = converter
        self.loss_func = loss_func
        self.device = device
        self.iteration = 0

        self.loss_scale = loss_scale
        if loss_scale is not None:
            for optimizer in six.itervalues(self._optimizers):
                optimizer.set_loss_scale(loss_scale)

        self.auto_new_epoch = auto_new_epoch
        if auto_new_epoch:
            for o in six.itervalues(self._optimizers):
                o.use_auto_new_epoch = True

    @property
    def epoch(self):
        return self._iterators['main'].epoch

    @property
    def epoch_detail(self):
        return self._iterators['main'].epoch_detail

    @property
    def previous_epoch_detail(self):
        return self._iterators['main'].previous_epoch_detail

    @property
    def is_new_epoch(self):
        return self._iterators['main'].is_new_epoch

    def finalize(self):
        """Finalizes the updater object.

        This method calls the `finalize` method of each iterator that
        this updater has.
        It is called at the end of training loops.

        """
        for iterator in six.itervalues(self._iterators):
            iterator.finalize()

    def get_optimizer(self, name):
        """Gets the optimizer of given name.

        Args:
            name (str): Name of the optimizer.

        Returns:
            ~chainer.Optimizer: Corresponding optimizer.

        """
        return self._optimizers[name]

    def get_all_optimizers(self):
        """Gets a dictionary of all optimizers for this updater.

        Returns:
            dict: Dictionary that maps names to optimizers.

        """
        return dict(self._optimizers)

    def get_iterator(self, name):
        """Gets the dataset iterator of given name.

        Args:
            name (str): Name of the dataset iterator.

        Returns:
            ~chainer.dataset.Iterator: Corresponding dataset iterator.

        """
        return self._iterators[name]

    def update(self):
        """Updates the parameters of the target model.

        This method implements an update formula for the training task,
        including data loading, forward/backward computations, and actual
        updates of parameters.

        This method is called once at each iteration of the training loop.

        """
        self.update_core()
        self.iteration += 1

    def _call_converter(self, batch, device):
        # TODO(niboshi): This is a temporary workaround to keep backward
        # compatibility about user-defined custom converters. Existing
        # converters expect int values as the `device` argument, so they
        # can't handle ChainerX devices. We should either break backward
        # compatibility at some time or introduce a sparate API.
        converter = self.converter
        if converter is convert.concat_examples:
            return converter(batch, device)
        else:
            if device is None:
                return converter(batch, None)
            if device.xp is numpy:
                return converter(batch, -1)
            if device.xp is cuda.cupy:
                return converter(batch, device.device.id)
            raise NotImplementedError(
                'Currently only `concat_examples` supports ChainerX.')

    def update_core(self):
        iterator = self._iterators['main']
        batch = iterator.next()
        in_arrays = self._call_converter(batch, self.device)

        optimizer = self._optimizers['main']
        loss_func = self.loss_func or optimizer.target

        if isinstance(in_arrays, tuple):
            optimizer.update(loss_func, *in_arrays)
        elif isinstance(in_arrays, dict):
            optimizer.update(loss_func, **in_arrays)
        else:
            optimizer.update(loss_func, in_arrays)

        if self.auto_new_epoch and iterator.is_new_epoch:
            optimizer.new_epoch(auto=True)

    def serialize(self, serializer):
        """Serializes the current state of the updater object."""
        for name, iterator in six.iteritems(self._iterators):
            iterator.serialize(serializer['iterator:' + name])

        for name, optimizer in six.iteritems(self._optimizers):
            optimizer.serialize(serializer['optimizer:' + name])
            optimizer.target.serialize(serializer['model:' + name])

        self.iteration = serializer('iteration', self.iteration)


text:
This project is a standard ERC20 token and distribution constructed for LOOMIA and their TILE token.
There is no crowdsale as the sale was conducted privately off chain.
The `TileDistrubtion` smart contract is deployed to the mainnet which does the following:
* creates the TILE token contract
* creates the Token Vesting contract
* creates the Token Timelock contract
* provide functions, via onlyOwner, to distribute tokens to valid ETH addresses
This contract does not accept payment of any kind, and will reject any payments made to the fallback function.

## Requirements
The server side scripts requires NodeJS 8.
Go to [NodeJS](https://nodejs.org/en/download/) and install the appropriate version for your system.

Yarn is required to be installed globally to minimize the risk of dependency issues.
Go to [Yarn](https://yarnpkg.com/en/docs/install) and choose the right installer for your system.

Depending on your system the following components might be already available or have to be provided manually:
* Python 2.7
* make (on Ubuntu this is part of the commonly installed `sudo apt-get install build-essential`)
* On OSX the build tools included in XCode are required

## General
Before running the provided scripts, you have to initialize your current terminal via `source ./tools/initShell.sh` for every terminal in use. This will add the current directory to the system PATH variables and must be repeated for time you start a new terminal window from project base directory.

For Windows, use `./tools/initShell.ps1`.

__Every command must be executed from within the projects base directory!__

## Setup
Open your terminal and change into your project base directory. From here, install all needed dependencies.
```
cd <project base directory>
source ./tools/initShell.sh
yarn install
```
This will install all required dependecies in the directory _node_modules_.

For Windows

Open up Powershell and change into your project base directory. From here, install all needed dependencies.

```
cd <project base directory>
.\tools\initShell.ps1
yarn install
```
Note: Windows users may run into an error:
```
.\tools\initShell.ps1 is not digitally signed. You cannot run this script on the current system.
For more information about running scripts and setting execution policy, see about_Execution_Policies at
https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1 + .\tools\initShell.ps1
```
If you get this error you have to change permissions first. Run PowerShell as admin and run:

`Set-ExecutionPolicy Unrestricted `

Enter 'Y' for yes and exit. You should now be able to run the previous script.

## Compile, migrate and run unit tests
To deploy the ICO smart contracts, go into the projects root directory, and change into the truffle development console.
```
cd <project base directory>
source ./tools/initShell.sh
yarn run dev
```
For Windows users: When running you may get a pop-up asking you if you really want to open the .js file. This is an issue, but we can fix it!
Search for"Advance System Settings"
When in "Advance System Settings" click on "Enviromental Variables" under the Advanced tab.
Under System variables, look for 'PATHEXT' Edit 'PATHEXT' to remove the '.JS' from the list. You should be good to run.

Now you can compile, migrate and run tests.
```
# Compile contract
compile

# Migrate contract
migrate

# Test the contract
test
```
__The development console will automatically start it's own TestRPC server for you!__

__Because the test consumes a lot of ETH, please restart the development console between each test!__

## Infura - Rinkeby Deployment Setup
Depends on the `.secrets.json` file that must be manually created when initally created.
This file name is added to the `.gitignore` file so it never get's pushed to GitHub as it contains your mnemonic key!

.secrect.json file:
```
{
    "ropsten": {
        "host": "https://ropsten.infura.io/<INFURA KEY>",
        "mnemonic": "<MNEMONIC KEY>"
    },
    "rinkeby": {
        "host": "https://rinkeby.infura.io/<INFURA KEY>",
        "mnemonic": "<MNEMONIC KEY>"
    },
    "kovan": {
        "host": "https://kovan.infura.io/<INFURA KEY>",
        "mnemonic": "<MNEMONIC KEY>"
    }
}
```


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Garbini</title>

  <link href="css/bootstrap.min.css" rel="stylesheet">

  <link href="css/owl.carousel.css" rel="stylesheet">
  <link href="css/owl.theme.css" rel="stylesheet">
  <link href="css/owl.transitions.css" rel="stylesheet">

  <link href="css/style.css" rel="stylesheet">
  <link href="css/config.css" rel="stylesheet">

            English

German

Spanish

Italian

           Cart

            3

          <button data-target=".top-nav" data-toggle="collapse" class="navbar-toggle" type="button">
            Toggle navigation

          </button>

About

Blog

Contact

LogIn / Register

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".main-nav">

          </button>

              Home

Home #1 / Slider

Home #2 / Categories

              For Woman

Subcat #1

Subcat #2

Subcat #3

Subcat #4

              For Men

Subcat #1

Subcat #2

Subcat #3

Subcat #4

              For Kids

Subcat #1

Subcat #2

Subcat #3

Subcat #4

              Accessories

Home

Account Login

About Us

In consectetur semper mauris et tincidunt. Sed rutrum posuere luctus. Curabitur fermentum massa risus, sit amet blandit dolor adipiscing a. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae.

Mauris vitae pulvinar eros. Etiam neque velit, aliquam nec lacinia at, aliquam vel quam. Aenean id quam velit, non egestas magna. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam fringilla bibendum arcu, at pretium ipsum scelerisque sed. Pellentesque commodo faucibus viverra. Sed vitae lectus nunc, non facilisis metus.

Phasellus eu aliquam mauris. Suspendisse potenti. Fusce fringilla, est in condimentum suscipit, eros justo semper lectus, eget convallis libero urna at quam. Maecenas nec aliquet tellus. Phasellus sit amet massa in ante iaculis facilisis cursus a nisi. Fusce id ligula ligula.

          Mauris vitae pulvinar eros. Etiam neque velit, aliquam nec lacinia at, aliquam vel quam. Aenean id quam velit, non egestas magna. Cum sociis natoque penatibus et magnis dis parturient montes.
          — Somebody

Our People

              Arni Marnason CEO

Mauris vitae pulvinar eros. Etiam neque velit, aliquam nec lacinia at, aliquam vel quam. Aenean id quam velit.

              Arni Marnason CEO

Mauris vitae pulvinar eros. Etiam neque velit, aliquam nec lacinia at, aliquam vel quam. Aenean id quam velit.

              Arni Marnason CEO

Mauris vitae pulvinar eros. Etiam neque velit, aliquam nec lacinia at, aliquam vel quam. Aenean id quam velit.

              Arni Marnason CEO

Mauris vitae pulvinar eros. Etiam neque velit, aliquam nec lacinia at, aliquam vel quam. Aenean id quam velit.

WORK WITH US - JOIN OUR TEAM

Want to be a part of us? We have no specified needs, but present your
ideas and yourself and we will contact you.

        See All Jobs

Our Skills

WHO WE ARE

Mauris vitae pulvinar eros. Etiam neque velit, aliquam nec lacinia at, aliquam vel quam. Aenean id quam velit, non egestas magna. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

WHAT WE DO

Mauris vitae pulvinar eros. Etiam neque velit, aliquam nec lacinia at, aliquam vel quam. Aenean id quam velit, non egestas magna. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

OUR GOAL AND IDEA

Mauris vitae pulvinar eros. Etiam neque velit, aliquam nec lacinia at, aliquam vel quam. Aenean id quam velit, non egestas magna. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

Garbini

Home

About Us

Log In / Sign Up

Checkout

My Wishlist

My Cart

What's New

Shop

Cloting

Feeding Bottles

Diaper

Infant Clothes

Educational Baby Toys

Strollers & Pams

Creams & Ointments

Info

Company

Franchisee

Partners

Contact

FAQ

Terms of Service

Privacy Policy

Newsletter

          <form action="#" id="newsletter">
            Get Our Newsletter

              <input type="text" name="newsletter-email" id="newsletter-email" placeholder="Email" class="form-control input-lg">

                <button class="btn btn-default btn-lg" type="button"></button>

          </form>

Lets Get Connected

We Accept

Free Shipping

 On orders over $50

© Copyright Garbini 2014 | All Rights Reserved | Designed by jThemes

Shopping Cart

          Reshape Panties

        1 × $12.00

          Reshape Panties

        1 × $12.00

          Reshape Panties

        1 × $12.00

Subtotal: $36.00

      View Cart
      Checkout


text:
<button class="ui-btn ui-shadow ui-corner-all ui-btn-icon-left ui-icon-alert">注意事項</button>
<div class="ui-grid-a">
<?php echo $str;?>
</div><!-- /grid-a -->


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

namespace Euler.Lib
{
    public class MaximumPathFinder
    {
        private int _index;
        private int _take = 2;
        private readonly int _lookahead;

        public MaximumPathFinder(int lookahead)
        {
            this._lookahead = lookahead;
        }

        public MaximumPathFinder()
        {
            this._lookahead = 4;
        }

        public int GetMax(int[][] triangle)
        {
            this._index = 0;
            int sum = 0;

            for (int i = 0; i < triangle.Length; i++ )
            {
                var arr = triangle[i];
                if (arr.Length == 1)
                {
                    sum += arr[0];
                }
                else
                {
                    var val = this.GetBestValue(i, triangle);
                    sum += val;
                    this._index = Array.IndexOf(arr, val);
                }
            }

            return sum;
        }

        private int GetBestValue(int current, int[][] triangle)
        {
            var index = 0;
            var best = 0;
            var candidates = triangle[current].Skip(this._index).Take(this._take).ToArray();
            var length = triangle.Length;

            for (int i = 0; i < 2; i++)
            {
                var previous = candidates[i];
                var sum = previous;

                for (int j = 0; j < this._lookahead; j++)
                {
                    if (length <= (current + j + 1)) break;

                    var value = this.GetNextValue(triangle[(current + (j+1))], Array.IndexOf(triangle[current + j], previous));
                    previous = value;
                    sum += value;
                }

                if (sum > best)
                {
                    best = sum;
                    index = i;
                }
            }

            return candidates[index];
        }

        private int GetNextValue(int[] next, int index)
        {
            return next.Skip(index).Take(2).Max();
        }
    }
}


text:
import React from 'react';
import { render, mount } from 'enzyme';
import { renderToJson } from 'enzyme-to-json';
import Drawer from '../index.web';

describe('Drawer', () => {
  it('renders correctly', () => {
    const wrapper = render(
      <Drawer
        className="my-drawer"
        style={{ minHeight: document.documentElement.clientHeight - 200 }}
        dragHandleStyle={{ display: 'none' }}
        contentStyle={{ color: '#A6A6A6', textAlign: 'center', paddingTop: 42 }}
        sidebar={sidebar content}
        position="left"
        open={false}
      >
        Click upper-left corner icon
      </Drawer>,
    );
    expect(wrapper.find('.my-drawer')).toHaveLength(1);
    expect(renderToJson(wrapper)).toMatchSnapshot();
  });

  it('check open/close state', () => {
    function onOpenChange(arg) {
      expect(arg).toBe(false);
    }
    // 注意:如果用 enzyme 的 shallow 方法、setProps 不起作用,
    // 也许是代码都是在 rc-drawer 里的缘故?(比如 Button 组件 shallow + setProps 是正常的)
    const wrapper = mount(
      <Drawer
        sidebar={sidebar content}
        position="left"
        open={false}
        onOpenChange={onOpenChange}
      >
        Click upper-left corner icon
      </Drawer>,
    );
    expect(wrapper.find('.am-drawer-open')).toHaveLength(0);
    wrapper.setProps({ open: true });
    expect(wrapper.find('.am-drawer-open')).toHaveLength(1);
    wrapper.find('.am-drawer-overlay').simulate('click');
  });
});