text:
from django.db import models, transaction
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from taggit.models import TaggedItemBase
from slugify import slugify as unislugify
from taggit_autosuggest.managers import TaggableManager
from entities.models import Entity

MAX_LENGTH_Q_SUBJECT = 140
MAX_LENGTH_Q_CONTENT = 255
MAX_LENGTH_A_SUBJECT = 80
MAX_LENGTH_A_CONTENT = 500

class BaseModel(models.Model):
    ''' just a common time base for the models
    '''
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

# TODO: next class looks silly, do we really need it?
class TaggedQuestion(TaggedItemBase):
    content_object = models.ForeignKey("Question")
    sites = models.ManyToManyField(Site)
    # objects = models.Manager()
    # objects = CurrentSiteManager()

class Question(BaseModel):

    # TODO: rename to just `slug`
    unislug = models.CharField(
        _('unicode slug'),
        max_length=MAX_LENGTH_Q_SUBJECT,
        null=True,
        blank=True,
        editable=False
    )
    author = models.ForeignKey(User, related_name="questions", verbose_name=_("author"))
    subject = models.CharField(_("question"), max_length=MAX_LENGTH_Q_SUBJECT)
    content = models.TextField(_("details"), max_length=MAX_LENGTH_Q_CONTENT,
       help_text=_("Please enter your content in no more than %s letters") % MAX_LENGTH_Q_CONTENT,
       blank = True, default = '')
    rating = models.IntegerField(_("rating"), default=1)
    flags_count = models.IntegerField(_("flags counter"), default=0)
    tags = TaggableManager(through=TaggedQuestion)
    # tags = TaggableManager(through=TaggedQuestion, blank=True)
    sites = models.ManyToManyField(Site)
    # for easy access to current site questions
    objects = models.Manager()
    on_site = CurrentSiteManager()
    entity = models.ForeignKey(Entity, null=True, related_name="questions")

    class Meta:
        unique_together = ('unislug','entity')

    def __unicode__(self):
        return self.subject

    def can_answer(self, user):
        ''' Can a given user answer self? '''
        if user.is_authenticated():
            profile = user.profile
            return profile.is_candidate and profile.locality==self.entity
        else:
            return False

    def get_absolute_url(self):
        return reverse('question_detail', kwargs=dict(
                            entity_slug=self.entity.slug,
                            slug=self.unislug,
                            )
                      )

    def save(self, **kwargs):
        # make a unicode slug from the subject
        self.unislug = unislugify(self.subject)
        return super(Question, self).save(**kwargs)

    @transaction.commit_on_success
    def flagged(self):
        self.flags_count += 1
        self.save()
        return self.flags_count

class Answer(BaseModel):
    author = models.ForeignKey(User, related_name="answers", verbose_name=_("author"))
    content = models.TextField(_("content"), max_length=MAX_LENGTH_A_CONTENT,
        help_text=_("Please enter an answer in no more than %s letters") % MAX_LENGTH_A_CONTENT)
    rating = models.IntegerField(_("rating"), default=0)
    question = models.ForeignKey(Question, related_name="answers", verbose_name=_("question"))
    sites = models.ManyToManyField(Site)
    # for easy access to current site answers
    objects = models.Manager()
    on_site = CurrentSiteManager()

    def __unicode__(self):
        return "%s: %s" % (self.author, self.content[:30])

    def get_absolute_url(self):
        return '%s#answer-%s' % (self.question.get_absolute_url(), self.id)

class QuestionUpvote(BaseModel):
    question = models.ForeignKey(Question, related_name="upvotes")
    user = models.ForeignKey(User, related_name="upvotes")

class QuestionFlag(BaseModel):
    question = models.ForeignKey(Question, related_name="flags")
    reporter = models.ForeignKey(User, related_name="flags")

''' signals code, to ensure correct site is saved
'''
@receiver(post_save)
def saved(sender, created, instance, **kwargs):
    if sender in (Question, Answer, TaggedQuestion):
        instance.sites.add(Site.objects.get_current())


text:
NSString *const LOC1 = @"Current location";
NSString *const LOC2 = @"Less than a quarter mile";
NSString *const LOC3 = @"Less than half a mile";
NSString *const LOC4 = @"Less than a mile";
NSString *const LOC5 = @"More than a mile";

@implementation ProjectConstants

@end

redpajama_set_name: RedPajamaGithub


text:
package com.devsmart.ubjson;

import java.util.Arrays;

public class UBStringArray extends UBArray {

    private static final long serialVersionUID = 9049462290900317723L;
    private final String[] mArray;

    UBStringArray(String[] value) {
        mArray = value;
    }

    @Override
    public Type getType() {
        return Type.Array;
    }

    @Override
    public boolean isStronglyTyped() {
        return true;
    }

    public ArrayType getStrongType() {
        return ArrayType.String;
    }

    @Override
    public int size() {
        return mArray.length;
    }

    @Override
    public UBValue get(int index) {
        return UBValueFactory.createStringOrNull(mArray[index]);
    }

    public String[] getValues() {
        return mArray;
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(mArray);
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Cake.Common.Tests.Fixtures.Tools.DotNetCore.VSTest;
using Cake.Common.Tools.DotNetCore.VSTest;
using Cake.Common.Tools.VSTest;
using Cake.Core.IO;
using Cake.Testing;
using Xunit;

namespace Cake.Common.Tests.Unit.Tools.DotNetCore.VSTest
{
    public sealed class DotNetCoreVSTesterTests
    {
        public sealed class TheTestMethod
        {
            [Fact]
            public void Should_Throw_If_Settings_Are_Null()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture
                {
                    TestFiles = new[] { (FilePath)"./test/unit.tests.csproj" },
                    Settings = null
                };
                fixture.GivenDefaultToolDoNotExist();

                // When
                var result = Record.Exception(() => fixture.Run());

                // Then
                AssertEx.IsArgumentNullException(result, "settings");
            }

            [Fact]
            public void Should_Throw_If_Process_Was_Not_Started()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture { TestFiles = new[] { (FilePath)"./test/unit.tests.csproj" } };
                fixture.GivenProcessCannotStart();

                // When
                var result = Record.Exception(() => fixture.Run());

                // Then
                AssertEx.IsCakeException(result, ".NET Core CLI: Process was not started.");
            }

            [Fact]
            public void Should_Throw_If_Process_Has_A_Non_Zero_Exit_Code()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture { TestFiles = new[] { (FilePath)"./test/unit.tests.csproj" } };
                fixture.GivenProcessExitsWithCode(1);

                // When
                var result = Record.Exception(() => fixture.Run());

                // Then
                AssertEx.IsCakeException(result, ".NET Core CLI: Process returned an error (exit code 1).");
            }

            [Fact]
            public void Should_Add_Mandatory_Arguments()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture { TestFiles = new[] { (FilePath)"./test/unit.tests.csproj" } };

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("vstest \"/Working/test/unit.tests.csproj\"", result.Args);
            }

            [Fact]
            public void Should_Add_Multiple_Test_File_Arguments()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture
                {
                    TestFiles = new[]
                    {
                        (FilePath)"./test1/unit.tests.csproj",
                        (FilePath)"./test2/unit.tests.csproj",
                        (FilePath)"./test3/unit.tests.csproj",
                    }
                };

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("vstest \"/Working/test1/unit.tests.csproj\" \"/Working/test2/unit.tests.csproj\" \"/Working/test3/unit.tests.csproj\"", result.Args);
            }

            [Fact]
            public void Should_Quote_Test_File_Path()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture { TestFiles = new[] { (FilePath)"./test/cake unit tests/cake core tests.csproj" } };

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("vstest \"/Working/test/cake unit tests/cake core tests.csproj\"", result.Args);
            }

            [Fact]
            public void Should_Add_Settings_Argument()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture
                {
                    TestFiles = new[] { (FilePath)"./test/unit.tests.csproj" },
                    Settings = new DotNetCoreVSTestSettings
                    {
                        Settings = "./test/demo.runsettings"
                    }
                };

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("vstest \"/Working/test/unit.tests.csproj\" --Settings:\"/Working/test/demo.runsettings\"", result.Args);
            }

            [Fact]
            public void Should_Add_Tests_Argument()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture
                {
                    TestFiles = new[] { (FilePath)"./test/unit.tests.csproj" },
                    Settings = new DotNetCoreVSTestSettings
                    {
                        TestsToRun = new[] { "TestMethod1", "TestMethod2" }
                    }
                };

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("vstest \"/Working/test/unit.tests.csproj\" --Tests:TestMethod1,TestMethod2", result.Args);
            }

            [Fact]
            public void Should_Add_TestAdapter_Argument()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture
                {
                    TestFiles = new[] { (FilePath)"./test/unit.tests.csproj" },
                    Settings = new DotNetCoreVSTestSettings
                    {
                        TestAdapterPath = @"/Working/custom-test-adapter"
                    }
                };

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("vstest \"/Working/test/unit.tests.csproj\" --TestAdapterPath:\"/Working/custom-test-adapter\"", result.Args);
            }

            [Fact]
            public void Should_Add_Platform_Argument()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture
                {
                    TestFiles = new[] { (FilePath)"./test/unit.tests.csproj" },
                    Settings = new DotNetCoreVSTestSettings
                    {
                        Platform = VSTestPlatform.x64
                    }
                };

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("vstest \"/Working/test/unit.tests.csproj\" --Platform:x64", result.Args);
            }

            [Fact]
            public void Should_Add_Framework_Argument()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture
                {
                    TestFiles = new[] { (FilePath)"./test/unit.tests.csproj" },
                    Settings = new DotNetCoreVSTestSettings
                    {
                        Framework = "dnxcore50"
                    }
                };

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("vstest \"/Working/test/unit.tests.csproj\" --Framework:dnxcore50", result.Args);
            }

            [Fact]
            public void Should_Add_Parallel_Argument()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture
                {
                    TestFiles = new[] { (FilePath)"./test/unit.tests.csproj" },
                    Settings = new DotNetCoreVSTestSettings
                    {
                        Parallel = true
                    }
                };

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("vstest \"/Working/test/unit.tests.csproj\" --Parallel", result.Args);
            }

            [Fact]
            public void Should_Add_TestCaseFilter_Argument()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture
                {
                    TestFiles = new[] { (FilePath)"./test/unit.tests.csproj" },
                    Settings = new DotNetCoreVSTestSettings
                    {
                        TestCaseFilter = "FullyQualifiedName~Cake.Common.Core.DotNetCore"
                    }
                };

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("vstest \"/Working/test/unit.tests.csproj\" --TestCaseFilter:\"FullyQualifiedName~Cake.Common.Core.DotNetCore\"", result.Args);
            }

            [Fact]
            public void Should_Add_Logger_Argument()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture
                {
                    TestFiles = new[] { (FilePath)"./test/unit.tests.csproj" },
                    Settings = new DotNetCoreVSTestSettings
                    {
                        Logger = @"trx;LogFileName=/Working/logfile.trx"
                    }
                };

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("vstest \"/Working/test/unit.tests.csproj\" --logger:\"trx;LogFileName=/Working/logfile.trx\"", result.Args);
            }

            [Fact]
            public void Should_Add_ParentProcessId_Argument()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture
                {
                    TestFiles = new[] { (FilePath)"./test/unit.tests.csproj" },
                    Settings = new DotNetCoreVSTestSettings
                    {
                        ParentProcessId = @"100"
                    }
                };

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("vstest \"/Working/test/unit.tests.csproj\" --ParentProcessId:100", result.Args);
            }

            [Fact]
            public void Should_Add_Port_Argument()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture
                {
                    TestFiles = new[] { (FilePath)"./test/unit.tests.csproj" },
                    Settings = new DotNetCoreVSTestSettings
                    {
                        Port = 8000
                    }
                };

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("vstest \"/Working/test/unit.tests.csproj\" --Port:8000", result.Args);
            }

            [Fact]
            public void Should_Add_Diag_Argument()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture
                {
                    TestFiles = new[] { (FilePath)"./test/unit.tests.csproj" },
                    Settings = new DotNetCoreVSTestSettings
                    {
                        DiagnosticFile = "./artifacts/logging/diagnostics.txt"
                    }
                };

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("vstest \"/Working/test/unit.tests.csproj\" --Diag:\"/Working/artifacts/logging/diagnostics.txt\"", result.Args);
            }

            [Fact]
            public void Should_Add_ResultsDirectory_Argument()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture
                {
                    TestFiles = new[] { (FilePath)"./test/unit.tests.csproj" },
                    Settings = new DotNetCoreVSTestSettings
                    {
                        ResultsDirectory = "./artifacts/TestResults"
                    }
                };

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("vstest \"/Working/test/unit.tests.csproj\" --ResultsDirectory:\"/Working/artifacts/TestResults\"", result.Args);
            }

            [Fact]
            public void Should_Add_Extra_Argument()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture
                {
                    TestFiles = new[] { (FilePath)"./test/unit.tests.csproj" },
                    Settings = new DotNetCoreVSTestSettings
                    {
                        Arguments =
                        {
                            { "Arg1", "Value1" },
                            { "Arg2", "Value2" },
                        }
                    }
                };

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("vstest \"/Working/test/unit.tests.csproj\" Arg1:\"Value1\" Arg2:\"Value2\"", result.Args);
            }

            [Fact]
            public void Should_Add_Host_Arguments()
            {
                // Given
                var fixture = new DotNetCoreVSTesterFixture { TestFiles = new[] { (FilePath)"./test/unit.tests.csproj" } };
                fixture.Settings.DiagnosticOutput = true;

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("--diagnostics vstest \"/Working/test/unit.tests.csproj\"", result.Args);
            }
        }
    }
}


text:
package org.mutabilitydetector.asmoverride;

import org.mutabilitydetector.classloading.AnalysisClassLoader;
import org.objectweb.asm.tree.analysis.BasicValue;
import org.objectweb.asm.tree.analysis.Interpreter;
import org.objectweb.asm.tree.analysis.SimpleVerifier;

public class ClassLoadingVerifierFactory implements AsmVerifierFactory {

    private final AnalysisClassLoader classLoader;

    public ClassLoadingVerifierFactory(AnalysisClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    @Override
    public Interpreter<BasicValue> interpreter() {
        SimpleVerifier simpleVerifier = new SimpleVerifier();
        simpleVerifier.setClassLoader(new ClassLoader() {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                return classLoader.loadClass(name);
            }
        });
        return simpleVerifier;
    }

}


text:
using System;

namespace MaxEqualSequence
{
    class MaxEqualSequence
    {
        static void Main()
        {
            /*Uslovie
             * 4. Write a program that finds the maximal sequence of equal elements in an array.
        	 * Example: {2, 1, 1, 2, 3, 3, 2, 2, 2, 1} -> {2, 2, 2}.
            */
            Console.Write("Input lenght of the sequence: ");
            int sequenceLength = int.Parse(Console.ReadLine());
            int[] sequence = new int[sequenceLength];
            for (int i = 0; i < sequenceLength; i++)
            {
                Console.Write("Input element in sequence: ");
                sequence[i] = int.Parse(Console.ReadLine());
            }
            int equalSequenceLength = 1;
            int equalSequenceBeginning = 0;
            int maxSequenceLength = 1;
            int maxSequenceBeginning = 0;
            for (int i = 1; i < sequence.Length; i++)
            {
                if (sequence[i - 1] != sequence[i])
                {
                    equalSequenceLength = 1;
                    equalSequenceBeginning = i;
                }
                else
                {
                    equalSequenceLength++;
                    if (equalSequenceLength > maxSequenceLength)
                    {
                        maxSequenceLength = equalSequenceLength;
                        maxSequenceBeginning = equalSequenceBeginning;
                    }
                }
            }
            if (maxSequenceLength == 1)
            {
                Console.WriteLine("There is no maximal sequence of equal elements.");
            }
            else
            {
                Console.Write("The maximal sequence of equal elements is: {");
                for (int i = maxSequenceBeginning; i < maxSequenceBeginning + maxSequenceLength; i++)
                {
                    if (i < maxSequenceLength + maxSequenceBeginning - 1)
                    {
                        Console.Write(sequence[i] + ", ");
                    }
                    else
                    {
                        Console.WriteLine(sequence[i] + "}");
                    }
                }
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<com.sothree.slidinguppanel.SlidingUpPanelLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:sothree="http://schemas.android.com/apk/res-auto"
    android:id="@+id/sliding_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom"
    sothree:umanoPanelHeight="72dp"
    sothree:umanoShadowHeight="4dp"
    sothree:umanoAnchorPoint="0.5"
    tools:context=".MapsActivity">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment" />

    <include layout="@layout/sliding_panel" />
</com.sothree.slidinguppanel.SlidingUpPanelLayout>


text:
<?php
Library::import('recess.database.orm.Model');
Library::import('recess.apps.ide.models.RecessReflectorClassProperties');
Library::import('recess.apps.ide.models.RecessReflectorClassMethods');

/**
 * !BelongsTo package, Class: RecessReflectorPackage, Key: packageId
 * !BelongsTo parent, Class: RecessReflectorClass, Key: parentId
 * !HasMany children, Class: RecessReflectorClass, Key: parentId
 * !Table recess_tools_classes
 */
class RecessReflectorClass extends Model {

	/** !Column PrimaryKey, Integer, AutoIncrement */
	public $id;

	/** !Column String */
	public $name;

	/**
	 * !Column Integer
	 */
	public $parentId;

	/**
	 * !Column Integer
	 */
	public $packageId;

	/** !Column Text */
	public $docComment;

	/** !Column Text */
	public $file;

	public function fromClass($class, $dir = '') {

		$classInfo = new RecessReflectionClass($class);

		$this->docComment = $classInfo->getDocComment();

		$this->file = $classInfo->getFileName();

		$package = Library::getPackage($class);

		if($dir != '') {
			if(strpos($dir, '/' . str_replace('.','/',$package)) !== 0) {
				throw new RecessException('The class: ' . $class . ' has been imported incorectly with ' . $package . '.' . $class . '. The real location is: ' . $dir, get_defined_vars());
			}
		}

		if($package != '') {
			$packageReflector = new RecessReflectorPackage();

			$packageReflector->name = $package;

			if($packageReflector->exists()) {
				$this->setPackage($packageReflector);
			} else {
				$packageReflector->insert();
				$this->setPackage($packageReflector);
			}
		}

		$this->save();

		$parent = $classInfo->getParentClass();

		if($parent != null) {
			$parentReflectorClass = new RecessReflectorClass();
			$parentReflectorClass->name = $parent->name;
			$exists = $parentReflectorClass->find()->first();
			if(!$exists) {
				$parentReflectorClass->fromClass($parent->name);
				$this->setParent($parentReflectorClass);
			} else {
				$this->setParent($exists);
			}
		}

	}

}
?>


text:
package com.googlecode.charts4j.collect;

import static com.googlecode.charts4j.collect.Preconditions.checkContentsNotNull;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * Lists static factory class.
 *
 * @author Julien Chastang (julien.c.chastang at gmail dot com)
 *
 */
public final class Lists {

    /**
     * Static factory class can never be instantiated.
     */
    private Lists() {
        throw new AssertionError();
    }

    /**
     * Static factory method to instantiate a LinkedList.
     *
     * @param <E>
     *            Type parameter for list.
     *
     * @return A newly instantiated LinkedList of type E.
     */
    public static <E> List<E> newLinkedList() {
        return new LinkedList<E>();
    }

    /**
     * Static factory method to instantiate an ArrayList.
     *
     * @param <E>
     *            Type parameter for list.
     *
     * @return A newly instantiated ArrayList of type E.
     */
    public static <E> List<E> newArrayList() {
        return new LinkedList<E>();
    }

    /**
     * Given a vararg, return an immutable list.
     *
     * @param <E>
     *            Type parameter for list.
     * @param a
     *            the vararg list
     * @return an immutable list given the vararg.
     */
    public static <E> ImmutableList<E> of(final E... a) {
        return new ImmutableList<E>(Arrays.asList(a));
    }

    /**
     * A shallow copy of a list.
     *
     * @param <E>
     *            Type parameter for list.
     * @param list
     *            list to copy
     * @return an immutable list given the list
     */
    public static <E> ImmutableList<E> copyOf(final List<? extends E> list) {
        checkContentsNotNull(list, "list cannnot be null");
        final List<E> l = Lists.newLinkedList();
        for (E e : list) {
            l.add(e);
        }
        return new ImmutableList<E>(list);
    }
}


text:
class AddEstimatedDurationToBuildJob < ActiveRecord::Migration[5.0]
  def change
    add_column :build_jobs, :estimated_duration, :integer, default: 0
  end
end


text:
function d = displaySet(d,parm,val,varargin)
% Set display structure values
%
%   d = displaySet(d,parm,val,varargin)
%
% Parameters
%   name               - display name
%   gTable             - gamma table
%   wave               - sample wavelength
%   spd                - spectral power distribution (average, not peak)
%   dpi                - dots per inch
%   dixel              - subpixel structure
%   viewing distance   - viewing distance
%   comment            - comments for this display
%   image              - Image data, typically RGB, to be rendered in the
%                        display window.
%
%   refresh rate       - Temporal refresh rate
%   pixels per dixel   - Spatial samples per dixel
%   dixel image        - The display pixel image showing the dixel
%   dixel control map  - Not sure
%   render function    - Not sure
%
% See also:
%   displayGet, displayCreate, ieLUTDigital, ieLUTLinear

% Examples:
%
%  d = displayCreate;
%  d = displaySet(d,'gTable',val)
%  d = displaySet(d,'gTable','linear');
%  d = displaySet(d,'name','My Display Type');
%

if notDefined('parm'), error('Parameter not found.');  end

% Convert parameter format
parm = ieParamFormat(parm);

switch parm
    case {'name'}
        d.name = val;
    case {'type'}
        d.type = val;
    case {'gtable','dv2intensity','gamma'}
        % d = displaySet(d,'gamma',val)
        % d = displaySet(d,'gamma','linear');
        % From digital values to primary intensity
        % Should be same number of columns as primaries
        if ischar(val) && strcmp(val, 'linear')
            % User just wants a linear gamma table
            sz = size(d.gamma,1);
            if ~isempty(varargin), sz = varargin{1}; end
            val = linspace(0,1,sz);
            val = repmat(val(:),1,displayGet(d, 'nprimaries'));
        end
        d.gamma = val;
    case {'wave','wavelength'}  %nanometers
        % d = displaySet(d,'wave',val);
        % Force column, interpolate SPD, and don't do anything if it turns
        % out that the current wave value is the same as sent in.
        if ~isfield(d, 'wave')
            d.wave = val(:);
        elseif ~isequal(val(:),d.wave)
            % disp('Interpolating display SPD for consistency with new wave.')
            spd = displayGet(d,'spd');
            wave = displayGet(d,'wave');
            newSPD = interp1(wave, spd, val(:), 'linear');
            d.wave = val(:);
            d = displaySet(d,'spd',newSPD);
        end

    case {'spd','spdprimaries'}
        % d = displaySet(d,'spd primaries',val);
        if ~ismatrix(val), error('unknown spd structure'); end
        if size(val,1) < size(val, 2), val = val'; end
        d.spd = val;

    case {'dpi'}
        % displaySet(d, 'dpi', val);
        % Dots per inch of the pixels (full pixel center-to-center)
        d.dpi = val;
    case {'viewingdistance'}
        % displaySet(d, 'viewing distance', val);
        % viewing distance in meters
        d.dist = val;
    case {'refreshrate'}
        % refresh rate of the display in Hz
        d.refreshRate = val;
    case {'dixel'}
        % displaySet(d, 'dixel', val)
        % dixel structure
        assert(isstruct(val), 'dixel should be a structure');
        d.dixel = val;
    case {'dixelintensitymap', 'dixelimage'}
        % dixel intensity map
        if size(val, 3) ~= displayGet(d, 'nprimaries')
            error('bad dixel intensity image size');
        end
        d.dixel.intensitymap = val;
    case {'dixelcontrolmap'}
        if size(val, 3) ~= displayGet(d, 'nprimaries')
            error('bad dixel control image size');
        end
        d.dixel.controlmap = val;
    case {'pixelsperdixel'}
        d.dixel.nPixels = val;
    case {'renderfunction'}
        d.dixel.renderFunc = val;
    case {'comment'}
        % comment for the display
        d.comment = val;
    case {'rgb','image'}
        d.image = val;

    otherwise
        error('Unknown parameter %s\n',parm);
end

end


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.Toolbar
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            android:layout_alignParentTop="true"
            android:id="@+id/toolbar"/>

        <FrameLayout
            android:layout_below="@+id/toolbar"
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </RelativeLayout>
</android.support.v4.widget.DrawerLayout>


text:
{-# LANGUAGE ConstraintKinds           #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts          #-}
{-# LANGUAGE GADTs                     #-}
{-# LANGUAGE LambdaCase                #-}
{-# LANGUAGE PatternSynonyms           #-}
{-# LANGUAGE RankNTypes                #-}
{-# LANGUAGE ScopedTypeVariables       #-}
{-# LANGUAGE StandaloneDeriving        #-}
{-# LANGUAGE NoStarIsType              #-}
{-# LANGUAGE TypeInType                #-}
{-# LANGUAGE TypeOperators             #-}
{-# LANGUAGE ViewPatterns              #-}

-- |
-- Module      : GHC.TypeLits.Witnesses
-- Copyright   : (c) Justin Le 2016
-- License     : MIT
-- Maintainer  : justin@jle.im
-- Stability   : unstable
-- Portability : non-portable
--
-- This module essentially provides a lightweight subset of the
-- /singletons/ library specifically for 'Nat' and 'Symbol', from
-- "GHC.TypeLits".
--
-- Its main functionality is for first-class manipulation of 'KnownNat' and
-- 'KnownSymbol' constraints.  For example, in general, if you have
-- @'KnownNat' n@, GHC can't infer @'KnownNat' (n + 1)@.  And, if you have
-- both @'KnownNat' n@ and @'KnownNat' m@, GHC can't infer @'KnownNat (n
-- + m)@.
--
-- This can be annoying when dealing with libraries and applications where
-- one regularly adds and subtracts type-level nats and expects 'KnownNat'
-- instances to follow.  For example, vector concatenation of
-- length-encoded vector types can be:
--
-- @
-- concat :: ('KnownNat' n, 'KnownNat' m) => Vector n a -> Vector m a -> Vector (n + m) a
-- @
--
-- But, now @n + m@ does not have a 'KnownNat' instance...which makes
-- operations like this much less useful.
--
-- Usually, the easiest way to get around this is to use a typechecker
-- plugin, like
-- <https://hackage.haskell.org/package/ghc-typelits-knownnat>.  However,
-- we can do this without the help of a typechecker plugin using
-- first-class values, at the cost of some increased verbosity.
--
-- We introduce @'SNat' n@, which is a term-level witness of knownnat-ness
-- that can be manipulated as a first-class value.
--
-- If we have @'KnownNat' n@, we can construct an @'SNat' n@:
--
-- @
-- 'SNat' :: KnownNat n -> SNat n
-- @
--
-- Furthermore, if we have an @'SNat' n@, we can /pattern match/ on the
-- 'SNat' constructor to get a @'KnownNat' n@ constraint:
--
-- @
-- myFunc :: SNat n -> Bool
-- myFunc SNat = ...  -- in this body, we have `KnownNat n`
-- @
--
-- So if we have @'KnownNat' n@ and @'KnownNat' m@, we can get @'KnownNat'
-- (n + m)@ by using '%+', which adds together 'SNat's:
--
-- @
-- case (SNat :: SNat n) %+ (SNat :: SNat m) of
--   SNat -> -- in this branch, we have `KnownNat (n + m)`
-- @
--
-- Note that this module converts between 'SNat' and 'Natural', and not
-- 'SNat' and 'Integer', in "GHC.TypeNats"-style.
--
-- Of course, all of this functionality is provided by the /singletons/
-- library, in "Data.Singletons.TypeLits".  This module can be useful if
-- you want a lightweight alternative without the full might of
-- /singletons/.  The main benefit of the /singletons/ library is providing
-- a unified interface for singletons of /all/ different kinds/types, and
-- not just 'Natural' and 'String'.
module GHC.TypeLits.Witnesses (
  -- * Nats
    SNat(..)
  , SomeNat(SomeNat_)
  , Natural(FromSNat)
  , fromSNat
  , withKnownNat
  , withSomeNat
  , toSomeNat
  -- ** Operations
  , (%+)
  , (%-)
  , minusSNat
  , minusSNat_
  , (%*)
  , (%^)
  -- ** Compare
  , (%<=?)
  , sCmpNat
  -- ** Unsafe
  , unsafeLiftNatOp1
  , unsafeLiftNatOp2
  -- * Symbols
  , SSymbol(..)
  , SomeSymbol(SomeSymbol_)
  , pattern FromSSymbol
  , fromSSymbol
  , withKnownSymbol
  , withSomeSymbol
  , toSomeSymbol
  ) where

import           Data.GADT.Compare
import           Data.GADT.Show
import           Data.Proxy
import           Data.Type.Equality
import           GHC.Natural
import           GHC.TypeLits hiding         (natVal, someNatVal)
import           GHC.TypeLits.Compare hiding ((%<=?))
import           GHC.TypeNats
import           Unsafe.Coerce
import qualified GHC.TypeLits.Compare        as Comp

-- | An @'SNat' n@ is a witness for @'KnownNat' n@.
--
-- This means that if you pattern match on the 'SNat' constructor, in that
-- branch you will have a @'KnownNat' n@ constraint.
--
-- @
-- myFunc :: SNat n -> Bool
-- myFunc SNat = ...  -- in this body, we have `KnownNat n`
-- @
--
-- This is essentially a singleton for 'Nat', and stands in for the
-- /singletons/ 'SNat' and 'Data.Singleton.Sing' types.
data SNat n = KnownNat n => SNat

deriving instance Eq (SNat n)
deriving instance Ord (SNat n)

instance Show (SNat n) where
    showsPrec d x@SNat = showParen (d > 10) $
      showString "SNat @" . showsPrec 11 (fromSNat x)

instance GShow SNat where
    gshowsPrec = showsPrec

instance TestEquality SNat where
    testEquality (SNat :: SNat n) (SNat :: SNat m) =
      flip fmap (sameNat (Proxy :: Proxy n) (Proxy :: Proxy m)) $ \case
        Refl -> Refl

instance GEq SNat where
    geq = testEquality

instance GCompare SNat where
    gcompare x = cmpNatGOrdering . sCmpNat x

data SomeNat__ = forall n. SomeNat__ (SNat n)

-- | A useful pattern synonym for matching on a 'SomeNat' as if it
-- contained an @'SNat' n@, and not a @'Proxy' n@ as it exists in
-- "GHC.TypeLits".
--
-- A layer of compatibility letting us use the original 'SomeNat' type in
-- a way that works well with 'SNat'.
--
-- This stands in for the /singletons/ 'Data.Singleton.SomeSing' constructor.
pattern SomeNat_ :: SNat n -> SomeNat
pattern SomeNat_ x <- ((\case SomeNat (Proxy :: Proxy n) -> SomeNat__ (SNat :: SNat n)) -> SomeNat__ x)
  where
    SomeNat_ (SNat :: SNat n) = SomeNat (Proxy :: Proxy n)
{-# COMPLETE SomeNat_ #-}

-- | A useful pattern synonym for matching on a 'Natural' as if it "were"
-- a 'SNat':
--
-- @
-- myFunc :: Natural -> Bool
-- myFunc (FromSNat x) = ...  -- x is `SNat n`, with `n` coming from the input
-- @
--
-- It can be used as a function, as well, to convert an @'SNat' n@ back
-- into the 'Natural' that it represents.
--
-- This stands in for the /singletons/ 'Data.Singleton.FromSing' pattern synonym.
pattern FromSNat :: SNat n -> Natural
pattern FromSNat x <- ((\i -> withSomeNat i SomeNat_) -> SomeNat_ x)
  where
    FromSNat = fromSNat
{-# COMPLETE FromSNat #-}

-- | Given an @'SNat' n@ and a value that would require a @'KnownNat' n@
-- instance, create that value.
--
-- This stands in for the function of the same name from
-- "Data.Singletons.TypeLits".
withKnownNat :: SNat n -> (KnownNat n => r) -> r
withKnownNat SNat x = x

-- | Promote ("reify") a 'Natural' to an @'SNat' n@, by providing
-- a continuation that would handle it in a way that is polymorphic over
-- all possible @n@.
--
-- This stands in the /singletons/ 'Data.Singleton.withSomeSing' function.
withSomeNat :: Natural -> (forall n. SNat n -> r) -> r
withSomeNat (someNatVal->SomeNat (Proxy :: Proxy n)) x = x (SNat :: SNat n)

-- | Promote ("reify") a 'Natural' to an @'SNat' n@ existentially hidden
-- inside a 'SomeNat'.  To use it, pattern match using 'SomeNat_'.
--
-- This stands in the /singletons/ 'Data.Singleton.toSomeSing' function.
toSomeNat :: Natural -> SomeNat
toSomeNat = someNatVal

-- | Convert ("reflect") an 'SNat' back into the 'Natural' it represents.
--
-- This stands in the /singletons/ 'Data.Singleton.fromSing' function.
fromSNat :: SNat n -> Natural
fromSNat x@SNat = natVal x

-- | Lift a unary operation to act on an @'SNat' n@ that returns an @'SNat'
-- m@.  The function given must properly describe the relationship between
-- @n@ and @m@.
--
-- For example:
--
-- @
-- double :: SNat n -> SNat (n * 2)
-- double = unsafeLiftNatOp1 (*2)
-- @
--
-- The correctness of the relationship is not checked, so be aware that
-- this can cause programs to break.
unsafeLiftNatOp1
    :: (Natural -> Natural)
    -> SNat n
    -> SNat m
unsafeLiftNatOp1 f x = withSomeNat (f (fromSNat x)) unsafeCoerce

-- | Lift a binary operation to act on an @'SNat' n@ and @'SNat' m@ that
-- returns an @'SNat' o@.  The function given must properly describe the
-- relationship between @n@, @m@, and @o@.
--
-- For example:
--
-- @
-- multiply :: SNat n -> SNat m -> SNat (n * m)
-- multiply = unsafeLiftNatOp2 (*)
-- @
--
-- The correctness of the relationship is not checked, so be aware that
-- this can cause programs to break.
unsafeLiftNatOp2
    :: (Natural -> Natural -> Natural)
    -> SNat n
    -> SNat m
    -> SNat o
unsafeLiftNatOp2 f x y = withSomeNat (f (fromSNat x) (fromSNat y)) unsafeCoerce

-- | Addition of 'SNat's.
--
-- This also will provide the correct 'KnownNat' instance for @'SNat' (n
-- + m)@, so can be used as a way to "add" 'KnownNat' instances.
--
-- This stands in for the function with the same name from
-- "Data.Singletons.Prelude.Num".
(%+) :: SNat n -> SNat m -> SNat (n + m)
(%+) = unsafeLiftNatOp2 (+)

-- | Subtraction of 'SNat's.  Note that this is unsafe, as will trigger
-- a run-time underflow if @m@ is bigger than @n@ even though it will always
-- succeed at compiletime.
--
-- This also will provide the correct 'KnownNat' instance for @'SNat' (n
-- - m)@, so can be used as a way to "subtract" 'KnownNat' instances.
--
-- This stands in for the function with the same name from
-- "Data.Singletons.Prelude.Num".
(%-) :: SNat n -> SNat m -> SNat (n - m)
(%-) = unsafeLiftNatOp2 (-)

-- | A safe version of '%-': it will return 'Left' if @n@ is less than @m@
-- (with a witness that it is), or else return the subtracted 'SNat' in
-- 'Right' in a way that is guarunteed to not have runtime underflow.
minusSNat
    :: SNat n
    -> SNat m
    -> Either (CmpNat n m :~: 'LT) (SNat (n - m))
minusSNat (fromSNat->x) (fromSNat->y) = case minusNaturalMaybe x y of
    Nothing -> Left (unsafeCoerce Refl)
    Just z  -> withSomeNat z unsafeCoerce

-- | A version of 'minusSNat' that just returns a 'Maybe'.
minusSNat_ :: SNat n -> SNat m -> Maybe (SNat (n - m))
minusSNat_ x = either (const Nothing) Just . minusSNat x

-- | Multiplication of 'SNat's.
--
-- This also will provide the correct 'KnownNat' instance for @'SNat' (n
-- * m)@, so can be used as a way to "multiply" 'KnownNat' instances.
--
-- This stands in for the function with the same name from
-- "Data.Singletons.Prelude.Num".
(%*) :: SNat n -> SNat m -> SNat (n * m)
(%*) = unsafeLiftNatOp2 (*)

-- | Exponentiation of 'SNat's.
--
-- This also will provide the correct 'KnownNat' instance for @'SNat' (n
-- ^ m)@, so can be used as a way to "exponentiate" 'KnownNat' instances.
--
-- This stands in for the function with the same name from
-- "Data.Singletons.TypeLits".
(%^) :: SNat n -> SNat m -> SNat (n ^ m)
(%^) = unsafeLiftNatOp2 (^)

-- | Compare @n@ and @m@, categorizing them into one of the constructors of
-- ':<=?'.
(%<=?) :: SNat n -> SNat m -> n :<=? m
x@SNat %<=? y@SNat = x Comp.%<=? y

-- | Compare @n@ and @m@, categorizing them into one of the constructors of
-- 'SCmpNat'.
sCmpNat :: SNat n -> SNat m -> SCmpNat n m
sCmpNat x@SNat y@SNat = cmpNat x y

-- | An @'SSymbol' n@ is a witness for @'KnownSymbol' n@.
--
-- This means that if you pattern match on the 'SSymbol' constructor, in that
-- branch you will have a @'KnownSymbol' n@ constraint.
--
-- @
-- myFunc :: SSymbol n -> Bool
-- myFunc SSymbol = ...  -- in this body, we have `KnownSymbol n`
-- @
--
-- This is essentially a singleton for 'Symbol', and stands in for the
-- /singletons/ 'SSymbol' and 'Data.Singleton.Sing' types.
data SSymbol n = KnownSymbol n => SSymbol

deriving instance Eq (SSymbol n)
deriving instance Ord (SSymbol n)

instance Show (SSymbol n) where
    showsPrec d x@SSymbol = showParen (d > 10) $
      showString "SSymbol @" . showsPrec 11 (fromSSymbol x)

instance GShow SSymbol where
    gshowsPrec = showsPrec

instance TestEquality SSymbol where
    testEquality (SSymbol :: SSymbol n) (SSymbol :: SSymbol m) =
      flip fmap (sameSymbol (Proxy :: Proxy n) (Proxy :: Proxy m)) $ \case
        Refl -> Refl

instance GEq SSymbol where
    geq = testEquality

instance GCompare SSymbol where
    gcompare x y = case compare (fromSSymbol x) (fromSSymbol y) of
      LT -> GLT
      EQ -> unsafeCoerce GEQ
      GT -> GGT

data SomeSymbol__ = forall n. SomeSymbol__ (SSymbol n)

-- | A useful pattern synonym for matching on a 'SomeSymbol' as if it
-- contained an @'SSymbol' n@, and not a @'Proxy' n@ as it exists in
-- "GHC.TypeLits".
--
-- A layer of compatibility letting us use the original 'SomeSymbol' type in
-- a way that works well with 'SSymbol'.
--
-- This stands in for the /singletons/ 'Data.Singleton.SomeSing' constructor.
pattern SomeSymbol_ :: SSymbol n -> SomeSymbol
pattern SomeSymbol_ x <- ((\case SomeSymbol (Proxy :: Proxy n) -> SomeSymbol__ (SSymbol :: SSymbol n)) -> SomeSymbol__ x)
  where
    SomeSymbol_ (SSymbol :: SSymbol n) = SomeSymbol (Proxy :: Proxy n)
{-# COMPLETE SomeSymbol_ #-}

-- | A useful pattern synonym for matching on a 'String' as if it "were"
-- a 'SSymbol':
--
-- @
-- myFunc :: String -> Bool
-- myFunc (FromSSymbol x) = ...  -- x is `SSymbol n`, with `n` coming from the input
-- @
--
-- It can be used as a function, as well, to convert an @'SSymbol' n@ back
-- into the 'String' that it represents.
--
-- This stands in for the /singletons/ 'Data.Singleton.FromSing' pattern synonym, except
-- it matches on a 'String' instead of a 'Data.Text.Text'.
pattern FromSSymbol :: SSymbol n -> String
pattern FromSSymbol x <- ((\i -> withSomeSymbol i SomeSymbol_) -> SomeSymbol_ x)
  where
    FromSSymbol = fromSSymbol
{-# COMPLETE FromSSymbol #-}

-- | Given an @'SSymbol' n@ and a value that would require a @'KnownSymbol' n@
-- instance, create that value.
--
-- This stands in for the function of the same name from
-- "Data.Singletons.TypeLits".
withKnownSymbol :: SSymbol n -> (KnownSymbol n => r) -> r
withKnownSymbol SSymbol x = x

-- | Promote ("reify") a 'String' to an @'SSymbol' n@, by providing
-- a continuation that would handle it in a way that is polymorphic over
-- all possible @n@.
--
-- This stands in the /singletons/ 'Data.Singleton.withSomeSing' function, except it takes
-- a 'String' instead of 'Data.Text.Text'.
withSomeSymbol :: String -> (forall n. SSymbol n -> r) -> r
withSomeSymbol (someSymbolVal->SomeSymbol (Proxy :: Proxy n)) x = x (SSymbol :: SSymbol n)

-- | Promote ("reify") a 'String' to an @'SSymbol' n@ existentially hidden
-- inside a 'SomeNat'.  To use it, pattern match using 'SomeSymbol_'.
--
-- This stands in the /singletons/ 'Data.Singleton.toSomeSing' function, except it takes
-- a 'String' instead of 'Data.Text.Text'.
toSomeSymbol :: String -> SomeSymbol
toSomeSymbol = someSymbolVal

-- | Convert ("reflect") an 'SSymbol' back into the 'String' it represents.
--
-- This stands in the /singletons/ 'Data.Singleton.fromSing' function, except it returns
-- a 'String' instead of 'Data.Text.Text'.
fromSSymbol :: SSymbol n -> String
fromSSymbol x@SSymbol = symbolVal x


text:
package com.suwonsmartapp.tourlist.database;

/**
 * Created by HYUN.KI.UNG on 2015-04-08.
 */
public class Info_CODEMT {
    public int _id;
    public String key;
    public String value;
    public String wdt;

    public Info_CODEMT() {
    }

    public Info_CODEMT(int _id, String key, String value, String wdt){
        this._id = _id;
        this.key = key;
        this.value = value;
        this.wdt = wdt;
    }
}


text:
package agent

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/hashicorp/consul/agent/consul/structs"
)

// aclCreateResponse is used to wrap the ACL ID
type aclCreateResponse struct {
	ID string
}

// ACLDisabled handles if ACL datacenter is not configured
func ACLDisabled(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	resp.WriteHeader(401)
	fmt.Fprint(resp, "ACL support disabled")
	return nil, nil
}

func (s *HTTPServer) ACLDestroy(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	// Mandate a PUT request
	if req.Method != "PUT" {
		resp.WriteHeader(405)
		return nil, nil
	}

	args := structs.ACLRequest{
		Datacenter: s.agent.config.ACLDatacenter,
		Op:         structs.ACLDelete,
	}
	s.parseToken(req, &args.Token)

	// Pull out the acl id
	args.ACL.ID = strings.TrimPrefix(req.URL.Path, "/v1/acl/destroy/")
	if args.ACL.ID == "" {
		resp.WriteHeader(400)
		fmt.Fprint(resp, "Missing ACL")
		return nil, nil
	}

	var out string
	if err := s.agent.RPC("ACL.Apply", &args, &out); err != nil {
		return nil, err
	}
	return true, nil
}

func (s *HTTPServer) ACLCreate(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	return s.aclSet(resp, req, false)
}

func (s *HTTPServer) ACLUpdate(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	return s.aclSet(resp, req, true)
}

func (s *HTTPServer) aclSet(resp http.ResponseWriter, req *http.Request, update bool) (interface{}, error) {
	// Mandate a PUT request
	if req.Method != "PUT" {
		resp.WriteHeader(405)
		return nil, nil
	}

	args := structs.ACLRequest{
		Datacenter: s.agent.config.ACLDatacenter,
		Op:         structs.ACLSet,
		ACL: structs.ACL{
			Type: structs.ACLTypeClient,
		},
	}
	s.parseToken(req, &args.Token)

	// Handle optional request body
	if req.ContentLength > 0 {
		if err := decodeBody(req, &args.ACL, nil); err != nil {
			resp.WriteHeader(400)
			fmt.Fprintf(resp, "Request decode failed: %v", err)
			return nil, nil
		}
	}

	// Ensure there is an ID set for update. ID is optional for
	// create, as one will be generated if not provided.
	if update && args.ACL.ID == "" {
		resp.WriteHeader(400)
		fmt.Fprint(resp, "ACL ID must be set")
		return nil, nil
	}

	// Create the acl, get the ID
	var out string
	if err := s.agent.RPC("ACL.Apply", &args, &out); err != nil {
		return nil, err
	}

	// Format the response as a JSON object
	return aclCreateResponse{out}, nil
}

func (s *HTTPServer) ACLClone(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	// Mandate a PUT request
	if req.Method != "PUT" {
		resp.WriteHeader(405)
		return nil, nil
	}

	args := structs.ACLSpecificRequest{
		Datacenter: s.agent.config.ACLDatacenter,
	}
	var dc string
	if done := s.parse(resp, req, &dc, &args.QueryOptions); done {
		return nil, nil
	}

	// Pull out the acl id
	args.ACL = strings.TrimPrefix(req.URL.Path, "/v1/acl/clone/")
	if args.ACL == "" {
		resp.WriteHeader(400)
		fmt.Fprint(resp, "Missing ACL")
		return nil, nil
	}

	var out structs.IndexedACLs
	defer setMeta(resp, &out.QueryMeta)
	if err := s.agent.RPC("ACL.Get", &args, &out); err != nil {
		return nil, err
	}

	// Bail if the ACL is not found
	if len(out.ACLs) == 0 {
		resp.WriteHeader(404)
		fmt.Fprint(resp, "Target ACL not found")
		return nil, nil
	}

	// Create a new ACL
	createArgs := structs.ACLRequest{
		Datacenter: args.Datacenter,
		Op:         structs.ACLSet,
		ACL:        *out.ACLs[0],
	}
	createArgs.ACL.ID = ""
	createArgs.Token = args.Token

	// Create the acl, get the ID
	var outID string
	if err := s.agent.RPC("ACL.Apply", &createArgs, &outID); err != nil {
		return nil, err
	}

	// Format the response as a JSON object
	return aclCreateResponse{outID}, nil
}

func (s *HTTPServer) ACLGet(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	args := structs.ACLSpecificRequest{
		Datacenter: s.agent.config.ACLDatacenter,
	}
	var dc string
	if done := s.parse(resp, req, &dc, &args.QueryOptions); done {
		return nil, nil
	}

	// Pull out the acl id
	args.ACL = strings.TrimPrefix(req.URL.Path, "/v1/acl/info/")
	if args.ACL == "" {
		resp.WriteHeader(400)
		fmt.Fprint(resp, "Missing ACL")
		return nil, nil
	}

	var out structs.IndexedACLs
	defer setMeta(resp, &out.QueryMeta)
	if err := s.agent.RPC("ACL.Get", &args, &out); err != nil {
		return nil, err
	}

	// Use empty list instead of nil
	if out.ACLs == nil {
		out.ACLs = make(structs.ACLs, 0)
	}
	return out.ACLs, nil
}

func (s *HTTPServer) ACLList(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	args := structs.DCSpecificRequest{
		Datacenter: s.agent.config.ACLDatacenter,
	}
	var dc string
	if done := s.parse(resp, req, &dc, &args.QueryOptions); done {
		return nil, nil
	}

	var out structs.IndexedACLs
	defer setMeta(resp, &out.QueryMeta)
	if err := s.agent.RPC("ACL.List", &args, &out); err != nil {
		return nil, err
	}

	// Use empty list instead of nil
	if out.ACLs == nil {
		out.ACLs = make(structs.ACLs, 0)
	}
	return out.ACLs, nil
}

func (s *HTTPServer) ACLReplicationStatus(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	// Note that we do not forward to the ACL DC here. This is a query for
	// any DC that's doing replication.
	args := structs.DCSpecificRequest{}
	s.parseSource(req, &args.Source)
	if done := s.parse(resp, req, &args.Datacenter, &args.QueryOptions); done {
		return nil, nil
	}

	// Make the request.
	var out structs.ACLReplicationStatus
	if err := s.agent.RPC("ACL.ReplicationStatus", &args, &out); err != nil {
		return nil, err
	}
	return out, nil
}


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#ifndef CONF_BOARD_H_INCLUDED
#define CONF_BOARD_H_INCLUDED

/** Enable the OLED screen. */
#define CONF_BOARD_SPI
#define CONF_BOARD_SPI_NPCS2

#define CONF_BOARD_OLED_UG_2832HSWEG04

#endif /* CONF_BOARD_H_INCLUDED */


text:
#include <af/vision.h>
#include <af/array.h>
#include "error.hpp"

namespace af
{

void nearestNeighbour(array& idx, array& dist,
                      const array& query, const array& train,
                      const dim_t dist_dim, const unsigned n_dist,
                      const af_match_type dist_type)
{
    af_array temp_idx  = 0;
    af_array temp_dist = 0;
    AF_THROW(af_nearest_neighbour(&temp_idx, &temp_dist, query.get(), train.get(), dist_dim, n_dist, dist_type));
    idx  = array(temp_idx);
    dist = array(temp_dist);
}

}


text:
package gui;

import gui.C4Game.Action;
import gui.C4Game.State;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;

/**
 * Generates a summary of all N-Tuples. Single N-Tuples can be displayed on the
 * playing-board
 *
 * @author Markus Thill
 *
 */
public class ShowNTuples extends Frame {
	private static final long serialVersionUID = 1L;

	private JButton ok;
	private ShowNTuples m_par;
	private TextArea txt;
	private JButton bPrevNTuple;
	private JButton bNextNTuple;
	private C4Game m_game;

	int mcrIndex = 0;

	public ShowNTuples(C4Game game) {
		super("Show N-Tuples");
		m_game = game;
		setSize(120, 700);
		setBounds(0, 0, 120, 700);
		setLayout(new BorderLayout(10, 10));
		add(new Label(" "), BorderLayout.SOUTH);

		txt = new TextArea();
		txt.setFont(new Font("Lucida Console", 0, 14));

		ok = new JButton("OK");
		m_par = this;

		bPrevNTuple = new JButton("Prev N-Tuple");
		bNextNTuple = new JButton("Next N-Tuple");

		bPrevNTuple.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				m_game.action = Action.MOVEBACK;
				String str = "[Previous N-Tuple]";
				m_game.c4Buttons.printStatus(str);
			}
		});

		bNextNTuple.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				m_game.action = Action.NEXTMOVE;
				String str = "[Next N-Tuple]";
				m_game.c4Buttons.printStatus(str);
			}
		});

		ok.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				m_par.setVisible(false);
				m_game.changeState(State.IDLE);
			}
		});

		bPrevNTuple
				.setToolTipText("Show the next N-Tuple for a N-Tuple-TD-Agent. This button "
						+ "doesn't work for other agent-types. The selected agent also must
"
						+ "be trained for this to work");

		bNextNTuple
				.setToolTipText("Show the previus N-Tuple for a N-Tuple-TD-Agent. This button "
						+ "doesn't work for other agent-types. The selected agent also must
"
						+ "be trained for this to work");

		Panel p = new Panel();
		p.setLayout(new GridLayout2(2, 3, 5, 5));
		p.add(bPrevNTuple);
		p.add(bNextNTuple);
		p.add(new Canvas());

		add(p, BorderLayout.NORTH);

		add(txt);
		add(ok, BorderLayout.SOUTH);

		pack();
		setVisible(false);
	}

	public void setNTuples(String mcr) {
		txt.setText(mcr);
		txt.setCaretPosition(0);
		txt.setCaretPosition(25);
		txt.setSelectionStart(7);
		txt.setSelectionEnd(17);
		mcrIndex = 0;
	}
}


text:
define("dojox/drawing/_base",["dojo","./annotations/Label","./Drawing"],function(_1,L,_2){
_1.experimental("dojox.drawing");
return _2;
});


text:
package org.jboss.aerogear.android.authorization;

import java.util.Collection;
import java.util.HashSet;
import org.jboss.aerogear.android.core.Config;

public abstract class AuthorizationConfiguration<CONFIGURATION extends AuthorizationConfiguration> implements Config<CONFIGURATION> {

    private Collection<OnAuthorizationCreatedListener> listeners = new HashSet<OnAuthorizationCreatedListener>();

    private String name;

    @Override
    public String getName() {
        return name;
    }

    @Override
    public CONFIGURATION setName(String name) {
        this.name = name;
        return (CONFIGURATION) this;
    }

    /**
     * OnAuthorizationCreatedListeners are a collection of classes to be
     * notified when the configuration of the Pipe is complete.
     *
     * @return the current collection.
     */
    public Collection<OnAuthorizationCreatedListener> getOnAuthorizationCreatedListeners() {
        return listeners;
    }

    /**
     * OnAuthorizationCreatedListeners are a collection of classes to be
     * notified when the configuration of the Pipe is complete.
     *
     * @param listener new listener to add to the collection
     * @return this configuration
     */
    public CONFIGURATION addOnAuthorizationCreatedListener(OnAuthorizationCreatedListener listener) {
        this.listeners.add(listener);
        return (CONFIGURATION) this;
    }

    /**
     * OnAuthorizationCreatedListeners are a collection of classes to be
     * notified when the configuration of the Pipe is complete.
     *
     * @param listeners new collection to replace the current one
     * @return this configuration
     */
    public CONFIGURATION setOnAuthorizationCreatedListeners(Collection<OnAuthorizationCreatedListener> listeners) {
        listeners.addAll(listeners);
        return (CONFIGURATION) this;
    }

    /**
     *
     * Creates a authenticationModule based on the current configuration and
     * notifies all listeners
     *
     * @return An AuthenticationModule based on this configuration
     *
     * @throws IllegalStateException if the AuthenticationModule can not be
     *             constructed.
     *
     */
    public final AuthzModule asModule() {

        AuthzModule newModule = buildModule();
        for (OnAuthorizationCreatedListener listener : getOnAuthorizationCreatedListeners()) {
            listener.onAuthorizationCreated(this, newModule);
        }
        return newModule;
    }

    /**
     *
     * Validates configuration parameters and returns a AuthenticationModule
     * instance.
     *
     * @return An AuthenticationModule based on this configuration
     *
     * @throws IllegalStateException if the Pipe can not be constructed.
     */
    protected abstract AuthzModule buildModule();

}


text:
package examples;

import basicUtils.Matrix;
import mlalgorithms.ActivationFunction;
import java.lang.Math;

/**
 * Created by 李沅泽 on 2017/1/3.
 * 作为激活函数构建的样例,实现了对数Sigmoid函数
 */
public class SigmoidActivationFunction extends ActivationFunction{

    public SigmoidActivationFunction() {

    }
    public double cal(double param) {
        return 1/(1+Math.exp(-1*param));
    }

    public double derivation(double param) {
        double temp = cal(param);
        return temp*(1-temp);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Toggl.Phoebe.Data.DataObjects;
using Toggl.Phoebe.Data.Utils;
using Toggl.Phoebe.Net;
using XPlatUtils;

namespace Toggl.Phoebe.Data.Views
{
    public class ProjectsCollection : ObservableRangeCollection<CommonData>
    {
        private List<ClientData> clients;
        private List<SuperProjectData> projects;
        private List<TaskData> tasks;
        private SortProjectsBy sortBy;
        private Guid workspaceId;
        private string projectNameFilter;

        public enum SortProjectsBy {
            Projects,
            Clients
        }

        ProjectsCollection (SortProjectsBy sortBy, Guid workspaceId)
        {
            this.sortBy = sortBy;
            this.workspaceId = workspaceId;
        }

        public static async Task<ProjectsCollection> Init (SortProjectsBy sortBy, Guid workspaceId)
        {
            var v = new ProjectsCollection (sortBy, workspaceId);
            var store = ServiceContainer.Resolve<IDataStore> ();
            var userData = ServiceContainer.Resolve<AuthManager> ().User;

            var projectsTask = store.GetUserAccessibleProjects (userData.Id);
            var clientsTask = store.Table<ClientData> ().Where (r => r.DeletedAt == null)
                              .OrderBy (r => r.Name).ToListAsync ();
            var tasksTask = store.Table<TaskData> ().Where (r => r.DeletedAt == null && r.IsActive)
                            .OrderBy (r => r.Name).ToListAsync();
            await Task.WhenAll (projectsTask, tasksTask, clientsTask);

            v.clients = clientsTask.Result;
            v.tasks = tasksTask.Result;
            v.projects = projectsTask.Result.Select (p =>
                         new SuperProjectData (p,
                                               v.clients.FirstOrDefault (c => c.Id == p.ClientId),
                                               v.tasks.Count (t => t.ProjectId == p.Id))
                                                    ).ToList ();
            // Create collection
            v.CreateSortedCollection (v.projects);
            return v;
        }

        #region List operations
        public SortProjectsBy SortBy
        {
            get {
                return sortBy;
            } set {
                if (sortBy == value) {
                    return;
                }
                sortBy = value;
                CreateSortedCollection (projects);
            }
        }

        public Guid WorkspaceId
        {
            get {
                return workspaceId;
            } set {
                if (workspaceId == value) {
                    return;
                }
                workspaceId = value;
                CreateSortedCollection (projects);
            }
        }

        public string ProjectNameFilter
        {
            get {
                return projectNameFilter;
            } set {
                if (projectNameFilter == value) {
                    return;
                }
                projectNameFilter = value;
                var prjs = string.IsNullOrEmpty (value) ? projects : projects.Where (p => p.Name.ToLower ().Contains (projectNameFilter.ToLower ()));
                CreateSortedCollection (prjs);
            }
        }
        #endregion

        private void CreateSortedCollection (IEnumerable<SuperProjectData> projectList)
        {
            var enumerable = projectList as IList<SuperProjectData> ?? projectList.ToList ();
            var data = new List<CommonData> ();

            // TODO: Maybe group using linq is clearer
            if (sortBy == SortProjectsBy.Clients) {

                // Add section without client
                data.Add (new ClientData ());
                data.Add (GetEmptyProject ());
                enumerable.Where (p => p.ClientId == null && p.WorkspaceId == workspaceId).ForEach (data.Add);

                // Add normal sections
                var sectionHeaders = clients.Where (p => p.WorkspaceId == workspaceId);
                foreach (var header in sectionHeaders) {
                    var sectionItems = enumerable.Where (p => p.ClientId == header.Id && p.WorkspaceId == workspaceId).ToList ();
                    if (sectionItems.Count > 0) {
                        data.Add (header);
                        sectionItems.ForEach (data.Add);
                    }
                }
            } else {
                data.Add (GetEmptyProject ());
                enumerable.Where (p => p.WorkspaceId == workspaceId).ForEach (data.Add);
            }

            // ObservableRange method :)
            Reset (data);
        }

        public bool AddTasks (ProjectData project)
        {
            // Remove previous tasks
            var oldTaskIndex = this.IndexOf (p => p is TaskData);
            if (oldTaskIndex != -1) {
                RemoveRange (this.OfType<TaskData> ());
            }

            // Insert new tasks
            var newTaskIndex = this.IndexOf (p => p.Id == project.Id) + 1;
            if (oldTaskIndex != newTaskIndex) {
                InsertRange (tasks.Where (p => p.ProjectId == project.Id), newTaskIndex);
                return true;
            }

            return false;
        }

        public class SuperProjectData : ProjectData
        {
            public string ClientName { get; private set; }
            public int TaskNumber { get; private set; }
            public bool IsEmpty { get; private set; }

            public SuperProjectData (ProjectData dataObject,
                                     ClientData client, int taskNumber, bool isEmpty = false) : base (dataObject)
            {
                TaskNumber = taskNumber;
                IsEmpty = isEmpty;
                ClientName = client != null ? client.Name : "";
            }
        }

        private SuperProjectData GetEmptyProject ()
        {
            return new SuperProjectData (new ProjectData (), null, 0, true);
        }
    }
}


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using RestSharp;

namespace PipeDriveApi.EntityServices
{
    public class OrganizationRelationshipEntityService<T> : EntityServiceBase
        where T : OrganizationRelationship
    {
        private readonly string _resource;

        public OrganizationRelationshipEntityService(IPipeDriveClient client) : base(client)
        {
            _resource = "organizationRelationships";
        }

        public async Task<ListResult<T>> GetForOrganizationAsync(
            int organizationid, int start = 0, int limit = 100, Sort sort = null)
        {
            var request = new RestRequest(_resource, Method.GET);
            return await GetForOrganizationAsync(request, organizationid, start, limit, sort);
        }

        public async Task<ListResult<T>> GetForOrganizationAsync(
            IRestRequest request, int organizationid, int start = 0, int limit = 100, Sort sort = null)
        {
            request.SetQueryParameter("org_id", organizationid.ToString());
            request.SetQueryParameter("start", start.ToString());
            request.SetQueryParameter("limit", limit.ToString());
            if (sort != null)
                request.SetQueryParameter("sort", sort.ToString());

            var response = await _client.ExecuteRequestWithCustomResponseAsync<
                PaginatedPipeDriveResponse<T>,
                List<T>>(request);

            return new ListResult<T>(response.Data ?? new List<T>(), response.AdditionalData.Pagination);
        }

        public async Task<IReadOnlyList<T>> GetAllForOrganizationAsync(
            int organizationid, Sort sort = null)
        {
            var request = new RestRequest(_resource, Method.GET);
            return await GetAllForOrganizationAsync(request, organizationid, sort);
        }

        public async Task<IReadOnlyList<T>> GetAllForOrganizationAsync(
            IRestRequest request, int organizationid, Sort sort = null)
        {
            var combinedList = new List<T>();
            int start = 0;
            const int limit = 1000;
            while (true)
            {
                var response = await GetForOrganizationAsync(request, organizationid, start, limit, sort);
                combinedList.AddRange(response);
                start = response.Pagination.NextStart;
                //TODO: API bug - MoreItemsInCollection is true even if there are no additional items
                //if (!response.Pagination.MoreItemsInCollection)
                break;
            }
            return combinedList;
        }
    }
}


text:
import React from 'react';
import lo from 'lodash';
import RSelect from 'react-select';
import Highlighter from 'react-highlight-words';
import 'react-select/dist/react-select.css';

var Dom = function({filter}){
    var command = filter.selectedCommand;
    return

                Code
                {command.code}

                Name (input)
                {command.name.input}
                (output)
                {command.name.output}

                Handlers (input)

                (output)

;
};

var printHandler = function(handlers){
    return JSON.stringify(handlers)
        .replace(/,/g, ", " )
        .replace(/\[/g, "[ ")
        .replace(/\]/g, "] ");
};

export default Dom;


text:
//
//  BaseNetworking.h
//
//  Created by Sardorbek on 12/13/15.
//  Copyright © 2015 Sardorbek Ruzmatov. All rights reserved.
//

#import <Foundation/Foundation.h>

typedef void(^BaseNetworkingResponse)(id responseData, NSURLResponse *responseObject, NSError *error);

/**
 *  A wrapper class for basic networking calls
 */
@interface BaseNetworking : NSObject

-(void)fetchDataAtURLString:(NSString*)urlString withBlock:(BaseNetworkingResponse)block;
-(void)fetchContentAtURLString:(NSString*)urlString withBlock:(BaseNetworkingResponse)block;
-(void)postContent:(id)content atURLString:(NSString*)urlString withBlock:(BaseNetworkingResponse)block;

@end


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE511_Logic_Time_Bomb__w32CompareFileTime_17.c
Label Definition File: CWE511_Logic_Time_Bomb.label.xml
Template File: point-flaw-17.tmpl.c
*/
/*
 * @description
 * CWE: 511 Logic Time Bomb
 * Sinks: w32CompareFileTime
 *    GoodSink: After a certain date, do something harmless
 *    BadSink : After a certain date, do something bad
 * Flow Variant: 17 Control flow: for loops
 *
 * */

#include "std_testcase.h"

#ifdef _WIN32
#define UNLINK _unlink
#else
#include <unistd.h>
#define UNLINK unlink
#endif

#include <windows.h>

#ifndef OMITBAD

void CWE511_Logic_Time_Bomb__w32CompareFileTime_17_bad()
{
    int j;
    for(j = 0; j < 1; j++)
    {
        {
            SYSTEMTIME setTime, currentTime;
            FILETIME setTimeAsFileTime, currentTimeAsFileTime;
            /* Jan 1, 2008 12:00:00 PM */
            setTime.wYear         = 2008; /* Year */
            setTime.wMonth        = 1;    /* January */
            setTime.wDayOfWeek    = 0;    /* Ignored */
            setTime.wDay          = 1;    /* The first of the month */
            setTime.wHour         = 12;   /* 12 PM */
            setTime.wMinute       = 0;    /* 0 minutes into the hour */
            setTime.wSecond       = 0;    /* 0 seconds into the minute */
            setTime.wMilliseconds = 0;    /* 0 milliseconds into the second */
            GetSystemTime(&currentTime);
            /* Must convert to FILETIME for comparison */
            SystemTimeToFileTime(&currentTime, &currentTimeAsFileTime);
            SystemTimeToFileTime(&setTime, &setTimeAsFileTime);
            /* FLAW: After a certain date, delete a file */
            if (CompareFileTime(&currentTimeAsFileTime, &setTimeAsFileTime) == 1)
            {
                UNLINK("important_file.txt");
            }
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good1() uses the GoodSinkBody in the for statements */
static void good1()
{
    int k;
    for(k = 0; k < 1; k++)
    {
        {
            SYSTEMTIME setTime, currentTime;
            FILETIME setTimeAsFileTime, currentTimeAsFileTime;
            /* Jan 1, 2008 12:00:00 PM */
            setTime.wYear         = 2008; /* Year */
            setTime.wMonth        = 1;    /* January */
            setTime.wDayOfWeek    = 0;    /* Ignored */
            setTime.wDay          = 1;    /* The first of the month */
            setTime.wHour         = 12;   /* 12 PM */
            setTime.wMinute       = 0;    /* 0 minutes into the hour */
            setTime.wSecond       = 0;    /* 0 seconds into the minute */
            setTime.wMilliseconds = 0;    /* 0 milliseconds into the second */
            GetSystemTime(&currentTime);
            /* Must convert to FILETIME for comparison */
            SystemTimeToFileTime(&currentTime, &currentTimeAsFileTime);
            SystemTimeToFileTime(&setTime, &setTimeAsFileTime);
            /* FIX: After a certain date, print to the console */
            if (CompareFileTime(&currentTimeAsFileTime, &setTimeAsFileTime) == 1)
            {
                printLine("Happy New Year!");
            }
        }
    }
}

void CWE511_Logic_Time_Bomb__w32CompareFileTime_17_good()
{
    good1();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE511_Logic_Time_Bomb__w32CompareFileTime_17_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE511_Logic_Time_Bomb__w32CompareFileTime_17_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
/*!
Theme Name: themename
Theme URI: https://themeurl/
Author: Themes Author
Author URI: https://themeauthorurl/
Description: Description
Version: 1.0.0
License: GNU General Public License v2 or later
License URI: LICENSE
Text Domain: themedomain
Tags: custom-background, custom-logo, custom-menu, featured-images, threaded-comments, translation-ready
*/


text:
package org.apache.ibatis.submitted.duplicate_resource_loaded;

import java.util.List;

public interface Mapper {

  List selectAllBlogs();

}


text:
//
//  NSArray+LINQ_Generation.h
//  LINQ4Obj-C
//
//  Copyright (c) 2013 Michal Konturek
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//

#import "LINQ.h"

@interface NSArray (LINQ_Generation)

/**
 Returns empty array.
 */
+ (instancetype)linq_empty;

/**
 Creates array with integers from to.
 */
+ (instancetype)linq_from:(NSInteger)from to:(NSInteger)to;

/**
 Generates a collection that contains one repeated value.
 */
+ (instancetype)linq_repeat:(id)element count:(NSInteger)count;

/**
 TBC
 */
+ (instancetype)linq_with:(id (^)(id item))block count:(NSInteger)count;

@end


text:
package com.jworkflow.scratchpad;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import net.jworkflow.providers.aws.DynamoDBLockService;
import net.jworkflow.sample01.HelloWorkflow;
import software.amazon.awssdk.regions.Region;

public class Main {
    public static void main(String[] args) throws Exception {

        Function<TestData, Object> f1 = (o) -> o.id;
        Function<TestData, Object> f2 = (o) -> o.getPid();

        //Function<TestData, Object> f3 = TestData::getPid;

        //Consumer<Integer> f4 = TestData::setPid;

        BiConsumer<TestData, Integer> f3 = (o, v) -> o.setPid(v);

        TestData d1 = new TestData();
        d1.id = 1;
        d1.name = "hi";
        d1.setPid(5);

        TestData.class.getField("id").set(d1, 2);
        //TestData.class.getMethod("setPid").set(d1, 8);

        f3.accept(d1, 11);

        Object v1 = f1.apply(d1);
        Object v2 = f2.apply(d1);

        System.out.println(String.valueOf(v1));
        System.out.println(String.valueOf(v2));

    }

}


text:
package testdata

import "os"

func Foo18(t *os.File) *os.File { return t }


text:
import { api } from '../api'
import * as akala from '@akala/server'
import * as fs from 'fs'
import { PacketType } from 'rfxtrx';
import { promisify } from 'util'

akala.api.buildServer(api, { rest: '/api' }, {
    types()
    {
        return Promise.all(Object.keys(PacketType).map(async k =>
        {
            if (await promisify(fs.exists)('views/new-' + k + '.html'))
            {
                return { name: k, view: '@domojs/rfx/new-' + k + '.html' };
            }
        })).then(values => { return values.filter(v => !!v) });
    }
})


text:
const expect = chai.expect;

describe('p5.Distortion', function () {
  it('can be created and disposed', function () {
    let distortion = new p5.Distortion();
    expect(distortion).to.have.property('input');
    expect(distortion).to.have.property('output');
    expect(distortion).to.have.property('wet');
    expect(distortion).to.have.property('waveShaperNode');
    expect(distortion.waveShaperNode).to.have.property('context').to.not.be
      .null;
    //default case
    expect(distortion.amount).to.equal(500);
    expect(distortion.waveShaperNode.oversample).to.equal('2x');

    distortion.dispose();
    expect(distortion.waveShaperNode).to.be.null;
  });

  it('can be created with only amount as a parameter', function () {
    let distortion = new p5.Distortion(0.3);
    expect(distortion.amount).to.equal(600);
    expect(distortion.waveShaperNode.oversample).to.equal('2x');

    //non-numerical value
    expect(() => new p5.Distortion('a')).to.throw();
  });
  it('can be created with only oversample as a parameter', function () {
    let distortion = new p5.Distortion(undefined, '4x');
    expect(distortion.amount).to.equal(500);
    expect(distortion.waveShaperNode.oversample).to.equal('4x');

    //non-numerical value
    expect(() => new p5.Distortion(undefined, 500)).to.throw();
  });
  it('can be created with both parameters', function () {
    let distortion = new p5.Distortion(0.8, '4x');
    expect(distortion.amount).to.equal(1600);
    expect(distortion.waveShaperNode.oversample).to.equal('4x');
  });

  describe('methods', function () {
    it('can process a sound source', function () {
      let osc = new p5.SawOsc();
      let distortion = new p5.Distortion();
      //no params
      distortion.process(osc);

      //both params
      distortion.process(osc, 0.62, '4x');
      expect(distortion.amount).to.equal(1240);
      expect(distortion.waveShaperNode.oversample).to.equal('4x');
    });
    it('can set amount and oversample', function () {
      let distortion = new p5.Distortion();
      //only one param
      distortion.set(0.98);
      expect(distortion.amount).to.equal(1960);
      expect(distortion.waveShaperNode.oversample).to.equal('2x');
      distortion.set(undefined, '4x');
      expect(distortion.amount).to.equal(1960);
      expect(distortion.waveShaperNode.oversample).to.equal('4x');

      //both params
      distortion.set(0.14, '2x');
      expect(distortion.amount).to.equal(280);
      expect(distortion.waveShaperNode.oversample).to.equal('2x');
    });
    it('can get amount', function () {
      let distortion = new p5.Distortion(0.43, '2x');
      expect(distortion.getAmount()).to.equal(860);
    });
    it('can get over sample', function () {
      let distortion = new p5.Distortion(0.43, '4x');
      expect(distortion.getOversample()).to.equal('4x');
    });
  });
});


text:
package net.mikaboshi.log;

import static org.junit.Assert.assertEquals;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class SimpleFileLoggerTest {

	private static final String LOG_PATH = "SimpleFileLoggerTest.log";

	@Before
	public void setUp() {
		deleteLogFile();
	}

	@After
	public void tearDown() {
		deleteLogFile();
	}

	private void deleteLogFile() {
		File logFile = new File(LOG_PATH);

		if (logFile.exists()) {
			logFile.delete();
		}
	}

	@Test
	public void testPut() throws IOException {
		SimpleFileLogger logger =
			new SimpleFileLogger(LOG_PATH, true, true);

		logger.put("aaa");
		logger.put("bbb");
		logger.close();

		String content =
			FileUtils.readFileToString(new File(LOG_PATH));

		String expected =
			"aaa" + IOUtils.LINE_SEPARATOR + "bbb" + IOUtils.LINE_SEPARATOR;

		assertEquals(expected, content);
	}

	@Test
	public void testPutf() throws IOException {
		SimpleFileLogger logger =
			new SimpleFileLogger(LOG_PATH, true, true);

		logger.putf("aaa %d bbb", 1);
		logger.putf("ccc %s eee", "fff");
		logger.close();

		String content =
			FileUtils.readFileToString(new File(LOG_PATH));

		String expected =
			"aaa 1 bbb" + IOUtils.LINE_SEPARATOR +
			"ccc fff eee" + IOUtils.LINE_SEPARATOR;

		assertEquals(expected, content);
	}

	@Test
	public void testRotate() throws IOException {
		SimpleFileLogger logger = new SimpleFileLogger(
				"SimpleFileLoggerRotateTest.log", true, true);

		logger.clean();

		logger.setRotetaSize(1000);

		for (int i = 0; i < 1000; i++) {
			logger.put("" + i);
		}
	}
}


text: Rails.application.config.session_store :cookie_store, key: '_posManager_session'