text:
package Lev9;
/*
Написать пять методов, которые вызывают друг друга.
Каждый метод должен возвращать имя метода, вызвавшего его, полученное с помощью StackTrace.

Требования:
1. В классе должно быть 5 методов (метод main не учитывать).
2. Каждый метод должен вызывать следующий: main вызывать method1, method1 вызывать method2 и т.д.
3. Каждый метод должен возвращать имя метода, вызвавшего его.
4. Для получения имени вызвавшего метода, используй метод getMethodName.

 */
public class Task0902done {
  public static void main(String[] args) throws Exception {
    method1();
    StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
 //   System.out.println(stackTrace[2]);
  }

  public static String method1() {
    method2();
    StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
    System.out.println(stackTrace[2].getMethodName());
    return stackTrace[2].getMethodName();
  }

  public static String method2() {
    method3();
    StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
    System.out.println(stackTrace[2].getMethodName());
    return stackTrace[2].getMethodName();
  }

  public static String method3() {
    method4();
    StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
    System.out.println(stackTrace[2].getMethodName());
    return stackTrace[2].getMethodName();
  }

  public static String method4() {
    method5();
    StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();

    System.out.println(stackTrace[2].getMethodName());
    return stackTrace[2].getMethodName();
  }

  public static String method5() {
    StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
    System.out.println(stackTrace[2].getMethodName());
    return stackTrace[2].getMethodName();
  }
}

redpajama_set_name: RedPajamaGithub


text:
// <file>
//     <copyright see="prj:///doc/copyright.txt"/>
//     <license see="prj:///doc/license.txt"/>
//     <owner name="David Srbecký" email="dsrbecky@gmail.com"/>
//     <version>$Revision$</version>
// </file>

using System;

namespace Debugger.Tests.TestPrograms
{
	public class MainClass
	{
		public static void Main()
		{
			GenericClass<int, string> gClass = new GenericClass<int, string>();
			gClass.Metod(1, "1!");
			gClass.GenericMethod<bool>(2, "2!");
			GenericClass<int, string>.StaticMetod(3, "3!");
			GenericClass<int, string>.StaticGenericMethod<bool>(4, "4!");

			GenericStruct<int, string> gStruct = new GenericStruct<int, string>();
			gStruct.Metod(5, "5!");
			gStruct.GenericMethod<bool>(6, "6!");
			GenericStruct<int, string>.StaticMetod(7, "7!");
			GenericStruct<int, string>.StaticGenericMethod<bool>(8, "8!");

			System.Diagnostics.Debugger.Break();
		}
	}

	public class GenericClass<V, K>
	{
		public V Prop {
			get {
				return default(V);
			}
		}

		public static V StaticProp {
			get {
				return default(V);
			}
		}

		public K Metod(V v, K k)
		{
			System.Diagnostics.Debugger.Break();
			return k;
		}

		public T GenericMethod<T>(V v, K k)
		{
			System.Diagnostics.Debugger.Break();
			return default(T);
		}

		public static K StaticMetod(V v, K k)
		{
			System.Diagnostics.Debugger.Break();
			return k;
		}

		public static T StaticGenericMethod<T>(V v, K k)
		{
			System.Diagnostics.Debugger.Break();
			return default(T);
		}
	}

	public struct GenericStruct<V, K>
	{
		public K Metod(V v, K k)
		{
			System.Diagnostics.Debugger.Break();
			return k;
		}

		public T GenericMethod<T>(V v, K k)
		{
			System.Diagnostics.Debugger.Break();
			return default(T);
		}

		public static K StaticMetod(V v, K k)
		{
			System.Diagnostics.Debugger.Break();
			return k;
		}

		public static T StaticGenericMethod<T>(V v, K k)
		{
			System.Diagnostics.Debugger.Break();
			return default(T);
		}
	}
}

#if TEST_CODE
namespace Debugger.Tests {
	public partial class DebuggerTests
	{
		[NUnit.Framework.Test]
		public void Generics()
		{
			ExpandProperties(
				"StackFrame.MethodInfo",
				"MemberInfo.DeclaringType"
			);
			StartTest("Generics.cs");

			for(int i = 0; i < 8; i++) {
				ObjectDump("SelectedStackFrame", process.SelectedStackFrame);
				ObjectDump("SelectedStackFrame-GetArguments", process.SelectedStackFrame.GetArgumentValues());
				process.Continue();
			}
			ObjectDump("Prop", process.SelectedStackFrame.GetLocalVariableValue("gClass").GetMemberValue("Prop"));
			ObjectDump("StaticProp", process.SelectedStackFrame.GetLocalVariableValue("gClass").GetMemberValue("StaticProp"));

			EndTest();
		}
	}
}
#endif

#if EXPECTED_OUTPUT
<?xml version="1.0" encoding="utf-8"?>
<DebuggerTests>
  <Test
    name="Generics.cs">
    <ProcessStarted />
    <ModuleLoaded>mscorlib.dll (No symbols)</ModuleLoaded>
    <ModuleLoaded>Generics.exe (Has symbols)</ModuleLoaded>
    <DebuggingPaused>Break Generics.cs:48,4-48,40</DebuggingPaused>
    <SelectedStackFrame>
      <StackFrame
        ArgumentCount="2"
        ChainIndex="1"
        FrameIndex="1"
        HasSymbols="True"
        IsInvalid="False"
        MethodInfo="Metod"
        NextStatement="Generics.cs:48,4-48,40">
        <MethodInfo>
          <MethodInfo
            DeclaringType="Debugger.Tests.TestPrograms.GenericClass<System.Int32,System.String>"
            FullName="Debugger.Tests.TestPrograms.GenericClass<System.Int32,System.String>.Metod"
            IsInternal="False"
            IsPrivate="False"
            IsProtected="False"
            IsPublic="True"
            IsSpecialName="False"
            IsStatic="False"
            Module="Generics.exe"
            Name="Metod"
            StepOver="False">
            <DeclaringType>
              <DebugType
                BaseType="System.Object"
                ElementType="null"
                FullName="Debugger.Tests.TestPrograms.GenericClass<System.Int32,System.String>"
                GenericArguments="{System.Int32, System.String}"
                Interfaces="{}"
                Kind="Class"
                Module="Generics.exe"
                Name="GenericClass<Int32,String>" />
            </DeclaringType>
          </MethodInfo>
        </MethodInfo>
      </StackFrame>
    </SelectedStackFrame>
    <SelectedStackFrame-GetArguments
      Capacity="4"
      Count="2">
      <Item>
        <Value
          ArrayDimensions="{Exception: Value is not an array}"
          ArrayLength="{Exception: Value is not an array}"
          ArrayRank="{Exception: Value is not an array}"
          AsString="1"
          Expression="v"
          IsInvalid="False"
          IsNull="False"
          IsReference="False"
          PrimitiveValue="1"
          Type="System.Int32" />
      </Item>
      <Item>
        <Value
          ArrayDimensions="{Exception: Value is not an array}"
          ArrayLength="{Exception: Value is not an array}"
          ArrayRank="{Exception: Value is not an array}"
          AsString="1!"
          Expression="k"
          IsInvalid="False"
          IsNull="False"
          IsReference="True"
          PrimitiveValue="1!"
          Type="System.String" />
      </Item>
    </SelectedStackFrame-GetArguments>
    <DebuggingPaused>Break Generics.cs:54,4-54,40</DebuggingPaused>
    <SelectedStackFrame>
      <StackFrame
        ArgumentCount="2"
        ChainIndex="1"
        FrameIndex="1"
        HasSymbols="True"
        IsInvalid="False"
        MethodInfo="GenericMethod"
        NextStatement="Generics.cs:54,4-54,40">
        <MethodInfo>
          <MethodInfo
            DeclaringType="Debugger.Tests.TestPrograms.GenericClass<System.Int32,System.String>"
            FullName="Debugger.Tests.TestPrograms.GenericClass<System.Int32,System.String>.GenericMethod"
            IsInternal="False"
            IsPrivate="False"
            IsProtected="False"
            IsPublic="True"
            IsSpecialName="False"
            IsStatic="False"
            Module="Generics.exe"
            Name="GenericMethod"
            StepOver="False">
            <DeclaringType>
              <DebugType
                BaseType="System.Object"
                ElementType="null"
                FullName="Debugger.Tests.TestPrograms.GenericClass<System.Int32,System.String>"
                GenericArguments="{System.Int32, System.String}"
                Interfaces="{}"
                Kind="Class"
                Module="Generics.exe"
                Name="GenericClass<Int32,String>" />
            </DeclaringType>
          </MethodInfo>
        </MethodInfo>
      </StackFrame>
    </SelectedStackFrame>
    <SelectedStackFrame-GetArguments
      Capacity="4"
      Count="2">
      <Item>
        <Value
          ArrayDimensions="{Exception: Value is not an array}"
          ArrayLength="{Exception: Value is not an array}"
          ArrayRank="{Exception: Value is not an array}"
          AsString="2"
          Expression="v"
          IsInvalid="False"
          IsNull="False"
          IsReference="False"
          PrimitiveValue="2"
          Type="System.Int32" />
      </Item>
      <Item>
        <Value
          ArrayDimensions="{Exception: Value is not an array}"
          ArrayLength="{Exception: Value is not an array}"
          ArrayRank="{Exception: Value is not an array}"
          AsString="2!"
          Expression="k"
          IsInvalid="False"
          IsNull="False"
          IsReference="True"
          PrimitiveValue="2!"
          Type="System.String" />
      </Item>
    </SelectedStackFrame-GetArguments>
    <DebuggingPaused>Break Generics.cs:60,4-60,40</DebuggingPaused>
    <SelectedStackFrame>
      <StackFrame
        ArgumentCount="2"
        ChainIndex="1"
        FrameIndex="1"
        HasSymbols="True"
        IsInvalid="False"
        MethodInfo="StaticMetod"
        NextStatement="Generics.cs:60,4-60,40">
        <MethodInfo>
          <MethodInfo
            DeclaringType="Debugger.Tests.TestPrograms.GenericClass<System.Int32,System.String>"
            FullName="Debugger.Tests.TestPrograms.GenericClass<System.Int32,System.String>.StaticMetod"
            IsInternal="False"
            IsPrivate="False"
            IsProtected="False"
            IsPublic="True"
            IsSpecialName="False"
            IsStatic="True"
            Module="Generics.exe"
            Name="StaticMetod"
            StepOver="False">
            <DeclaringType>
              <DebugType
                BaseType="System.Object"
                ElementType="null"
                FullName="Debugger.Tests.TestPrograms.GenericClass<System.Int32,System.String>"
                GenericArguments="{System.Int32, System.String}"
                Interfaces="{}"
                Kind="Class"
                Module="Generics.exe"
                Name="GenericClass<Int32,String>" />
            </DeclaringType>
          </MethodInfo>
        </MethodInfo>
      </StackFrame>
    </SelectedStackFrame>
    <SelectedStackFrame-GetArguments
      Capacity="4"
      Count="2">
      <Item>
        <Value
          ArrayDimensions="{Exception: Value is not an array}"
          ArrayLength="{Exception: Value is not an array}"
          ArrayRank="{Exception: Value is not an array}"
          AsString="3"
          Expression="v"
          IsInvalid="False"
          IsNull="False"
          IsReference="False"
          PrimitiveValue="3"
          Type="System.Int32" />
      </Item>
      <Item>
        <Value
          ArrayDimensions="{Exception: Value is not an array}"
          ArrayLength="{Exception: Value is not an array}"
          ArrayRank="{Exception: Value is not an array}"
          AsString="3!"
          Expression="k"
          IsInvalid="False"
          IsNull="False"
          IsReference="True"
          PrimitiveValue="3!"
          Type="System.String" />
      </Item>
    </SelectedStackFrame-GetArguments>
    <DebuggingPaused>Break Generics.cs:66,4-66,40</DebuggingPaused>
    <SelectedStackFrame>
      <StackFrame
        ArgumentCount="2"
        ChainIndex="1"
        FrameIndex="1"
        HasSymbols="True"
        IsInvalid="False"
        MethodInfo="StaticGenericMethod"
        NextStatement="Generics.cs:66,4-66,40">
        <MethodInfo>
          <MethodInfo
            DeclaringType="Debugger.Tests.TestPrograms.GenericClass<System.Int32,System.String>"
            FullName="Debugger.Tests.TestPrograms.GenericClass<System.Int32,System.String>.StaticGenericMethod"
            IsInternal="False"
            IsPrivate="False"
            IsProtected="False"
            IsPublic="True"
            IsSpecialName="False"
            IsStatic="True"
            Module="Generics.exe"
            Name="StaticGenericMethod"
            StepOver="False">
            <DeclaringType>
              <DebugType
                BaseType="System.Object"
                ElementType="null"
                FullName="Debugger.Tests.TestPrograms.GenericClass<System.Int32,System.String>"
                GenericArguments="{System.Int32, System.String}"
                Interfaces="{}"
                Kind="Class"
                Module="Generics.exe"
                Name="GenericClass<Int32,String>" />
            </DeclaringType>
          </MethodInfo>
        </MethodInfo>
      </StackFrame>
    </SelectedStackFrame>
    <SelectedStackFrame-GetArguments
      Capacity="4"
      Count="2">
      <Item>
        <Value
          ArrayDimensions="{Exception: Value is not an array}"
          ArrayLength="{Exception: Value is not an array}"
          ArrayRank="{Exception: Value is not an array}"
          AsString="4"
          Expression="v"
          IsInvalid="False"
          IsNull="False"
          IsReference="False"
          PrimitiveValue="4"
          Type="System.Int32" />
      </Item>
      <Item>
        <Value
          ArrayDimensions="{Exception: Value is not an array}"
          ArrayLength="{Exception: Value is not an array}"
          ArrayRank="{Exception: Value is not an array}"
          AsString="4!"
          Expression="k"
          IsInvalid="False"
          IsNull="False"
          IsReference="True"
          PrimitiveValue="4!"
          Type="System.String" />
      </Item>
    </SelectedStackFrame-GetArguments>
    <DebuggingPaused>Break Generics.cs:75,4-75,40</DebuggingPaused>
    <SelectedStackFrame>
      <StackFrame
        ArgumentCount="2"
        ChainIndex="1"
        FrameIndex="1"
        HasSymbols="True"
        IsInvalid="False"
        MethodInfo="Metod"
        NextStatement="Generics.cs:75,4-75,40">
        <MethodInfo>
          <MethodInfo
            DeclaringType="Debugger.Tests.TestPrograms.GenericStruct<System.Int32,System.String>"
            FullName="Debugger.Tests.TestPrograms.GenericStruct<System.Int32,System.String>.Metod"
            IsInternal="False"
            IsPrivate="False"
            IsProtected="False"
            IsPublic="True"
            IsSpecialName="False"
            IsStatic="False"
            Module="Generics.exe"
            Name="Metod"
            StepOver="False">
            <DeclaringType>
              <DebugType
                BaseType="System.ValueType"
                ElementType="null"
                FullName="Debugger.Tests.TestPrograms.GenericStruct<System.Int32,System.String>"
                GenericArguments="{System.Int32, System.String}"
                Interfaces="{}"
                Kind="ValueType"
                Module="Generics.exe"
                Name="GenericStruct<Int32,String>" />
            </DeclaringType>
          </MethodInfo>
        </MethodInfo>
      </StackFrame>
    </SelectedStackFrame>
    <SelectedStackFrame-GetArguments
      Capacity="4"
      Count="2">
      <Item>
        <Value
          ArrayDimensions="{Exception: Value is not an array}"
          ArrayLength="{Exception: Value is not an array}"
          ArrayRank="{Exception: Value is not an array}"
          AsString="5"
          Expression="v"
          IsInvalid="False"
          IsNull="False"
          IsReference="False"
          PrimitiveValue="5"
          Type="System.Int32" />
      </Item>
      <Item>
        <Value
          ArrayDimensions="{Exception: Value is not an array}"
          ArrayLength="{Exception: Value is not an array}"
          ArrayRank="{Exception: Value is not an array}"
          AsString="5!"
          Expression="k"
          IsInvalid="False"
          IsNull="False"
          IsReference="True"
          PrimitiveValue="5!"
          Type="System.String" />
      </Item>
    </SelectedStackFrame-GetArguments>
    <DebuggingPaused>Break Generics.cs:81,4-81,40</DebuggingPaused>
    <SelectedStackFrame>
      <StackFrame
        ArgumentCount="2"
        ChainIndex="1"
        FrameIndex="1"
        HasSymbols="True"
        IsInvalid="False"
        MethodInfo="GenericMethod"
        NextStatement="Generics.cs:81,4-81,40">
        <MethodInfo>
          <MethodInfo
            DeclaringType="Debugger.Tests.TestPrograms.GenericStruct<System.Int32,System.String>"
            FullName="Debugger.Tests.TestPrograms.GenericStruct<System.Int32,System.String>.GenericMethod"
            IsInternal="False"
            IsPrivate="False"
            IsProtected="False"
            IsPublic="True"
            IsSpecialName="False"
            IsStatic="False"
            Module="Generics.exe"
            Name="GenericMethod"
            StepOver="False">
            <DeclaringType>
              <DebugType
                BaseType="System.ValueType"
                ElementType="null"
                FullName="Debugger.Tests.TestPrograms.GenericStruct<System.Int32,System.String>"
                GenericArguments="{System.Int32, System.String}"
                Interfaces="{}"
                Kind="ValueType"
                Module="Generics.exe"
                Name="GenericStruct<Int32,String>" />
            </DeclaringType>
          </MethodInfo>
        </MethodInfo>
      </StackFrame>
    </SelectedStackFrame>
    <SelectedStackFrame-GetArguments
      Capacity="4"
      Count="2">
      <Item>
        <Value
          ArrayDimensions="{Exception: Value is not an array}"
          ArrayLength="{Exception: Value is not an array}"
          ArrayRank="{Exception: Value is not an array}"
          AsString="6"
          Expression="v"
          IsInvalid="False"
          IsNull="False"
          IsReference="False"
          PrimitiveValue="6"
          Type="System.Int32" />
      </Item>
      <Item>
        <Value
          ArrayDimensions="{Exception: Value is not an array}"
          ArrayLength="{Exception: Value is not an array}"
          ArrayRank="{Exception: Value is not an array}"
          AsString="6!"
          Expression="k"
          IsInvalid="False"
          IsNull="False"
          IsReference="True"
          PrimitiveValue="6!"
          Type="System.String" />
      </Item>
    </SelectedStackFrame-GetArguments>
    <DebuggingPaused>Break Generics.cs:87,4-87,40</DebuggingPaused>
    <SelectedStackFrame>
      <StackFrame
        ArgumentCount="2"
        ChainIndex="1"
        FrameIndex="1"
        HasSymbols="True"
        IsInvalid="False"
        MethodInfo="StaticMetod"
        NextStatement="Generics.cs:87,4-87,40">
        <MethodInfo>
          <MethodInfo
            DeclaringType="Debugger.Tests.TestPrograms.GenericStruct<System.Int32,System.String>"
            FullName="Debugger.Tests.TestPrograms.GenericStruct<System.Int32,System.String>.StaticMetod"
            IsInternal="False"
            IsPrivate="False"
            IsProtected="False"
            IsPublic="True"
            IsSpecialName="False"
            IsStatic="True"
            Module="Generics.exe"
            Name="StaticMetod"
            StepOver="False">
            <DeclaringType>
              <DebugType
                BaseType="System.ValueType"
                ElementType="null"
                FullName="Debugger.Tests.TestPrograms.GenericStruct<System.Int32,System.String>"
                GenericArguments="{System.Int32, System.String}"
                Interfaces="{}"
                Kind="ValueType"
                Module="Generics.exe"
                Name="GenericStruct<Int32,String>" />
            </DeclaringType>
          </MethodInfo>
        </MethodInfo>
      </StackFrame>
    </SelectedStackFrame>
    <SelectedStackFrame-GetArguments
      Capacity="4"
      Count="2">
      <Item>
        <Value
          ArrayDimensions="{Exception: Value is not an array}"
          ArrayLength="{Exception: Value is not an array}"
          ArrayRank="{Exception: Value is not an array}"
          AsString="7"
          Expression="v"
          IsInvalid="False"
          IsNull="False"
          IsReference="False"
          PrimitiveValue="7"
          Type="System.Int32" />
      </Item>
      <Item>
        <Value
          ArrayDimensions="{Exception: Value is not an array}"
          ArrayLength="{Exception: Value is not an array}"
          ArrayRank="{Exception: Value is not an array}"
          AsString="7!"
          Expression="k"
          IsInvalid="False"
          IsNull="False"
          IsReference="True"
          PrimitiveValue="7!"
          Type="System.String" />
      </Item>
    </SelectedStackFrame-GetArguments>
    <DebuggingPaused>Break Generics.cs:93,4-93,40</DebuggingPaused>
    <SelectedStackFrame>
      <StackFrame
        ArgumentCount="2"
        ChainIndex="1"
        FrameIndex="1"
        HasSymbols="True"
        IsInvalid="False"
        MethodInfo="StaticGenericMethod"
        NextStatement="Generics.cs:93,4-93,40">
        <MethodInfo>
          <MethodInfo
            DeclaringType="Debugger.Tests.TestPrograms.GenericStruct<System.Int32,System.String>"
            FullName="Debugger.Tests.TestPrograms.GenericStruct<System.Int32,System.String>.StaticGenericMethod"
            IsInternal="False"
            IsPrivate="False"
            IsProtected="False"
            IsPublic="True"
            IsSpecialName="False"
            IsStatic="True"
            Module="Generics.exe"
            Name="StaticGenericMethod"
            StepOver="False">
            <DeclaringType>
              <DebugType
                BaseType="System.ValueType"
                ElementType="null"
                FullName="Debugger.Tests.TestPrograms.GenericStruct<System.Int32,System.String>"
                GenericArguments="{System.Int32, System.String}"
                Interfaces="{}"
                Kind="ValueType"
                Module="Generics.exe"
                Name="GenericStruct<Int32,String>" />
            </DeclaringType>
          </MethodInfo>
        </MethodInfo>
      </StackFrame>
    </SelectedStackFrame>
    <SelectedStackFrame-GetArguments
      Capacity="4"
      Count="2">
      <Item>
        <Value
          ArrayDimensions="{Exception: Value is not an array}"
          ArrayLength="{Exception: Value is not an array}"
          ArrayRank="{Exception: Value is not an array}"
          AsString="8"
          Expression="v"
          IsInvalid="False"
          IsNull="False"
          IsReference="False"
          PrimitiveValue="8"
          Type="System.Int32" />
      </Item>
      <Item>
        <Value
          ArrayDimensions="{Exception: Value is not an array}"
          ArrayLength="{Exception: Value is not an array}"
          ArrayRank="{Exception: Value is not an array}"
          AsString="8!"
          Expression="k"
          IsInvalid="False"
          IsNull="False"
          IsReference="True"
          PrimitiveValue="8!"
          Type="System.String" />
      </Item>
    </SelectedStackFrame-GetArguments>
    <DebuggingPaused>Break Generics.cs:28,4-28,40</DebuggingPaused>
    <Prop>
      <Value
        ArrayDimensions="{Exception: Value is not an array}"
        ArrayLength="{Exception: Value is not an array}"
        ArrayRank="{Exception: Value is not an array}"
        AsString="0"
        Expression="gClass.Prop"
        IsInvalid="False"
        IsNull="False"
        IsReference="False"
        PrimitiveValue="0"
        Type="System.Int32" />
    </Prop>
    <StaticProp>
      <Value
        ArrayDimensions="{Exception: Value is not an array}"
        ArrayLength="{Exception: Value is not an array}"
        ArrayRank="{Exception: Value is not an array}"
        AsString="0"
        Expression="Debugger.Tests.TestPrograms.GenericClass<System.Int32,System.String>.StaticProp"
        IsInvalid="False"
        IsNull="False"
        IsReference="False"
        PrimitiveValue="0"
        Type="System.Int32" />
    </StaticProp>
    <ProcessExited />
  </Test>
</DebuggerTests>
#endif // EXPECTED_OUTPUT


text:
package org.joda.beans.sample;

import java.util.Map;

import org.joda.beans.Bean;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaBean;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.gen.BeanDefinition;
import org.joda.beans.gen.PropertyDefinition;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;

/**
 * Mock person JavaBean, used for testing.
 *
 * @author Stephen Colebourne
 */
@BeanDefinition(builderScope = "public")
public class SimpleSubPersonWithBuilderNonFinal extends SimplePersonWithBuilderNonFinal {

    /** The middle name. */
    @PropertyDefinition
    private String middleName;

    //------------------------- AUTOGENERATED START -------------------------
    /**
     * The meta-bean for {@code SimpleSubPersonWithBuilderNonFinal}.
     * @return the meta-bean, not null
     */
    public static SimpleSubPersonWithBuilderNonFinal.Meta meta() {
        return SimpleSubPersonWithBuilderNonFinal.Meta.INSTANCE;
    }

    static {
        MetaBean.register(SimpleSubPersonWithBuilderNonFinal.Meta.INSTANCE);
    }

    /**
     * Returns a builder used to create an instance of the bean.
     * @return the builder, not null
     */
    public static SimpleSubPersonWithBuilderNonFinal.Builder builder() {
        return new SimpleSubPersonWithBuilderNonFinal.Builder();
    }

    /**
     * Restricted constructor.
     * @param builder  the builder to copy from, not null
     */
    protected SimpleSubPersonWithBuilderNonFinal(SimpleSubPersonWithBuilderNonFinal.Builder builder) {
        super(builder);
        this.middleName = builder.middleName;
    }

    @Override
    public SimpleSubPersonWithBuilderNonFinal.Meta metaBean() {
        return SimpleSubPersonWithBuilderNonFinal.Meta.INSTANCE;
    }

    //-----------------------------------------------------------------------
    /**
     * Gets the middle name.
     * @return the value of the property
     */
    public String getMiddleName() {
        return middleName;
    }

    /**
     * Sets the middle name.
     * @param middleName  the new value of the property
     */
    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }

    /**
     * Gets the the {@code middleName} property.
     * @return the property, not null
     */
    public final Property<String> middleName() {
        return metaBean().middleName().createProperty(this);
    }

    //-----------------------------------------------------------------------
    /**
     * Returns a builder that allows this bean to be mutated.
     * @return the mutable builder, not null
     */
    @Override
    public Builder toBuilder() {
        return new Builder(this);
    }

    @Override
    public SimpleSubPersonWithBuilderNonFinal clone() {
        return JodaBeanUtils.cloneAlways(this);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj != null && obj.getClass() == this.getClass()) {
            SimpleSubPersonWithBuilderNonFinal other = (SimpleSubPersonWithBuilderNonFinal) obj;
            return JodaBeanUtils.equal(getMiddleName(), other.getMiddleName()) &&
                    super.equals(obj);
        }
        return false;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = hash * 31 + JodaBeanUtils.hashCode(getMiddleName());
        return hash ^ super.hashCode();
    }

    @Override
    public String toString() {
        StringBuilder buf = new StringBuilder(64);
        buf.append("SimpleSubPersonWithBuilderNonFinal{");
        int len = buf.length();
        toString(buf);
        if (buf.length() > len) {
            buf.setLength(buf.length() - 2);
        }
        buf.append('}');
        return buf.toString();
    }

    @Override
    protected void toString(StringBuilder buf) {
        super.toString(buf);
        buf.append("middleName").append('=').append(JodaBeanUtils.toString(getMiddleName())).append(',').append(' ');
    }

    //-----------------------------------------------------------------------
    /**
     * The meta-bean for {@code SimpleSubPersonWithBuilderNonFinal}.
     */
    public static class Meta extends SimplePersonWithBuilderNonFinal.Meta {
        /**
         * The singleton instance of the meta-bean.
         */
        static final Meta INSTANCE = new Meta();

        /**
         * The meta-property for the {@code middleName} property.
         */
        private final MetaProperty<String> middleName = DirectMetaProperty.ofReadWrite(
                this, "middleName", SimpleSubPersonWithBuilderNonFinal.class, String.class);
        /**
         * The meta-properties.
         */
        private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
                this, (DirectMetaPropertyMap) super.metaPropertyMap(),
                "middleName");

        /**
         * Restricted constructor.
         */
        protected Meta() {
        }

        @Override
        protected MetaProperty<?> metaPropertyGet(String propertyName) {
            switch (propertyName.hashCode()) {
                case -818219584:  // middleName
                    return middleName;
            }
            return super.metaPropertyGet(propertyName);
        }

        @Override
        public SimpleSubPersonWithBuilderNonFinal.Builder builder() {
            return new SimpleSubPersonWithBuilderNonFinal.Builder();
        }

        @Override
        public Class<? extends SimpleSubPersonWithBuilderNonFinal> beanType() {
            return SimpleSubPersonWithBuilderNonFinal.class;
        }

        @Override
        public Map<String, MetaProperty<?>> metaPropertyMap() {
            return metaPropertyMap$;
        }

        //-----------------------------------------------------------------------
        /**
         * The meta-property for the {@code middleName} property.
         * @return the meta-property, not null
         */
        public final MetaProperty<String> middleName() {
            return middleName;
        }

        //-----------------------------------------------------------------------
        @Override
        protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
            switch (propertyName.hashCode()) {
                case -818219584:  // middleName
                    return ((SimpleSubPersonWithBuilderNonFinal) bean).getMiddleName();
            }
            return super.propertyGet(bean, propertyName, quiet);
        }

        @Override
        protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
            switch (propertyName.hashCode()) {
                case -818219584:  // middleName
                    ((SimpleSubPersonWithBuilderNonFinal) bean).setMiddleName((String) newValue);
                    return;
            }
            super.propertySet(bean, propertyName, newValue, quiet);
        }

    }

    //-----------------------------------------------------------------------
    /**
     * The bean-builder for {@code SimpleSubPersonWithBuilderNonFinal}.
     */
    public static class Builder extends SimplePersonWithBuilderNonFinal.Builder {

        private String middleName;

        /**
         * Restricted constructor.
         */
        protected Builder() {
        }

        /**
         * Restricted copy constructor.
         * @param beanToCopy  the bean to copy from, not null
         */
        protected Builder(SimpleSubPersonWithBuilderNonFinal beanToCopy) {
            super(beanToCopy);
            this.middleName = beanToCopy.getMiddleName();
        }

        //-----------------------------------------------------------------------
        @Override
        public Object get(String propertyName) {
            switch (propertyName.hashCode()) {
                case -818219584:  // middleName
                    return middleName;
                default:
                    return super.get(propertyName);
            }
        }

        @Override
        public Builder set(String propertyName, Object newValue) {
            switch (propertyName.hashCode()) {
                case -818219584:  // middleName
                    this.middleName = (String) newValue;
                    break;
                default:
                    super.set(propertyName, newValue);
                    break;
            }
            return this;
        }

        @Override
        public Builder set(MetaProperty<?> property, Object value) {
            super.set(property, value);
            return this;
        }

        @Override
        public SimpleSubPersonWithBuilderNonFinal build() {
            return new SimpleSubPersonWithBuilderNonFinal(this);
        }

        //-----------------------------------------------------------------------
        /**
         * Sets the middle name.
         * @param middleName  the new value
         * @return this, for chaining, not null
         */
        public Builder middleName(String middleName) {
            this.middleName = middleName;
            return this;
        }

        //-----------------------------------------------------------------------
        @Override
        public String toString() {
            StringBuilder buf = new StringBuilder(64);
            buf.append("SimpleSubPersonWithBuilderNonFinal.Builder{");
            int len = buf.length();
            toString(buf);
            if (buf.length() > len) {
                buf.setLength(buf.length() - 2);
            }
            buf.append('}');
            return buf.toString();
        }

        @Override
        protected void toString(StringBuilder buf) {
            super.toString(buf);
            buf.append("middleName").append('=').append(JodaBeanUtils.toString(middleName)).append(',').append(' ');
        }

    }

    //-------------------------- AUTOGENERATED END --------------------------
}


text:
import java.io.*;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class QueryTranslator
{
static String convertedString="";
	QueryTranslator(String inputString, String dbName, String driver, String username, String password,boolean toggle) throws IOException//Constructor
	{
		//Query Preprocessing
		String preProcessedString=QueryPreProcessor.preProcessor(inputString,dbName,driver,username,password);
		TokenizerModule t=new TokenizerModule(preProcessedString);
		String correctedString=t.correctString();
		System.out.println(correctedString);

		//Query Translation
		ANTLRInputStream input=new ANTLRInputStream(correctedString.replace(" ","")+"\n");
		nlptosqlLexer lex=new nlptosqlLexer(input);
		CommonTokenStream tokens=new CommonTokenStream(lex);
		nlptosqlParser parser=new nlptosqlParser(tokens);
		ParseTree tree=parser.translate();
		convertedString=parser.result;
                if(toggle){
		ParserRuleContext tree1=(ParserRuleContext)tree;
        tree1.inspect(parser);
                }
		System.out.println(convertedString);

		//Query Postprocessing
		Pattern pattern = Pattern.compile("value[0-9]");
		for (int i=0;i<QueryPreProcessor.items;i++)
		{
			System.out.println(i+" "+QueryPreProcessor.ReplacedContent[i][0]+" "+QueryPreProcessor.ReplacedContent[i][1]);
			Matcher matcher = pattern.matcher(QueryPreProcessor.ReplacedContent[i][1]);
			if(matcher.find())
			{
                            String s1=DateUtil.convertToDate(QueryPreProcessor.ReplacedContent[i][0]);
                            if(s1!=null)
                            {
                                convertedString=convertedString.replace(QueryPreProcessor.ReplacedContent[i][1],"'"+s1+"'");
                            }
                            else{
				int s=convertedString.indexOf(QueryPreProcessor.ReplacedContent[i][1]);
				if(convertedString.charAt(s-1)=='%')
				{
					if(convertedString.length()-s==7)
					{
						String k=QueryPreProcessor.ReplacedContent[i][0];
						System.out.println(k);
						k="'%"+k+"%'";
						convertedString=convertedString.replace("%"+QueryPreProcessor.ReplacedContent[i][1]+"%",k);
					}
					else
					{
						String k=QueryPreProcessor.ReplacedContent[i][0];
						k="'%"+k+"'";
						convertedString=convertedString.replace("%"+QueryPreProcessor.ReplacedContent[i][1],k);
					}
				}
				else
				if(convertedString.length()-s==7)
					{
						String k=QueryPreProcessor.ReplacedContent[i][0];
						k="'"+k+"%'";
						convertedString=convertedString.replace(QueryPreProcessor.ReplacedContent[i][1]+"%",k);
					}
				else
				{
				convertedString=convertedString.replace(QueryPreProcessor.ReplacedContent[i][1],"'"+QueryPreProcessor.ReplacedContent[i][0]+"'");
				}
                            }
			}
			else
			convertedString=convertedString.replace(QueryPreProcessor.ReplacedContent[i][1],QueryPreProcessor.ReplacedContent[i][0]);
		}
		System.out.println(convertedString);
	}

	public static void main(String args[]) throws IOException
	{
	Scanner scan=new Scanner(System.in);
	String query=scan.nextLine();
	String dbName="classicmodels";
	String driver="com.mysql.jdbc.Driver";
	String username="root";
	String pass="";
	new QueryTranslator(query,dbName,driver,username,pass,true);
	}
}


text:
<?php

namespace Coast;

use ArrayAccess;
use SeekableIterator;
use Countable;
use Serializable;
use JsonSerializable;

class Collection implements ArrayAccess, SeekableIterator, Countable, Serializable, JsonSerializable
{
    protected $_array = [];

    public function __construct(array $array = [])
    {
        $this->_array = $array;
    }

    public function toArray()
    {
        return $this->_array;
    }

    public function fromArray(array $array)
    {
        $this->_array = $array;
        return $this;
    }

    public function __set($key, $value)
    {
        if (isset($key)) {
            $this->_array[$key] = $value;
        } else {
            $this->_array[] = $value;
        }
    }

    public function __get($key)
    {
        return $this->_array[$key];
    }

    public function __isset($key)
    {
        return isset($this->_array[$key]);
    }

    public function __unset($key)
    {
        unset($this->_array[$key]);
    }

    public function offsetSet($offset, $value)
    {
       return $this->__set($offset, $value);
    }

    public function offsetExists($offset)
    {
        return $this->__isset($offset);
    }

    public function offsetUnset($offset)
    {
        return $this->__unset($offset);
    }

    public function offsetGet($offset)
    {
        return $this->__get($offset);
    }

    public function rewind()
    {
        reset($this->_array);
    }

    public function current()
    {
        return current($this->_array);
    }

    public function key()
    {
        return key($this->_array);
    }

    public function next()
    {
        next($this->_array);
    }

    public function valid()
    {
        return key($this->_array) !== null;
    }

    public function seek($position)
    {
        do {
            if ($position === key($this->_array)) {
                return true;
            }
        } while (next($this->_array));
        return false;
    }

    public function count()
    {
        return count($this->_array);
    }

    public function serialize()
    {
        return serialize($this->_array);
    }

    public function unserialize($array)
    {
        $this->_array = unserialize($array);
    }

    public function jsonSerialize()
    {
        return $this->_array;
    }
}


text:
function headprintln(x,sym)
    println(repeat(sym,50))
    println(x)
    println(repeat(sym,50))
end


text:
XTOOLS_NAMESPACE_BEGIN

DECLARE_PTR_PRE(SharingManager)

/// Main class responsible for initializing the primary systems and allowing
/// access to the creation of other objects
class SharingManager : public AtomicRefCounted
{
public:
	/// Create a new SharingManager instance.  There should only be one per app
	static ref_ptr<SharingManager>			Create(const ClientConfigPtr& config);

	/// Returns the \ref SessionManager, which keeps track of available sessions and allows
	/// this client to create, join, and leave sessions
	virtual const SessionManagerPtr&		GetSessionManager() const = 0;

	virtual const UserPresenceManagerPtr&	GetUserPresenceManager() const = 0;

	virtual const AudioManagerPtr&			GetAudioManager() const = 0;

	/// Returns the PairingManager, which allows two clients to connect to each other
	virtual const PairingManagerPtr&		GetPairingManager() const = 0;

	/// Returns the RoomManager, which allows users to define which physical real-world rooms they
	/// are in, which allows for appropriate sharing of spatial tracking anchors on HoloLens and
	/// ensures voice audio gets sent to only people who are not in the same room.
	virtual const RoomManagerPtr&			GetRoomManager() const = 0;

	/// Returns the root element in the sync data set.  There is always a root object
	virtual ObjectElementPtr				GetRootSyncObject() = 0;

	/// Register a listener object to receive notifications before and after the sync system
	/// sends notifications that sync elements have been changed by remote peers.
	/// Returns true if successful, false if registration fails
	virtual bool							RegisterSyncListener(SyncListener* listener) = 0;

	/// Ticks the entire XTools system.  Causes any network messages that have been received to be processed and
	/// any registered callbacks to be called.  This function should be called frequently (eg: once per frame).
	virtual void							Update() = 0;

	/// Get the connection to the Baraboo visualizer for this app, so that custom
	/// messages can be sent back and forth.
	/// Note that the visualizer may not be connected yet, but the NetworkConnection
	/// provides hooks to notify you when that happens.
	virtual NetworkConnectionPtr			GetPairedConnection() = 0;

	/// Get the connection to the server.  This may or may not already be connected.
	/// Not currently expected to be used by desktop app code, but exposed just in case
	virtual NetworkConnectionPtr			GetServerConnection() = 0;

#if defined(MSTEST)
	/// Expose the connect to the session list server on in builds for Test.  This connection is
	/// used to tell multiple remote clients to join and leave sessions by automated tests.
	virtual NetworkConnectionPtr			GetListServerConnection() = 0;
#endif

	/// Get the settings that were loaded in from the config file
	virtual const SettingsPtr&				GetSettings() = 0;

	virtual void							SetServerConnectionInfo(const XStringPtr& address, uint32 port) = 0;

	/// Returns an object representing the local user.
	/// Note that this will not return null, but the user can be invalid.
	/// Check with User.IsValid() before using.
	virtual UserPtr							GetLocalUser() = 0;

	virtual void							SetUserName(const XStringPtr& name) = 0;
};

DECLARE_PTR_POST(SharingManager)

XTOOLS_NAMESPACE_END


text:
package main // import "eriol.xyz/mvshaker"

import (
	"io/ioutil"
	"math/rand"
	"os"
	"path/filepath"
	"sort"
	"testing"

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

// sort.Interface for []shakableFile based on the filepath field.
type ByPath []shakableFile

func (p ByPath) Len() int           { return len(p) }
func (p ByPath) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p ByPath) Less(i, j int) bool { return p[i].filepath < p[j].filepath }

func Testランダム(t *testing.T) {
	files := []shakableFile{
		shakableFile{filepath: "a.txt", isShaked: false},
		shakableFile{filepath: "b.txt", isShaked: false},
		shakableFile{filepath: "c.txt", isShaked: false}}

	assert.Equal(t, files[0].filepath, "a.txt")
	assert.Equal(t, files[1].filepath, "b.txt")
	assert.Equal(t, files[2].filepath, "c.txt")

	rand.Seed(1)

	ランダム(files)

	assert.Equal(t, files[0].filepath, "c.txt")
	assert.Equal(t, files[1].filepath, "a.txt")
	assert.Equal(t, files[2].filepath, "b.txt")

}

func TestCollectNoExclude(t *testing.T) {

	file1, _ := ioutil.TempFile("", "mvshaker")
	defer os.Remove(file1.Name())
	file2, _ := ioutil.TempFile("", "mvshaker")
	defer os.Remove(file2.Name())
	file3, _ := ioutil.TempFile("", "mvshaker")
	defer os.Remove(file3.Name())

	filesToCollect := []string{file1.Name(), file2.Name(), file3.Name()}
	paths := collect(filesToCollect, []string{}, false)

	assert.Equal(
		t,
		paths,
		[]shakableFile{
			shakableFile{filepath: file1.Name(), isShaked: false},
			shakableFile{filepath: file2.Name(), isShaked: false},
			shakableFile{filepath: file3.Name(), isShaked: false}})
}

func TestCollectExclude(t *testing.T) {

	file1, _ := ioutil.TempFile("", "mvshaker")
	defer os.Remove(file1.Name())
	file2, _ := ioutil.TempFile("", "mvshaker")
	defer os.Remove(file2.Name())
	file3, _ := ioutil.TempFile("", "mvshaker")
	defer os.Remove(file3.Name())

	filesToCollect := []string{file1.Name(), file2.Name(), file3.Name()}
	paths := collect(filesToCollect, []string{filepath.Base(file2.Name())}, false)

	assert.Equal(
		t,
		paths,
		[]shakableFile{
			shakableFile{filepath: file1.Name(), isShaked: false},
			shakableFile{filepath: file3.Name(), isShaked: false}})
}

func TestCollectDirectory(t *testing.T) {

	file1, _ := ioutil.TempFile("", "mvshaker")
	defer os.Remove(file1.Name())
	file2, _ := ioutil.TempFile("", "mvshaker")
	defer os.Remove(file2.Name())
	dir, _ := ioutil.TempDir("", "mvshaker")
	defer os.Remove(dir)

	filesToCollect := []string{file1.Name(), file2.Name(), dir}
	paths := collect(filesToCollect, []string{}, false)

	assert.Equal(
		t,
		paths,
		[]shakableFile{
			shakableFile{filepath: file1.Name(), isShaked: false},
			shakableFile{filepath: file2.Name(), isShaked: false}})
}

func TestCollectDirectoryRecursive(t *testing.T) {

	file1, _ := ioutil.TempFile("", "mvshaker")
	defer os.Remove(file1.Name())
	file2, _ := ioutil.TempFile("", "mvshaker")
	defer os.Remove(file2.Name())
	dir, _ := ioutil.TempDir("", "mvshaker")
	defer os.Remove(dir)
	file3, _ := ioutil.TempFile(dir, "mvshaker")
	defer os.Remove(file3.Name())
	dir2, _ := ioutil.TempDir(dir, "mvshaker")
	defer os.Remove(dir2)
	file4, _ := ioutil.TempFile(dir2, "mvshaker")
	defer os.Remove(file4.Name())

	filesToCollect := []string{file1.Name(), file2.Name(), dir}
	paths := collect(filesToCollect, []string{}, true)
	sort.Sort(ByPath(paths))

	expected := []shakableFile{
		shakableFile{filepath: file1.Name(), isShaked: false},
		shakableFile{filepath: file2.Name(), isShaked: false},
		shakableFile{filepath: file3.Name(), isShaked: false},
		shakableFile{filepath: file4.Name(), isShaked: false}}
	sort.Sort(ByPath(expected))

	assert.Equal(t, paths, expected)
}

func TestShake(t *testing.T) {

	file1, _ := ioutil.TempFile("", "mvshaker")
	defer os.Remove(file1.Name())
	file2, _ := ioutil.TempFile("", "mvshaker")
	defer os.Remove(file2.Name())
	file3, _ := ioutil.TempFile("", "mvshaker")
	defer os.Remove(file3.Name())

	if err := ioutil.WriteFile(file1.Name(), []byte("01\n"), 0644); err != nil {
		assert.Error(t, err)
	}
	if err := ioutil.WriteFile(file2.Name(), []byte("02\n"), 0644); err != nil {
		assert.Error(t, err)
	}
	if err := ioutil.WriteFile(file3.Name(), []byte("03\n"), 0644); err != nil {
		assert.Error(t, err)
	}

	source := []shakableFile{
		shakableFile{filepath: file1.Name(), isShaked: false},
		shakableFile{filepath: file2.Name(), isShaked: false},
		shakableFile{filepath: file3.Name(), isShaked: false}}

	dest := make([]shakableFile, len(source))
	copy(dest, source)

	rand.Seed(1)
	ランダム(dest)

	shake(source, dest)

	assert.Equal(t, source[0].isShaked, false)
	assert.Equal(t, source[1].isShaked, true)
	assert.Equal(t, source[2].isShaked, true)

	assert.Equal(t, dest[0].isShaked, false)
	assert.Equal(t, dest[1].isShaked, true)
	assert.Equal(t, dest[2].isShaked, true)

	data1, err := ioutil.ReadFile(file1.Name())
	if err != nil {
		assert.Error(t, err)
	}
	data2, err := ioutil.ReadFile(file2.Name())
	if err != nil {
		assert.Error(t, err)
	}
	data3, err := ioutil.ReadFile(file3.Name())
	if err != nil {
		assert.Error(t, err)
	}

	assert.Equal(t, string(data1), "03\n")
	assert.Equal(t, string(data2), "01\n")
	assert.Equal(t, string(data3), "02\n")
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateNotificationsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up() {
		Schema::create('notifications', function($table) {
			$table->increments('id');
			$table->integer('user_id')->unsigned();
			$table->foreign('user_id')->references('id')->on('users');
			$table->integer('reply_id')->unsigned();
			$table->foreign('reply_id')->references('id')->on('replies');
			$table->boolean('has_read');
			$table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down() {
		DB::statement('SET FOREIGN_KEY_CHECKS=0');
		Schema::drop('notifications');
	}

}


text:
package org.jboss.pnc.indyrepositorymanager;

import org.jboss.pnc.model.Artifact;
import org.jboss.pnc.spi.coordinator.CompletionStatus;
import org.jboss.pnc.spi.repositorymanager.RepositoryManagerResult;

import java.util.List;

/**
 * Created by Matej Lazar on 2015-02-02.
 */
public class IndyRepositoryManagerResult implements RepositoryManagerResult {

    private final CompletionStatus completionStatus;
    private final String log;

    private final List<Artifact> builtArtifacts;
    private final List<Artifact> dependencies;
    private final String buildContentId;

    /**
     *
     * @deprecated Use constructor with status and log parameter
     */
    @Deprecated
    public IndyRepositoryManagerResult(
            List<Artifact> builtArtifacts,
            List<Artifact> dependencies,
            String buildContentId) {
        this.builtArtifacts = builtArtifacts;
        this.dependencies = dependencies;
        this.buildContentId = buildContentId;
        this.completionStatus = CompletionStatus.SUCCESS;
        this.log = "";
    }

    public IndyRepositoryManagerResult(
            List<Artifact> builtArtifacts,
            List<Artifact> dependencies,
            String buildContentId,
            String log,
            CompletionStatus completionStatus) {
        this.builtArtifacts = builtArtifacts;
        this.dependencies = dependencies;
        this.buildContentId = buildContentId;
        this.log = log;
        this.completionStatus = completionStatus;
    }

    @Override
    public List<Artifact> getBuiltArtifacts() {
        return builtArtifacts;
    }

    @Override
    public List<Artifact> getDependencies() {
        return dependencies;
    }

    @Override
    public String getBuildContentId() {
        return buildContentId;
    }

    @Override
    public String getLog() {
        return log;
    }

    @Override
    public CompletionStatus getCompletionStatus() {
        return completionStatus;
    }
}


text:
package org.locke.biokit.chemistry.molecule.compounds.polymers.collections;

import org.locke.biokit.chemistry.molecule.compounds.polymers.Polymer;
import org.locke.superkit.collections.lists.ObjectList;
import org.locke.superkit.language.scalars.indexes.Index;
import org.locke.superkit.language.scalars.numbers.count.Count;

public class PolymerArrayList implements Polymer.Collection
{
	private final ObjectList<Polymer> polymers;

	public PolymerArrayList()
	{
		this.polymers = new ObjectList<>();
	}

	public PolymerArrayList(final ObjectList<Polymer> sequences)
	{
		this.polymers = sequences;
	}

	public PolymerArrayList add(final Polymer sequence)
	{
		this.polymers.add(sequence);
		return this;
	}

	public PolymerArrayList addAll(final Polymer.Sequence polymers)
	{
		for (final Polymer polymer : polymers.polymers())
		{
			add(polymer);
		}
		return this;
	}

	public PolymerSet asSet()
	{
		return newPolymerSet().addAll(polymers());
	}

	public boolean contains(final Polymer sequence)
	{
		return this.polymers.contains(sequence);
	}

	@Override
	public boolean equals(final Object object)
	{
		if (object instanceof PolymerArrayList)
		{
			final PolymerArrayList that = (PolymerArrayList) object;
			return this.polymers.equals(that.polymers);
		}
		return false;
	}

	public Polymer get(final Index index)
	{
		return this.polymers.get(index);
	}

	@Override
	public int hashCode()
	{
		return this.polymers.hashCode();
	}

	@Override
	public Polymer head()
	{
		return isEmpty() ? null : this.polymers.get(Index.ZERO);
	}

	@Override
	public boolean isEmpty()
	{
		return this.polymers.isEmpty();
	}

	@Override
	public Iterable<Polymer> polymers()
	{
		return this.polymers;
	}

	public void set(final Index index, final Polymer polymer)
	{
		this.polymers.set(index, polymer);
	}

	@Override
	public Count count()
	{
		return this.polymers.count();
	}

	public PolymerArrayList tail()
	{
		return without(Index.ZERO);
	}

	public PolymerArrayList then(final Polymer that)
	{
		final PolymerArrayList list = new PolymerArrayList();
		list.addAll(this);
		list.add(that);
		return list;
	}

	public PolymerArrayList then(final PolymerArrayList that)
	{
		final PolymerArrayList list = new PolymerArrayList();
		list.addAll(this);
		list.addAll(that);
		return list;
	}

	@Override
	public String toString()
	{
		return join(", ");
	}

	public PolymerArrayList without(final Index without)
	{
		final PolymerArrayList list = new PolymerArrayList();
		for (final Index index : count())
		{
			if (!index.equals(without))
			{
				list.add(get(index));
			}
		}
		return list;
	}
}


text:
[![license](https://img.shields.io/github/license/bigbluehat/web-annotation-protocol-tester.svg?maxAge=2592000?style=flat-square)](https://github.com/bigbluehat/web-annotation-protocol-tester)

# Web Annotation Protocol Test Client

This is an **experimental** test client for the
[Web Annotation Protocol](https://www.w3.org/TR/annotation-protocol/).

### Usage

```sh
$ npm i
$ npm test -- --url=http://localhost:8080/annotations/ # runs all tests
$ # or
$ npm run musts -- --url=http://localhost:8080/annotations/
$ npm run shoulds -- --url=http://localhost:8080/annotations/
```

Alternatively (if you don't like the massive node stack trace mess...):

```sh
$ mocha tests/musts.js --url=http://localhost:8080/annotations/
$ # or
$ mocha tests/shoulds.js --url=http://localhost:8080/annotations/
```

You can also run specific tests by using mocha's built in grep feature:

```sh
$ mocha -g PUT tests/musts.js --url=http://localhost:8080/annotations/
```

### Config

If you'd rather not keep typing the `--url` parameter, you can:

```sh
$ cp config.json.sample config.json
```

And change the `url` parameter to your liking.

### Screenshot

![pretty, right?](screenshot.png)

### License

MIT


text:
Pin elight("elight", ELIGHTS_PIN, elight.analog, elight.out);

void ELights::device_setup(){
  Settings::capability_bitarray |= (1 << LIGHTS_CAPABLE);
  elight.reset();
  elight.write(0);
}

void ELights::device_loop(Command command){

    if( command.cmp("eligt")){
      float percentvalue = command.args[1]/100.0; //0 - 255
      int value = 255*percentvalue;
      elight.write(value);

      Serial.print(F("LIGTE:"));
      Serial.print(value);
      Serial.print(';');
      Serial.print(F("LIGPE:"));
      Serial.print(percentvalue);
      Serial.println(';');
    }
}
#endif


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ShareDatabaseNameMessageHandler.cs" company="Naos Project">
//    Copyright (c) Naos Project 2019. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Naos.Database.MessageBus.Handler
{
    using System.Threading.Tasks;

    using Naos.Database.MessageBus.Scheduler;
    using Naos.Logging.Domain;
    using Naos.MessageBus.Domain;

    /// <summary>
    /// Naos.MessageBus handler for Share.
    /// </summary>
    public class ShareDatabaseNameMessageHandler : MessageHandlerBase<ShareDatabaseNameMessage>, IShareDatabaseName
    {
        /// <inheritdoc cref="MessageHandlerBase{T}" />
        public override async Task HandleAsync(ShareDatabaseNameMessage message)
        {
            using (var log = Log.With(() => new { Message = message, DatabaseNameToShare = message.DatabaseNameToShare }))
            {
                log.Write(() => "Sharing database name: " + message.DatabaseNameToShare);
                this.DatabaseName = await Task.FromResult(message.DatabaseNameToShare);
            }
        }

        /// <inheritdoc />
        public string DatabaseName { get; set; }
    }
}


text:
@interface Foo
@end


text:
#include "ConcurrentModificationException.h"

using namespace std;
using namespace decaf;
using namespace decaf::util;
using namespace decaf::lang;
using namespace decaf::lang::exceptions;

////////////////////////////////////////////////////////////////////////////////
ConcurrentModificationException::ConcurrentModificationException() {
}

////////////////////////////////////////////////////////////////////////////////
ConcurrentModificationException::~ConcurrentModificationException() throw () {
}

////////////////////////////////////////////////////////////////////////////////
ConcurrentModificationException::ConcurrentModificationException(const lang::Exception& ex) : lang::exceptions::RuntimeException() {
    *(lang::Exception*) this = ex;
}

////////////////////////////////////////////////////////////////////////////////
ConcurrentModificationException::ConcurrentModificationException(const ConcurrentModificationException& ex) : lang::exceptions::RuntimeException() {
    *(lang::Exception*) this = ex;
}

////////////////////////////////////////////////////////////////////////////////
ConcurrentModificationException::ConcurrentModificationException(
    const char* file, const int lineNumber, const std::exception* cause, const char* msg, ...) : lang::exceptions::RuntimeException(cause) {

    va_list vargs;
    va_start(vargs, msg);
    buildMessage(msg, vargs);

    // Set the first mark for this exception.
    setMark(file, lineNumber);
}

////////////////////////////////////////////////////////////////////////////////
ConcurrentModificationException::ConcurrentModificationException(const std::exception* cause) : lang::exceptions::RuntimeException(cause) {
}

////////////////////////////////////////////////////////////////////////////////
ConcurrentModificationException::ConcurrentModificationException(const char* file, const int lineNumber, const char* msg, ...) : lang::exceptions::RuntimeException() {

    va_list vargs;
    va_start(vargs, msg);
    buildMessage(msg, vargs);

    // Set the first mark for this exception.
    setMark(file, lineNumber);
}


text:
<?php

/**
 * This is a script to test the Jwt grant type
 */

require __DIR__ . '/../vendor/autoload.php';
date_default_timezone_set('utc');

use OAuth2\Encryption\Jwt;
use DateTime;

/**
 * Generate a JWT
 *
 * @param $privateKey The private key to use to sign the token
 * @param $iss The issuer, usually the client_id
 * @param $sub The subject, usually a user_id
 * @param $aud The audience, usually the URI for the oauth server
 * @param $exp The expiration date. If the current time is greater than the exp, the JWT is invalid
 * @param $nbf The "not before" time. If the current time is less than the nbf, the JWT is invalid
 * @param $jti The "jwt token identifier", or nonce for this JWT
 *
 * @return string
 */
function generateJWT($privateKey, $iss, $sub, $aud, $exp = null, $nbf = null, $jti = null)
{
    if (!$exp) {
        $exp = time() + 1000;
    }

    $params = array(
        'iss' => $iss,
        'sub' => $sub,
        'aud' => $aud,
        'exp' => $exp,
        'iat' => time(),
    );

    if ($nbf) {
        $params['nbf'] = $nbf;
    }

    if ($jti) {
        $params['jti'] = $jti;
    }

    $jwtUtil = new Jwt();

    return $jwtUtil->encode($params, $privateKey, 'RS256');
}

$private_key = file_get_contents(__DIR__ . '/../media/key.pem');
$client_id   = 'client1';
$user_id     = 'user1';
$grant_type  = 'urn:ietf:params:oauth:grant-type:jwt-bearer';

$expires = new DateTime('today +1 day');
$expires = $expires->format('U');
$nbf = new DateTime();
$nbf = $nbf->format('U');
$jwt = generateJWT($private_key, $client_id, $user_id, 'http://localhost:8083', $expires, $nbf, '123456abcdefg');

passthru("curl http://localhost:8083/oauth -d 'grant_type=$grant_type&assertion=$jwt'");


text:
__all__ = ['coroutine',
           'iscoroutinefunction', 'iscoroutine',
           'From', 'Return']

import functools
import inspect
import opcode
import os
import sys
import textwrap
import traceback
import types

from . import compat
from . import events
from . import futures
from .log import logger

# Opcode of "yield from" instruction
_YIELD_FROM = opcode.opmap.get('YIELD_FROM', None)

# If you set _DEBUG to true, @coroutine will wrap the resulting
# generator objects in a CoroWrapper instance (defined below).  That
# instance will log a message when the generator is never iterated
# over, which may happen when you forget to use "yield from" with a
# coroutine call.  Note that the value of the _DEBUG flag is taken
# when the decorator is used, so to be of any use it must be set
# before you define your coroutines.  A downside of using this feature
# is that tracebacks show entries for the CoroWrapper.__next__ method
# when _DEBUG is true.
_DEBUG = bool(os.environ.get('TROLLIUSDEBUG'))

try:
    _types_coroutine = types.coroutine
except AttributeError:
    _types_coroutine = None

try:
    _inspect_iscoroutinefunction = inspect.iscoroutinefunction
except AttributeError:
    _inspect_iscoroutinefunction = lambda func: False

try:
    from collections.abc import Coroutine as _CoroutineABC, \
                                Awaitable as _AwaitableABC
except ImportError:
    _CoroutineABC = _AwaitableABC = None

if _YIELD_FROM is not None:
    # Check for CPython issue #21209
    exec('''if 1:
        def has_yield_from_bug():
            class MyGen:
                def __init__(self):
                    self.send_args = None
                def __iter__(self):
                    return self
                def __next__(self):
                    return 42
                def send(self, *what):
                    self.send_args = what
                    return None
            def yield_from_gen(gen):
                yield from gen
            value = (1, 2, 3)
            gen = MyGen()
            coro = yield_from_gen(gen)
            next(coro)
            coro.send(value)
            return gen.send_args != (value,)
''')
    _YIELD_FROM_BUG = has_yield_from_bug()
    del has_yield_from_bug
else:
    _YIELD_FROM_BUG = False

if compat.PY35:
    return_base_class = Exception
else:
    return_base_class = StopIteration

class ReturnException(return_base_class):
    def __init__(self, *args):
        return_base_class.__init__(self)
        if not args:
            self.value = None
        elif len(args) == 1:
            self.value = args[0]
        else:
            self.value = args
        self.raised = False
        if _DEBUG:
            frame = sys._getframe(1)
            self._source_traceback = traceback.extract_stack(frame)
            # explicitly clear the reference to avoid reference cycles
            frame = None
        else:
            self._source_traceback = None

    def __del__(self):
        if self.raised:
            return

        fmt = 'Return(%r) used without raise'
        if self._source_traceback:
            fmt += '\nReturn created at (most recent call last):\n'
            tb = ''.join(traceback.format_list(self._source_traceback))
            fmt += tb.rstrip()
        logger.error(fmt, self.value)

if compat.PY33 and not compat.PY35:
    # Don't use the Return class on Python 3.3 and 3.4 to support asyncio
    # coroutines (to avoid the warning emited in Return destructor).
    #
    # The problem is that ReturnException inherits from StopIteration.
    # "yield from trollius_coroutine". Task._step() does not receive the Return
    # exception, because "yield from" handles it internally. So it's not
    # possible to set the raised attribute to True to avoid the warning in
    # Return destructor.
    def Return(*args):
        if not args:
            value = None
        elif len(args) == 1:
            value = args[0]
        else:
            value = args
        return StopIteration(value)
else:
    Return = ReturnException

def debug_wrapper(gen):
    # This function is called from 'sys.set_coroutine_wrapper'.
    # We only wrap here coroutines defined via 'async def' syntax.
    # Generator-based coroutines are wrapped in @coroutine
    # decorator.
    return CoroWrapper(gen, None)

def _coroutine_at_yield_from(coro):
    """Test if the last instruction of a coroutine is "yield from".

    Return False if the coroutine completed.
    """
    frame = coro.gi_frame
    if frame is None:
        return False
    code = coro.gi_code
    assert frame.f_lasti >= 0
    offset = frame.f_lasti + 1
    instr = code.co_code[offset]
    return (instr == _YIELD_FROM)

class CoroWrapper:
    # Wrapper for coroutine object in _DEBUG mode.

    def __init__(self, gen, func=None):
        assert inspect.isgenerator(gen) or inspect.iscoroutine(gen), gen
        self.gen = gen
        self.func = func # Used to unwrap @coroutine decorator
        self._source_traceback = traceback.extract_stack(sys._getframe(1))
        self.__name__ = getattr(gen, '__name__', None)
        self.__qualname__ = getattr(gen, '__qualname__', None)

    def __repr__(self):
        coro_repr = _format_coroutine(self)
        if self._source_traceback:
            frame = self._source_traceback[-1]
            coro_repr += ', created at %s:%s' % (frame[0], frame[1])
        return '<%s %s>' % (self.__class__.__name__, coro_repr)

    def __iter__(self):
        return self

    def __next__(self):
        return next(self.gen)
    next = __next__

    if _YIELD_FROM_BUG:
        # For for CPython issue #21209: using "yield from" and a custom
        # generator, generator.send(tuple) unpacks the tuple instead of passing
        # the tuple unchanged. Check if the caller is a generator using "yield
        # from" to decide if the parameter should be unpacked or not.
        def send(self, *value):
            frame = sys._getframe()
            caller = frame.f_back
            assert caller.f_lasti >= 0
            if caller.f_code.co_code[caller.f_lasti] != _YIELD_FROM:
                value = value[0]
            return self.gen.send(value)
    else:
        def send(self, value):
            return self.gen.send(value)

    def throw(self, exc_type, exc_value=None, exc_tb=None):
        return self.gen.throw(exc_type, exc_value, exc_tb)

    def close(self):
        return self.gen.close()

    @property
    def gi_frame(self):
        return self.gen.gi_frame

    @property
    def gi_running(self):
        return self.gen.gi_running

    @property
    def gi_code(self):
        return self.gen.gi_code

    if compat.PY35:

        __await__ = __iter__ # make compatible with 'await' expression

        @property
        def gi_yieldfrom(self):
            return self.gen.gi_yieldfrom

        @property
        def cr_await(self):
            return self.gen.cr_await

        @property
        def cr_running(self):
            return self.gen.cr_running

        @property
        def cr_code(self):
            return self.gen.cr_code

        @property
        def cr_frame(self):
            return self.gen.cr_frame

    def __del__(self):
        # Be careful accessing self.gen.frame -- self.gen might not exist.
        gen = getattr(self, 'gen', None)
        frame = getattr(gen, 'gi_frame', None)
        if frame is None:
            frame = getattr(gen, 'cr_frame', None)
        if frame is not None and frame.f_lasti == -1:
            msg = '%r was never yielded from' % self
            tb = getattr(self, '_source_traceback', ())
            if tb:
                tb = ''.join(traceback.format_list(tb))
                msg += ('\nCoroutine object created at '
                        '(most recent call last):\n')
                msg += tb.rstrip()
            logger.error(msg)

if not compat.PY34:
    # Backport functools.update_wrapper() from Python 3.4:
    # - Python 2.7 fails if assigned attributes don't exist
    # - Python 2.7 and 3.1 don't set the __wrapped__ attribute
    # - Python 3.2 and 3.3 set __wrapped__ before updating __dict__
    def _update_wrapper(wrapper,
                       wrapped,
                       assigned = functools.WRAPPER_ASSIGNMENTS,
                       updated = functools.WRAPPER_UPDATES):
        """Update a wrapper function to look like the wrapped function

           wrapper is the function to be updated
           wrapped is the original function
           assigned is a tuple naming the attributes assigned directly
           from the wrapped function to the wrapper function (defaults to
           functools.WRAPPER_ASSIGNMENTS)
           updated is a tuple naming the attributes of the wrapper that
           are updated with the corresponding attribute from the wrapped
           function (defaults to functools.WRAPPER_UPDATES)
        """
        for attr in assigned:
            try:
                value = getattr(wrapped, attr)
            except AttributeError:
                pass
            else:
                setattr(wrapper, attr, value)
        for attr in updated:
            getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
        # Issue #17482: set __wrapped__ last so we don't inadvertently copy it
        # from the wrapped function when updating __dict__
        wrapper.__wrapped__ = wrapped
        # Return the wrapper so this can be used as a decorator via partial()
        return wrapper

    def _wraps(wrapped,
              assigned = functools.WRAPPER_ASSIGNMENTS,
              updated = functools.WRAPPER_UPDATES):
        """Decorator factory to apply update_wrapper() to a wrapper function

           Returns a decorator that invokes update_wrapper() with the decorated
           function as the wrapper argument and the arguments to wraps() as the
           remaining arguments. Default arguments are as for update_wrapper().
           This is a convenience function to simplify applying partial() to
           update_wrapper().
        """
        return functools.partial(_update_wrapper, wrapped=wrapped,
                                 assigned=assigned, updated=updated)
else:
    _wraps = functools.wraps

_PEP479 = (sys.version_info >= (3, 5))
if _PEP479:
    # Need exec() because yield+return raises a SyntaxError on Python 2
    exec(textwrap.dedent('''
        def pep479_wrapper(func, coro_func):
            @_wraps(func)
            def pep479_wrapped(*args, **kw):
                coro = coro_func(*args, **kw)
                value = None
                error = None
                while True:
                    try:
                        if error is not None:
                            value = coro.throw(error)
                        elif value is not None:
                            value = coro.send(value)
                        else:
                            value = next(coro)
                    except RuntimeError:
                        # FIXME: special case for
                        # FIXME: "isinstance(exc.__context__, StopIteration)"?
                        raise
                    except StopIteration as exc:
                        return exc.value
                    except Return as exc:
                        exc.raised = True
                        return exc.value
                    except BaseException as exc:
                        raise

                    try:
                        value = yield value
                        error = None
                    except BaseException as exc:
                        value = None
                        error = exc

            return pep479_wrapped
        '''))

def coroutine(func):
    """Decorator to mark coroutines.

    If the coroutine is not yielded from before it is destroyed,
    an error message is logged.
    """
    if _inspect_iscoroutinefunction(func):
        # In Python 3.5 that's all we need to do for coroutines
        # defiend with "async def".
        # Wrapping in CoroWrapper will happen via
        # 'sys.set_coroutine_wrapper' function.
        return func

    if inspect.isgeneratorfunction(func):
        coro = func
    else:
        @_wraps(func)
        def coro(*args, **kw):
            res = func(*args, **kw)
            if (isinstance(res, futures._FUTURE_CLASSES)
                or inspect.isgenerator(res)):
                res = yield From(res)
            elif _AwaitableABC is not None:
                # If 'func' returns an Awaitable (new in 3.5) we
                # want to run it.
                try:
                    await_meth = res.__await__
                except AttributeError:
                    pass
                else:
                    if isinstance(res, _AwaitableABC):
                        res = yield From(await_meth())
            raise Return(res)

    if _PEP479:
        # FIXME: use @_wraps
        coro = pep479_wrapper(func, coro)
        coro = _wraps(func)(coro)

    if not _DEBUG:
        if _types_coroutine is None:
            wrapper = coro
        else:
            wrapper = _types_coroutine(coro)
    else:
        @_wraps(func)
        def wrapper(*args, **kwds):
            w = CoroWrapper(coro(*args, **kwds), func=func)
            if w._source_traceback:
                del w._source_traceback[-1]
            # Python < 3.5 does not implement __qualname__
            # on generator objects, so we set it manually.
            # We use getattr as some callables (such as
            # functools.partial may lack __qualname__).
            w.__name__ = getattr(func, '__name__', None)
            w.__qualname__ = getattr(func, '__qualname__', None)
            return w

    wrapper._is_coroutine = True  # For iscoroutinefunction().
    return wrapper

def iscoroutinefunction(func):
    """Return True if func is a decorated coroutine function."""
    return (getattr(func, '_is_coroutine', False) or
            _inspect_iscoroutinefunction(func))

_COROUTINE_TYPES = (types.GeneratorType, CoroWrapper)
if _CoroutineABC is not None:
    _COROUTINE_TYPES += (_CoroutineABC,)
if events.asyncio is not None:
    # Accept also asyncio CoroWrapper for interoperability
    if hasattr(events.asyncio, 'coroutines'):
        _COROUTINE_TYPES += (events.asyncio.coroutines.CoroWrapper,)
    else:
        # old asyncio/Python versions
        _COROUTINE_TYPES += (events.asyncio.tasks.CoroWrapper,)

def iscoroutine(obj):
    """Return True if obj is a coroutine object."""
    return isinstance(obj, _COROUTINE_TYPES)

def _format_coroutine(coro):
    assert iscoroutine(coro)

    coro_name = None
    if isinstance(coro, CoroWrapper):
        func = coro.func
        coro_name = coro.__qualname__
        if coro_name is not None:
            coro_name = '{0}()'.format(coro_name)
    else:
        func = coro

    if coro_name is None:
        coro_name = events._format_callback(func, ())

    try:
        coro_code = coro.gi_code
    except AttributeError:
        coro_code = coro.cr_code

    try:
        coro_frame = coro.gi_frame
    except AttributeError:
        coro_frame = coro.cr_frame

    filename = coro_code.co_filename
    if (isinstance(coro, CoroWrapper)
    and not inspect.isgeneratorfunction(coro.func)
    and coro.func is not None):
        filename, lineno = events._get_function_source(coro.func)
        if coro_frame is None:
            coro_repr = ('%s done, defined at %s:%s'
                         % (coro_name, filename, lineno))
        else:
            coro_repr = ('%s running, defined at %s:%s'
                         % (coro_name, filename, lineno))
    elif coro_frame is not None:
        lineno = coro_frame.f_lineno
        coro_repr = ('%s running at %s:%s'
                     % (coro_name, filename, lineno))
    else:
        lineno = coro_code.co_firstlineno
        coro_repr = ('%s done, defined at %s:%s'
                     % (coro_name, filename, lineno))

    return coro_repr

class FromWrapper(object):
    __slots__ = ('obj',)

    def __init__(self, obj):
        if isinstance(obj, FromWrapper):
            obj = obj.obj
            assert not isinstance(obj, FromWrapper)
        self.obj = obj

def From(obj):
    if not _DEBUG:
        return obj
    else:
        return FromWrapper(obj)


text:
<?php
/**
 * This file is part of the "litgroup/sms" package.
 *
 * (c) Roman Shamritskiy <roman@litgroup.ru>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Test\LitGroup\Sms\Exception\Exception;

use LitGroup\Sms\Exception\GatewayException;

class GatewayExceptionTest extends \PHPUnit_Framework_TestCase
{
    const MESSAGE = 'Some message';

    /**
     * @test
     */
    public function messageMustBeGiven()
    {
        $e = new GatewayException(self::MESSAGE);
        $this->assertSame(self::MESSAGE, $e->getMessage());
    }

    /**
     * @test
     */
    public function previousExceptionMayBeAttached()
    {
        $prev = $this->getMock(\Exception::class, [], [], '', false, false);

        $e = new GatewayException(self::MESSAGE, $prev);
        $this->assertSame(self::MESSAGE, $e->getMessage());
        $this->assertSame($prev, $e->getPrevious());
    }
}


text:
package uk.ac.ed.portlets.almaportlet.data;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Represents a fine issued to a patron.
 *
 *  <fine href="http://127.0.0.1:7014/vxws/patron/252470/circulationActions/debt/fines/1517083?patron_homedb=1@EDDB20020903165307">
 *    <fineId>1517083</fineId>
 *    <fineDate>2013-10-14</fineDate>
 *    <itemTitle>One flew over the cuckoo's nest / a novel by Ken Kesey.</itemTitle>
 *    <fineType>Overdue</fineType>
 *    <amount>GBP 5.00</amount>
 *    <dbKey>EDDB20020903165307</dbKey>
 *    <dbName>Edinburgh University Librar></dbName>
 *  </fine>
 *
 */
@XmlRootElement(name = "fine")
@XmlAccessorType(XmlAccessType.FIELD)
public class Fine {
    @XmlAttribute(name = "href")
    private String href;

    @XmlElement(name = "fineId")
    private String fineId;

    @XmlElement(name = "fineDate")
    private String fineDate;

    @XmlElement(name = "itemTitle")
    private String itemTitle;

    @XmlElement(name = "fineType")
    private String fineType;

    @XmlElement(name = "amount")
    private String amount;

    @XmlElement(name = "dbKey")
    private String dbKey;

    @XmlElement(name = "dbName")
    private String dbName;

    /**
     * @return the ID of the fine.
     */
    public String getFineId() {
        return fineId;
    }

    /**
     * @return the date the fine was issued on.
     */
    public String getFineDate() {
        return fineDate;
    }

    @JsonProperty("fineDateConverted")
    public String getFineDateConverted() throws ParseException{
        Date date = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(fineDate);
        return new SimpleDateFormat("dd-MM-yyyy",Locale.ENGLISH).format(date);
    }

    /**
     * @return the itemTitle
     */
    public String getItemTitle() {
        return itemTitle;
    }

    /**
     * @return the fineType
     */
    public String getFineType() {
        return fineType;
    }

    /**
     * @return the amount
     */
    public String getAmount() {
        return amount;
    }

    /**
     * @return the dbKey
     */
    public String getDbKey() {
        return dbKey;
    }

    /**
     * @return the dbName
     */
    public String getDbName() {
        return dbName;
    }

    /**
     * @return the href
     */
    public String getHref() {
        return href;
    }

    public void setHref(String href) {
        this.href = href;
    }

    public void setFineId(String fineId) {
        this.fineId = fineId;
    }

    public void setFineDate(String fineDate) {
        this.fineDate = fineDate;
    }

    public void setItemTitle(String itemTitle) {
        this.itemTitle = itemTitle;
    }

    public void setFineType(String fineType) {
        this.fineType = fineType;
    }

    public void setAmount(String amount) {
        this.amount = amount;
    }

    public void setDbKey(String dbKey) {
        this.dbKey = dbKey;
    }

    public void setDbName(String dbName) {
        this.dbName = dbName;
    }

}


text:
/**
 * Abstract implementations of processors for Groovy support.
 */
package org.openksavi.sponge.groovy;


text:
#include "config.h"
#include "RandomNumber.h"

#include "CryptographicallyRandomNumber.h"
#include "RandomNumberSeed.h"

#include <limits>
#include <limits.h>
#include <stdint.h>
#include <stdlib.h>

namespace WTF {

double randomNumber()
{
    uint32_t bits = cryptographicallyRandomNumber();
    return static_cast<double>(bits) / (static_cast<double>(std::numeric_limits<uint32_t>::max()) + 1.0);
}

}


text:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require("./logger");

var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');

var routes = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
logger.debug("Overriding 'Express' logger");
app.use(require('morgan')('combined',{ "stream": logger.stream }));
// app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// MOVE FROM HERE TO A MODULE

function checkForRenditions(err) {
    if (err) {
        logger.error('error: ' + err);
        return;
    }
    logger.info('checking for renditions to cut');
}

// TO HERE

setInterval(checkForRenditions, 1000);

app.use(function(req,res,next){
    req.db = db;
    req.logger = logger;
    next();
});

app.use('/', routes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;


text:
layout: post
title: DNE 27 - Especial Nerd Marco Gomes
cast: 232845949-devnaestrada-devnaestrada-27-especial-nerd-marco-gomes.mp3
cast-length: "53616635"
cast-time: "01:29:21"
description: "Fundador da boo-box e Mova Mais, Marco Gomes nos conta sua incrível trajetória de menino do Gama a dono de startup. Uma história muito inspiradora e bacana, que nos ensina a não desistir e sempre correr atrás dos nossos sonhos."
soundcloud-id: "232845949"
soundcloud-post-image: "000135984395-ti74sz"
---

Fundador da boo-box e Mova Mais, Marco Gomes nos conta sua incrível trajetória de menino do Gama a dono de startup. Uma história muito inspiradora e bacana, que nos ensina a não desistir e sempre correr atrás dos nossos sonhos.

[Marco Gomes](http://marcogomes.com)

[Boo-box](http://boo-box.com/)

[Mova Mais](http://movamais.com)

[POST Techcrunch](http://techcrunch.com/2007/01/21/boobox-to-help-bloggers-sell-stuff/)

[FTPI Digital](http://ftpidigital.com.br/)

[Venha para o SorocabaJS](http://sorocabajs.github.io/)

[Curta a Fanpage do DevNaEstrada](https://www.facebook.com/devnaestrada)

[Venha no Front in Sampa 21/11](http://frontinsampa.com.br/)


text:
module Web.TED.Types
  ( Cue(..)
  , Paragraph(..)
  , Transcript(..)
  , transcriptToText
  ) where

import           Data.Aeson
import           Data.Text  (Text)
import qualified Data.Text  as T
import           RIO

data Cue = Cue
    { time :: Int
    , text :: Text
    } deriving (Generic, Show)
instance FromJSON Cue

data Paragraph = Paragraph
    { cues :: [Cue]
    } deriving (Generic, Show)
instance FromJSON Paragraph

data Transcript = Transcript
    { paragraphs :: [Paragraph]
    } deriving (Generic, Show)
instance FromJSON Transcript

transcriptToText :: Transcript -> Text
transcriptToText (Transcript ps) =
    T.intercalate "\n" $ map (
      \(Paragraph cues) -> T.intercalate " " $ map (T.replace "\n" " " . text) cues) ps


text:
package org.knowm.xchange.bleutrade.service;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;

public class WithdrawRecord extends DepositRecord {
  public final String transactionId;

  public WithdrawRecord(
      @JsonProperty("Id") String id,
      @JsonProperty("TimeStamp") String timestamp,
      @JsonProperty("Amount") BigDecimal amount,
      @JsonProperty("Label") String label,
      @JsonProperty("Coin") String coin,
      @JsonProperty("TransactionId") String transactionId) {
    super(id, timestamp, amount, label, coin);
    this.transactionId = transactionId;
  }

  @Override
  public String toString() {
    return "WithdrawRecord{"
        + "id='"
        + id
        + '\''
        + ", transactionId='"
        + transactionId
        + '\''
        + ", timestamp='"
        + timestamp
        + '\''
        + ", amount="
        + amount
        + ", label='"
        + label
        + '\''
        + ", coin='"
        + coin
        + '\''
        + '}';
  }
}


text:
'use strict';

var datascope = require('../src/datascope.js');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports['generateFakeData'] = {
    setUp: function(done) {
        // setup here
        done();
    },
    'generate 1000 random datapoints': function(test) {
        test.expect(2);
        // tests here
        var data = datascope.generateFakeData(1000);

        test.equal(data.length, 1000, 'generateFakeData should have generated 1000 records.');
        test.equal(Object.keys(data[0]).length, 8, 'generateFakeData should return 8 columns');
        test.done();
    },
};
exports['smooth'] = {
    'smooth 1000 datapoints': function(test) {
        test.expect(2);
        var data = datascope.generateFakeData(1000);

        var result = datascope.smooth(data, 'x1', 'y1', 100);
        console.log(result);
        test.equal(result.xAxis.length, 100, 'smooth should return xAxis of length 100.');
        test.equal(Object.keys(result.yFrequency).length, 1, 'smooth should return string results as well as numeric results');
        test.done();
    },
};


text:
{-# LANGUAGE UnboxedSums #-}
{-# LANGUAGE DataKinds #-}

module T15067 where

import Type.Reflection

floopadoop :: TypeRep (# Bool | Int #)
floopadoop = typeRep


text:
package shadow.core;

import javax.sql.DataSource;

import shadow.exceptions.NotValidPersistentClassException;

public class PersistentContextFactory{

	private DataSource dataSource;

	public PersistentContextFactory(DataSource ds){
		this.dataSource = ds;
	}

	public <T> PersistentContext<T> getPersistentContextFor(Class<T> c) throws NotValidPersistentClassException{
		return new PersistentContext<T>(this.dataSource, c);
	}
}


text:
package com.yunikov.commons;

import java.util.Objects;
import java.util.function.Supplier;

/**
 * Represents a object which can be lazily initialized. See
 * Lazy loading design pattern.
 *
 * @author yyunikov
 * @since 1.8
 */
public class Lazy<T> {

    private T obj;

    public Lazy() {
    }

    /**
     * Get's the object value lazily.
     *
     * @param lazySupplier supplier of lazy initialization function
     * @return value
     */
    public T get(final Supplier<? extends T> lazySupplier) {
        if (obj == null) {
            obj = lazySupplier.get();
        }

        return obj;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean equals(final Object object) {
        if (object instanceof Lazy) {
            final Lazy<?> lazy = (Lazy<?>) object;
            return Objects.equals(obj, lazy.obj);
        }

        return false;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int hashCode() {
        return Objects.hash(obj);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return obj.toString();
    }
}


text:
package com.google.debugging.sourcemap;

import com.google.common.collect.Lists;

import java.util.List;

/**
 * Class for parsing the line maps in SourceMap v2.
 *
 * @author johnlenz@google.com (John Lenz)
 * @author jschorr@google.com (Joseph Schorr)
 */
class SourceMapLineDecoder {

  /**
   * Decodes a line in a character map into a list of mapping IDs.
   */
  static List<Integer> decodeLine(String lineSource) {
    return decodeLine(new StringParser(lineSource));
  }

  private SourceMapLineDecoder() {}

  static LineEntry decodeLineEntry(String in, int lastId) {
    return decodeLineEntry(new StringParser(in), lastId);
  }

  private static LineEntry decodeLineEntry(StringParser reader, int lastId) {
    int repDigits = 0;

    // Determine the number of digits used for the repetition count.
    // Each "!" indicates another base64 digit.
    for (char peek = reader.peek(); peek == '!'; peek = reader.peek()) {
      repDigits++;
      reader.next(); // consume the "!"
    }

    int idDigits = 0;
    int reps = 0;
    if (repDigits == 0) {
      // No repetition digit escapes, so the next character represents the
      // number of digits in the id (bottom 2 bits) and the number of
      // repetitions (top 4 digits).
      char digit = reader.next();
      int value = addBase64Digit(digit, 0);
      reps = (value >> 2);
      idDigits = (value & 3);
    } else {
      char digit = reader.next();
      idDigits = addBase64Digit(digit, 0);

      int value = 0;
      for (int i = 0; i < repDigits; i++) {
        digit = reader.next();
        value = addBase64Digit(digit, value);
      }
      reps = value;
    }

    // Adjust for 1 offset encoding.
    reps += 1;
    idDigits += 1;

    // Decode the id token.
    int value = 0;
    for (int i = 0; i < idDigits; i++) {
      char digit = reader.next();
      value = addBase64Digit(digit, value);
    }
    int mappingId = getIdFromRelativeId(value, idDigits, lastId);
    return new LineEntry(mappingId, reps);
  }

  private static List<Integer> decodeLine(StringParser reader) {
    List<Integer> result = Lists.newArrayListWithCapacity(512);
    int lastId = 0;
    while (reader.hasNext()) {
      LineEntry entry = decodeLineEntry(reader, lastId);
      lastId = entry.id;

      for (int i=0; i < entry.reps; i++) {
        result.add(entry.id);
      }
    }

    return result;
  }

  /**
   * Build base64 number a digit at a time, most significant digit first.
   */
  private static int addBase64Digit(char digit, int previousValue) {
    return (previousValue * 64) + Base64.fromBase64(digit);
  }

  /**
   * @return the id from the relative id.
   */
  static int getIdFromRelativeId(int rawId, int digits, int lastId) {
    // The value range depends on the number of digits
    int base = 1 << (digits * 6);
    return ((rawId >= base/2) ? rawId - base : rawId) + lastId;
  }

  /**
   * Simple class for tracking a single entry in a line map.
   */
  static class LineEntry {
    final int id;
    final int reps;
    public LineEntry(int id, int reps) {
      this.id = id;
      this.reps = reps;
    }
  }

  /**
   * A simple class for maintaining the current location
   * in the input.
   */
  static class StringParser {
    final String content;
    int current = 0;

    StringParser(String content) {
      this.content = content;
    }

    char next() {
      return content.charAt(current++);
    }

    char peek() {
      return content.charAt(current);
    }

    boolean hasNext() {
      return current < content.length() -1;
    }
  }
}


text:
function setMfcFlowRate(debug,olfactometerH,slave,mfcID,percentOfCapacity)
% olfactometerH = olfactometerAccess.setMfcFlowRate(debug)
% Not coded yet.
% Establishes a connection to the LASOM and returns the activeX control
% handle "olfactometerH". If no connection is posible, throws an error.
% In testing mode it will return [].
%
% lorenzpammer 2012/07

%% Set global variables

global olfStimTestMode

%% Check arguments to function

if nargin < 5
    errormsg = sprintf('Not enough input arguments. Olfactometer handle, slave, number of MFC and\npercentage of maximum capacity to set have to be provided to set the MFC flow rate.');
    error(errormsg)
end

%% See whether we're in test mode

% if in test mode, don't interact with the olfactometer.
if olfStimTestMode
    return
end

%% Set the flow rates of the mass flow controller

invoke(olfactometerH,'SetMfcFlowRate',slave,mfcID,percentOfCapacity);

end