text: module.exports = require('../../../full/string/virtual/repeat');

redpajama_set_name: RedPajamaGithub


text:
class Roster
  include Virtus.value_object

  values do
    attribute :team, Team
    attribute :manager, Manager
    attribute :players, Array[Player]
  end
end


text:
package org.apache.cassandra.auth;

import org.apache.cassandra.config.DatabaseDescriptor;

public class NetworkAuthCache extends AuthCache<RoleResource, DCPermissions> implements AuthCacheMBean
{
    public NetworkAuthCache(INetworkAuthorizer authorizer)
    {
        super("NetworkAuthCache",
              DatabaseDescriptor::setRolesValidity,
              DatabaseDescriptor::getRolesValidity,
              DatabaseDescriptor::setRolesUpdateInterval,
              DatabaseDescriptor::getRolesUpdateInterval,
              DatabaseDescriptor::setRolesCacheMaxEntries,
              DatabaseDescriptor::getRolesCacheMaxEntries,
              authorizer::authorize,
              () -> DatabaseDescriptor.getAuthenticator().requireAuthentication());
    }

}


text:
project_id = attribute("project_id", default: ENV["TF_VAR_project"])
control "gcloud_datastore" do
  title "Check if datastore has correct indexes"
  # Ensure first index is type 'Task'
  describe command("gcloud --project='#{project_id}' datastore indexes list --filter='properties[0].name=done' --format=json --quiet | jq -jce '.[0].kind'") do
    its('exit_status') { should eq 0 }
    its('stderr') { should eq '' }
    its('stdout') { should eq 'Task' }
  end

  # Ensure first index has expected properties
  describe command("gcloud --project='#{project_id}' datastore indexes list --filter='properties[0].name=done' --format=json --quiet | jq -jce '.[0].properties'") do
    its('exit_status') { should eq 0 }
    its('stderr') { should eq '' }
    its('stdout') { should eq '[{"direction":"ASCENDING","name":"done"},{"direction":"DESCENDING","name":"priority"}]' }
  end

  # Ensure second index is type 'Task'
  describe command("gcloud --project='#{project_id}' datastore indexes list --filter='properties[0].name=collaborators' --format=json --quiet | jq -jce '.[0].kind'") do
    its('exit_status') { should eq 0 }
    its('stderr') { should eq '' }
    its('stdout') { should eq 'Task' }
  end

  # Ensure second index has expected properties
  describe command("gcloud --project='#{project_id}' datastore indexes list --filter='properties[0].name=collaborators' --format=json --quiet | jq -jce '.[0].properties'") do
    its('exit_status') { should eq 0 }
    its('stderr') { should eq '' }
    its('stdout') { should eq '[{"direction":"ASCENDING","name":"collaborators"},{"direction":"DESCENDING","name":"created"}]' }
  end
end


text:
package org.onosproject.isis.io.isispacket.tlv;

import org.easymock.EasyMock;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;

/**
 * Unit test class for HostNameTlv.
 */
public class HostNameTlvTest {
    private final String hostName = "TEST";
    private final byte[] tlv = hostName.getBytes();
    private HostNameTlv hostNameTlv;
    private TlvHeader tlvHeader;
    private String result;
    private ChannelBuffer channelBuffer;
    private byte[] result1;

    @Before
    public void setUp() throws Exception {
        tlvHeader = new TlvHeader();
        tlvHeader.setTlvLength(tlv.length);
        hostNameTlv = new HostNameTlv(tlvHeader);
        channelBuffer = EasyMock.createMock(ChannelBuffer.class);
    }

    @After
    public void tearDown() throws Exception {
        tlvHeader = null;
        hostNameTlv = null;
    }

    /**
     * Tests hostName() getter method.
     */
    @Test
    public void testHostName() throws Exception {
        hostNameTlv.setHostName(hostName);
        result = hostNameTlv.hostName();
        assertThat(result, is(hostName));
    }

    /**
     * Tests hostName() setter method.
     */
    @Test
    public void testSetHostName() throws Exception {
        hostNameTlv.setHostName(hostName);
        result = hostNameTlv.hostName();
        assertThat(result, is(hostName));
    }

    /**
     * Tests readFrom() method.
     */
    @Test
    public void testReadFrom() throws Exception {
        channelBuffer = ChannelBuffers.copiedBuffer(tlv);
        hostNameTlv.readFrom(channelBuffer);
        assertThat(hostNameTlv.hostName(), is(hostName));
    }

    /**
     * Tests asBytes() method.
     */
    @Test
    public void testAsBytes() throws Exception {
        channelBuffer = ChannelBuffers.copiedBuffer(tlv);
        hostNameTlv.readFrom(channelBuffer);
        result1 = hostNameTlv.asBytes();
        assertThat(result1, is(notNullValue()));
    }

    /**
     * Tests toString() method.
     */
    @Test
    public void testToString() throws Exception {
        assertThat(hostNameTlv.toString(), is(notNullValue()));
    }
}


text:
package ru.doxhost.newhost.server.lib;

import java.io.*;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author Eugene Kirin
 */
public class Nh2Checksum {

    /**
     * Generates md5 checksum for given {@code Class}
     * @param forClass Class
     * @return md5 checksum
     * @throws NoSuchAlgorithmException
     */
    public static String md5Sum(Class forClass) throws NoSuchAlgorithmException, IOException {

        MessageDigest messageDigest = MessageDigest.getInstance("MD5");

        String path = forClass.getName().replace('.', '/');
        String fileName = path + ".class";

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        InputStream stream = forClass.getClassLoader().getResourceAsStream(fileName);

        int datum = stream.read();

        while( datum != -1) {
            buffer.write(datum);
            datum = stream.read();
        }

        messageDigest.update(buffer.toByteArray());

        byte[] digestBytes = messageDigest.digest();

        StringBuilder sb = new StringBuilder("");

        for (byte digestByte : digestBytes) {
            sb.append(Integer.toString((digestByte & 0xff) + 0x100, 16).substring(1));
        }
        return sb.toString();
    }
}


text:
using System.Collections.Generic;
using Xunit;

namespace System.Runtime.InteropServices.Tests
{
    public class GCHandleTests
    {
        [Fact]
        public void Ctor_Default()
        {
            var handle = new GCHandle();
            Assert.Throws<InvalidOperationException>(() => handle.Target);
            Assert.False(handle.IsAllocated);

            Assert.Equal(IntPtr.Zero, GCHandle.ToIntPtr(handle));
            Assert.Equal(IntPtr.Zero, (IntPtr)handle);
        }

        public static IEnumerable<object[]> Alloc_TestData()
        {
            yield return new object[] { null };
            yield return new object[] { "String" };
            yield return new object[] { 123 };
            yield return new object[] { new int[1] };
            yield return new object[] { new NonBlittable[1] };
            yield return new object[] { new object[1] };
            yield return new object[] { new NonBlittable() };
        }

        [Theory]
        [MemberData(nameof(Alloc_TestData))]
        public void Alloc_Value_ReturnsExpected(object value)
        {
            GCHandle handle = GCHandle.Alloc(value);
            ValidateGCHandle(handle, GCHandleType.Normal, value);
        }

        public static IEnumerable<object[]> Alloc_Type_TestData()
        {
            foreach (object[] data in Alloc_TestData())
            {
                yield return new object[] { data[0], GCHandleType.Normal };
                yield return new object[] { data[0], GCHandleType.Weak };
                yield return new object[] { data[0], GCHandleType.WeakTrackResurrection };
            }

            yield return new object[] { null, GCHandleType.Pinned };
            yield return new object[] { "", GCHandleType.Pinned };
            yield return new object[] { 1, GCHandleType.Pinned };
            yield return new object[] { new Blittable(), GCHandleType.Pinned };
            yield return new object[] { new Blittable(), GCHandleType.Pinned };
            yield return new object[] { new Blittable[0], GCHandleType.Pinned };
        }

        [Theory]
        [MemberData(nameof(Alloc_Type_TestData))]
        public static void Alloc_Type_ReturnsExpected(object value, GCHandleType type)
        {
            GCHandle handle = GCHandle.Alloc(value, type);
            ValidateGCHandle(handle, type, value);
        }

        public static IEnumerable<object[]> InvalidPinnedObject_TestData()
        {
            yield return new object[] { new NonBlittable() };
            yield return new object[] { new object[0] };
            yield return new object[] { new NonBlittable[0] };
        }

        [Theory]
        [MemberData(nameof(InvalidPinnedObject_TestData))]
        public void Alloc_InvalidPinnedObject_ThrowsArgumentException(object value)
        {
            Assert.Throws<ArgumentException>(() => GCHandle.Alloc(value, GCHandleType.Pinned));
        }

        [Theory]
        [InlineData(GCHandleType.Weak - 1)]
        [InlineData(GCHandleType.Pinned + 1)]
        public void Alloc_InvalidGCHandleType_ThrowsArgumentOutOfRangeException(GCHandleType type)
        {
            AssertExtensions.Throws<ArgumentOutOfRangeException>("type", () => GCHandle.Alloc(new object(), type));
        }

        [Fact]
        public void FromIntPtr_Zero_ThrowsInvalidOperationException()
        {
            Assert.Throws<InvalidOperationException>(() => GCHandle.FromIntPtr(IntPtr.Zero));
        }

        [Fact]
        public void AddrOfPinnedObject_NotInitialized_ThrowsInvalidOperationException()
        {
            var handle = new GCHandle();
            Assert.Throws<InvalidOperationException>(() => handle.AddrOfPinnedObject());
        }

        [Fact]
        public void AddrOfPinnedObject_NotPinned_ThrowsInvalidOperationException()
        {
            GCHandle handle = GCHandle.Alloc(new object());
            try
            {
                Assert.Throws<InvalidOperationException>(() => handle.AddrOfPinnedObject());
            }
            finally
            {
                handle.Free();
            }
        }

        [Fact]
        public void Free_NotInitialized_ThrowsInvalidOperationException()
        {
            var handle = new GCHandle();
            Assert.Throws<InvalidOperationException>(() => handle.Free());
        }

        public static IEnumerable<object[]> Equals_TestData()
        {
            GCHandle handle = GCHandle.Alloc(new object());
            yield return new object[] { handle, handle, true };
            yield return new object[] { GCHandle.Alloc(new object()), GCHandle.Alloc(new object()), false };

            yield return new object[] { GCHandle.Alloc(new object()), new object(), false };
            yield return new object[] { GCHandle.Alloc(new object()), null, false };
        }

        [Theory]
        [MemberData(nameof(Equals_TestData))]
        public void Equals_Object_ReturnsExpected(GCHandle handle, object other, bool expected)
        {
            try
            {
                Assert.Equal(expected, handle.Equals(other));
                if (other is GCHandle otherHandle)
                {
                    Assert.Equal(expected, handle == otherHandle);
                    Assert.Equal(!expected, handle != otherHandle);
                }
            }
            finally
            {
                handle.Free();
                if (other is GCHandle otherHandle && !expected)
                {
                    otherHandle.Free();
                }
            }
        }

        private static void ValidateGCHandle(GCHandle handle, GCHandleType type, object target)
        {
            try
            {
                Assert.Equal(target, handle.Target);
                Assert.True(handle.IsAllocated);

                Assert.NotEqual(IntPtr.Zero, GCHandle.ToIntPtr(handle));
                Assert.Equal(GCHandle.ToIntPtr(handle), (IntPtr)handle);
                Assert.Equal(((IntPtr)handle).GetHashCode(), handle.GetHashCode());

                if (type == GCHandleType.Pinned)
                {
                    if (target == null)
                    {
                        Assert.Equal(IntPtr.Zero, handle.AddrOfPinnedObject());
                    }
                    else
                    {
                        Assert.NotEqual(IntPtr.Zero, handle.AddrOfPinnedObject());
                    }
                }

            }
            finally
            {
                handle.Free();
                Assert.False(handle.IsAllocated);
            }
        }

        public struct Blittable
        {
            public int Object { get; set; }
        }

        public struct NonBlittable
        {
            public List<string> Object { get; set; }
        }
    }
}


text:
package cuckoo_egg

class BirdNest extends Nest {
  def layEgg: Egg = {
    new BirdEgg
  }
}


text:
layout: page
title: Lyons Solutions Conference
date: 2016-05-24
author: Danielle Patterson
tags: weekly links, java
status: published
summary: Quisque maximus quis nunc sit amet commodo.
banner: images/banner/wedding.jpg
booking:
  startDate: 07/08/2019
  endDate: 07/12/2019
  ctyhocn: DENGWHX
  groupCode: LSC
published: true
---
Cras pellentesque, dolor ut mattis posuere, ligula odio imperdiet quam, vestibulum condimentum nunc enim eu odio. Donec consectetur pellentesque elementum. Cras semper nunc eget pellentesque fermentum. Vestibulum vestibulum nec nunc in varius. Aenean consequat, metus quis dictum faucibus, enim sem convallis ante, sed euismod urna odio vitae tellus. Vivamus suscipit nibh et fringilla consectetur. Cras sed mi sem. Sed consequat lacus nisl. Phasellus aliquam sit amet purus at viverra. Duis aliquet lacus id metus elementum interdum. Fusce consectetur consectetur tortor, quis maximus arcu hendrerit non. Aliquam erat volutpat. Aliquam lobortis lobortis orci sit amet imperdiet.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi at congue elit. Maecenas magna mi, blandit vitae dapibus ac, feugiat sit amet mauris. Integer eros risus, finibus sed diam non, bibendum convallis eros. Nulla semper accumsan diam, ut consectetur lorem faucibus et. Phasellus a erat et nunc ultrices eleifend vel sit amet sapien. Etiam dictum metus eget facilisis tempor. Nunc in commodo felis.

* Nullam mollis turpis in efficitur pellentesque
* Quisque varius enim in risus convallis tincidunt
* Nunc suscipit ante nec condimentum pellentesque
* Sed eu eros in erat dapibus gravida.

Integer laoreet aliquam purus, nec suscipit erat rhoncus vel. Morbi blandit, ipsum in molestie facilisis, quam nisl faucibus metus, id posuere ante tellus ultricies sem. Vivamus euismod tempus placerat. Phasellus odio quam, ultricies a ligula ut, interdum auctor ipsum. Sed quis orci et turpis maximus molestie. Ut ut nibh vitae mi pellentesque scelerisque. Duis non est id libero bibendum facilisis. Ut maximus molestie odio in dictum. Fusce elementum ipsum non mauris cursus, at fringilla elit hendrerit. Pellentesque vitae suscipit ligula. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec semper sit amet elit sit amet bibendum. Vivamus non dolor magna.


text:
package network::hirschmann::standard::snmp::mode::components::temperature;

use strict;
use warnings;

# In MIB 'hmpriv.mib'
my $mapping = {
    hmTemperature => { oid => '.1.3.6.1.4.1.248.14.2.5.1' },
    hmTempUprLimit => { oid => '.1.3.6.1.4.1.248.14.2.5.2' },
    hmTempLwrLimit => { oid => '.1.3.6.1.4.1.248.14.2.5.3' },
};
my $oid_hmTempTable = '.1.3.6.1.4.1.248.14.2.5';

sub load {
    my ($self) = @_;

    push @{$self->{request}}, { oid => $oid_hmTempTable };
}

sub check {
    my ($self) = @_;

    $self->{output}->output_add(long_msg => "Checking temperatures");
    $self->{components}->{temperature} = {name => 'temperatures', total => 0, skip => 0};
    return if ($self->check_filter(section => 'temperature'));

    return if (!defined($self->{results}->{$oid_hmTempTable}->{$mapping->{hmTemperature}->{oid} . '.0'}));
    my $instance = 0;
    my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_hmTempTable}, instance => $instance);

    next if ($self->check_filter(section => 'temperature', instance => $instance));
    $self->{components}->{temperature}->{total}++;

    $self->{output}->output_add(long_msg => sprintf("temperature is %dC [instance: %s].",
                                                    $result->{hmTemperature},
                                                    $instance));
    my ($exit, $warn, $crit, $checked) = $self->get_severity_numeric(section => 'temperature', instance => $instance, value => $result->{hmTemperature});
    if ($checked == 0) {
        my $warn_th = '';
        my $crit_th = $result->{hmTempLwrLimit} . ':' . $result->{hmTempUprLimit};
        $self->{perfdata}->threshold_validate(label => 'warning-temperature-instance-' . $instance, value => $warn_th);
        $self->{perfdata}->threshold_validate(label => 'critical-temperature-instance-' . $instance, value => $crit_th);
        $warn = $self->{perfdata}->get_perfdata_for_output(label => 'warning-temperature-instance-' . $instance);
        $crit = $self->{perfdata}->get_perfdata_for_output(label => 'critical-temperature-instance-' . $instance);
    }
    if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
        $self->{output}->output_add(severity => $exit,
                                    short_msg => sprintf("Temperature is %s degree centigrade", $result->{hmTemperature}));
    }
    $self->{output}->perfdata_add(label => "temp", unit => 'C',
                                  value => $result->{hmTemperature},
                                  warning => $warn,
                                  critical => $crit);
}

1;


text:
[![Build Status](https://travis-ci.org/servo/saltfs.svg)](https://travis-ci.org/servo/saltfs)

## What's going on?

Salt is a configuration management tool that we use to automate Servo's
infrastructure. See [the tutorials](https://docs.saltstack.com/en/2015.5/topics/tutorials/index.html) to get started.

## Contributing

There are guides available on [the servo wiki](https://github.com/servo/servo/wiki/Buildbot-administration).
If you see a way that these configurations could be improved, or try to set up
your own instance and run into trouble, file [an issue](https://github.com/servo/saltfs/issues/new)!

## Travis

TravisCI is set up to test all configurations.

## License

This repository is distributed under the terms of both the MIT license
and the Apache License (Version 2.0).

See [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT) for details.


text:
import { WindsState, Action } from "common/types";
import windReducer from "common/reducers/wind";
import { actions } from "common/actions";
import { omit } from "underscore";

const initialState: WindsState = {};

const windOpenedType = actions.windOpened({} as any).type;
const windClosedType = actions.windClosed({} as any).type;

export default function (state: WindsState, action: Action<any>) {
  if (typeof state === "undefined") {
    return initialState;
  }

  if (action) {
    if (action.type === windOpenedType) {
      const { wind } = action.payload as typeof actions.windOpened["payload"];

      let windState = windReducer(undefined, null);
      windState = windReducer(windState, action);

      return {
        ...state,
        [wind]: windState,
      };
    }

    if (action.type === windClosedType) {
      const { wind } = action.payload as typeof actions.windClosed["payload"];
      return omit(state, wind);
    }

    if (action.payload && action.payload.wind) {
      const { wind } = action.payload;
      if (typeof state[wind] !== "undefined") {
        return {
          ...state,
          [wind]: windReducer(state[wind], action),
        };
      }
    }

    let newState: WindsState = {};
    let changed = false;
    for (const k of Object.keys(state)) {
      newState[k] = windReducer(state[k], action);
      if (state[k] !== newState[k]) {
        changed = true;
      }
    }
    if (changed) {
      return newState;
    }
  }

  return state;
}


text:
from enthought.traits.api import Float, String
from os import access,  F_OK
"""
Utility to convert the Oslo Glass Data Files to the RayTrace Glass Data Format.
"""

from optparse import OptionParser

parser=OptionParser(usage="usage: %prog -i inputfile -o outputfile",
                    description=\
                    "Utility to convert de Oslo Glass Data Files, to the RayTrace"\
                    "material library file")

parser.add_option("-i", dest="inputfile", help="GLS file to convert")
parser.add_option("-o",  dest="outputfile",  help="RTGL file to create")
(options, args) = parser.parse_args()

if options.inputfile==None:
     parser.error("\n\nError: Input filename must be given.\n\n")

print "\n\n\nProcessing file", options.inputfile, "\n\n\n"
try:
    f=open(options.inputfile, 'r')
except:
    print "File ", options.inputfile,  "not found"

lines=f.readlines()
f.close()

try:
    version, size, library=lines[0].split(None, 2)
    s=float(size)
except:
    exit("The input file seems not to be an OSLO glass description file")

if version not in ("5.00","5.11","5.31","5.32","5.41","6.02" , "6.03"):
    print "Library version migth not be supported. Please verify the output file"

# Check if the output file exists

if access(options.outputfile, F_OK):
    exit("The outputfile already exists. Use a diferent one.\n\n")

fo=open(options.outputfile, "w")

# Write the header of the library
# Library type RayTraceGlassLibrary Version 0
fo.write("RTGL-0\n")
# Description line allways tab separated
# ref - Glass reference as given by the manufacturer
# nd  - Refraction index for the d line
# vd  - Abbe's number for the d line
# B1,B2,B3,C1,C2,C3 - Dispersion constants for the glass

fo.write("ref\tnd\tvd\tB1\tB2\tB3\tC1\tC2\tC3\n")

for line in lines[1:]:

    line_data=line.split()

    # Skip blank lines
    if len(line_data)!=0:
        ndisp_coef=int(line_data[13])
        if ndisp_coef ==6:
            ref=line_data[0]
            nd=line_data[1]
            vd=line_data[2]
            B1=line_data[14]
            B2=line_data[15]
            B3=line_data[16]
            C1=line_data[17]
            C2=line_data[18]
            C3=line_data[19]
            fo.write("\"%s\"\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n"%\
                     (ref, nd, vd, B1, B2, B3, C1, C2, C3))


text:
using System;
using System.Runtime.Serialization;

namespace QueueP
{
    /// <summary>
    /// Исключение, вызываемое в случае попытки достать значение из пустой очереди
    /// </summary>
    [Serializable]
    public class QueueEmptyException : Exception
    {
        /// <summary>
        /// Конструктор по умолчанию, кидающий исключение типа <see cref="QueueEmptyException"/>
        /// </summary>
        public QueueEmptyException()
        {
        }

        /// <summary>
        /// Конструктор, с аргументом сообщение
        /// </summary>
        /// <param name="message">Сообщение</param>
        public QueueEmptyException(string message) : base(message)
        {
        }

        /// <summary>
        /// Конструктор, с аргументом сообщение и внутренним исключением
        /// </summary>
        /// <param name="message">Сообщение</param>
        /// <param name="innerException">Внутренне исключение</param>
        public QueueEmptyException(string message, Exception innerException) : base(message, innerException)
        {
        }

        protected QueueEmptyException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }
    }
}


text:
import ParserBlock from '../parserTypes/ParserBlock';
import CompilerBlock from './CompilerBlock';
import document from '../helper/document';
import Environment from '../helper/Environment';

const CONTENT_INDEX = 0;

class Dom extends CompilerBlock {

  constructor(block: ParserBlock, environment: Environment, parentBlock?: CompilerBlock) {
    super(block, environment, parentBlock);
    this.element = document.createText(this.getParameterValue(CONTENT_INDEX));
    this.appendToParent(this.element);
  }
}

export default Dom;


text:
iOS development

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae.

Android development

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae.

Windows Phone development

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae.

Ruby on Rails development

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae.

Javascript development

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae.

Responsive web design

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae.


text:
#import "ALPValidatorRule.h"

const NSString * ALPValidatorRuleDefaultErrorMessageForType(ALPValidatorRuleType type) {
    switch (type) {
        case ALPValidatorRuleTypeRequired:              return @"String is required.";
        case ALPValidatorRuleTypeMinLength:             return @"String is too short.";
        case ALPValidatorRuleTypeMaxLength:             return @"String is too long.";
        case ALPValidatorRuleTypeEmail:                 return @"String isn't a valid email address.";
        case ALPValidatorRuleTypeRegex:                 return @"String doesn't match a pattern.";
        case ALPValidatorRuleTypeRemote:                return @"String doesn't satisfy a remote condition.";
        case ALPValidatorRuleTypeCustom:                return @"String doesn't satisfy a custom condition.";
        case ALPValidatorRuleTypeStringRange:           return @"String character length is not in the correct range.";
        case ALPValidatorRuleTypeNumericRange:          return @"Number is not in the correct range..";
        case ALPValidatorRuleTypeEqual:                 return @"Instance should be identical to another instance";
        case ALPValidatorRuleTypeStringContainsNumber:  return @"String requires a numeric character.";
    }
}

@interface ALPValidatorRule ()

@property (nonatomic) ALPValidatorRuleType type;
@property (copy, nonatomic) NSString *errorMessage;

@end

@implementation ALPValidatorRule

#pragma mark Init

- (id)initWithType:(ALPValidatorRuleType)type invalidMessage:(NSString *)message
{
    self = [super init];
    if (self) {
        _type = type;
        _errorMessage = message;
        if (!message) _errorMessage = ALPValidatorRuleDefaultErrorMessageForType(type);
    }
    return self;
}

#pragma mark Validate

- (BOOL)isValidationRuleSatisfied:(id)instance
{
    return NO;
}

@end


text:
package org.kaazing.gateway.server.topic;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

import java.util.concurrent.CountDownLatch;

import org.junit.Test;

import com.hazelcast.core.ITopic;
import com.hazelcast.core.MessageListener;

public abstract class AbstractClusterTopicTest {

    @Test
    public void shouldCallMessageListenersOnTwoThreads() throws InterruptedException {
        ITopic<String> topicMember1 = getTopicForShouldCallMessageListenersOnTwoThreads();
        CountDownLatch listenersCalled = new CountDownLatch(2);
        topicMember1.addMessageListener(message -> {
            assertEquals("msg1", message.getMessageObject());
            listenersCalled.countDown();
        });
        Thread t = new Thread(() -> {
            topicMember1.addMessageListener(message -> {
                assertEquals("msg1", message.getMessageObject());
                listenersCalled.countDown();
            });
        });
        t.start();
        t.join();
        topicMember1.publish("msg1");
        listenersCalled.await();
        assertEquals(1, topicMember1.getLocalTopicStats().getPublishOperationCount());
        assertEquals(2, topicMember1.getLocalTopicStats().getReceiveOperationCount());
        topicMember1.destroy();

    }

    @Test
    public void shouldNotifyListenersIfOneThrowsException() throws InterruptedException {
        ITopic<String> topicMessageListenerMember1 = getTopicMember1ForShouldNotifyListenersIfOneThrowsException();
        CountDownLatch listenersCalled = new CountDownLatch(3);
        topicMessageListenerMember1.addMessageListener(message -> listenersCalled.countDown());
        topicMessageListenerMember1.addMessageListener(message -> {
            listenersCalled.countDown();
            throw new NullPointerException();
        });
        topicMessageListenerMember1.addMessageListener(message -> listenersCalled.countDown());
        ITopic<String> topicMessageListenerMember2 = getTopicMember2ForShouldNotifyListenersIfOneThrowsException();
        topicMessageListenerMember2.publish("msg1");
        listenersCalled.await();
        assertEquals(1, topicMessageListenerMember2.getLocalTopicStats().getPublishOperationCount());
        assertEquals(3, topicMessageListenerMember1.getLocalTopicStats().getReceiveOperationCount());
        topicMessageListenerMember1.destroy();
        topicMessageListenerMember2.destroy();
    }

    @Test
    public void shouldCallMultipleTimesMessageListener() throws InterruptedException {
        ITopic<String> topicSameListenerMember1 = getTopicMember1ForShouldCallMultipleTimesMessageListener();
        CountDownLatch listenersCalledSameListener = new CountDownLatch(2);
        MessageListener<String> m = message -> listenersCalledSameListener.countDown();
        topicSameListenerMember1.addMessageListener(m);
        topicSameListenerMember1.addMessageListener(m);
        ITopic<String> topicSameListenerMember2 = getTopicMember2ForShouldCallMultipleTimesMessageListener();
        topicSameListenerMember2.publish("msg1");
        listenersCalledSameListener.await();
        assertEquals(1, topicSameListenerMember2.getLocalTopicStats().getPublishOperationCount());
        assertEquals(2, topicSameListenerMember1.getLocalTopicStats().getReceiveOperationCount());
        topicSameListenerMember1.destroy();
        topicSameListenerMember2.destroy();
    }

    @Test
    public void shouldAddAndRemoveMessageListener() throws InterruptedException {
        ITopic<String> topicAddRemoveMember1 = getTopicMember1ForShouldAddAndRemoveMessageListener();
        ITopic<String> topicAddRemoveMember2 = getTopicMember2ForShouldAddAndRemoveMessageListener();
        CountDownLatch listenersCalledAddRemove = new CountDownLatch(1);
        String name = topicAddRemoveMember1.addMessageListener(message -> listenersCalledAddRemove.countDown());
        topicAddRemoveMember2.publish("msg1");
        listenersCalledAddRemove.await();
        topicAddRemoveMember1.removeMessageListener(name);
        topicAddRemoveMember2.publish("msg2");
        assertEquals(2, topicAddRemoveMember2.getLocalTopicStats().getPublishOperationCount());
        assertEquals(1, topicAddRemoveMember1.getLocalTopicStats().getReceiveOperationCount());
        topicAddRemoveMember1.destroy();
        topicAddRemoveMember2.destroy();
    }

    @Test
    public void shouldAllowAddAndRemoveFromMessageListenerDifferentThread() throws InterruptedException {
        ITopic<String> topicMember1 = getTopicMember1ForShouldAllowAddAndRemoveFromMessageListenerDifferentThread();
        ITopic<String> topicMember2 = getTopicMember2ForShouldAllowAddAndRemoveFromMessageListenerDifferentThread();
        CountDownLatch listenerCalled = new CountDownLatch(1);
        MessageListener<String> m1 = message -> {};
        String name = topicMember1.addMessageListener(m1);
        MessageListener<String> m2 = message -> {
            Thread t = new Thread(() -> {
                topicMember1.removeMessageListener(name);
                listenerCalled.countDown();
            });
            t.start();
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        topicMember1.addMessageListener(m2);
        topicMember2.publish("msg1");
        listenerCalled.await();
        assertFalse(topicMember1.removeMessageListener(name)); // already removed
        topicMember1.destroy();
        topicMember2.destroy();
    }

    @Test
    public void shouldPubSubFromMessageListeners() throws InterruptedException {
        CountDownLatch listenersCalled = new CountDownLatch(1);
        ITopic<String> topic1 = getTopicMember1ForShouldPubSubFromMessageListeners();
        ITopic<String> topic2 = getTopicMember2ForShouldPubSubFromMessageListeners();
        MessageListener<String> m1 = message -> topic2.publish("Message sent to topic2");
        MessageListener<String> m2 = message -> listenersCalled.countDown();
        topic1.addMessageListener(m1);
        topic2.addMessageListener(m2);

        topic1.publish("trigger m2");
        listenersCalled.await();
        assertEquals(1, topic1.getLocalTopicStats().getPublishOperationCount());
        assertEquals(1, topic1.getLocalTopicStats().getReceiveOperationCount());

        assertEquals(1, topic2.getLocalTopicStats().getPublishOperationCount());
        assertEquals(1, topic2.getLocalTopicStats().getReceiveOperationCount());
        topic1.destroy();
        topic2.destroy();
    }

    @Test
    public void shouldNotDeadlockNestedPublishOnDifferentThread() throws InterruptedException {
        ITopic<String> topic = getTopicMember1ForShouldNotDeadlockNestedPublishOnDifferentThread();
        CountDownLatch listenerCalled = new CountDownLatch(10);
        topic.addMessageListener(message -> {
            listenerCalled.countDown();
            Thread t = new Thread(() -> {
                if (listenerCalled.getCount() > 0) {
                    topic.publish("Resend: " + message.getMessageObject());
                }
            });
            t.start();
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        topic.publish("KickOff");
        listenerCalled.await();
        assertEquals(10, topic.getLocalTopicStats().getPublishOperationCount());
        assertEquals(10, topic.getLocalTopicStats().getReceiveOperationCount());
        topic.destroy();
    }

    @Test(expected = NullPointerException.class)
    public void shouldNotAddNullMessageListener() {
        ITopic<String> topic = getTopicMember1ForShouldNotAddNullMessageListener();
        topic.addMessageListener(null);
    }

    @Test
    public void shouldDetectClassIncompatibility() throws InterruptedException {
        CountDownLatch registeredBadListenerType = new CountDownLatch(2);
        ITopic<String> topic = getTopicMember1ForShouldDetectClassIncompatibility();
        topic.addMessageListener(message -> registeredBadListenerType.countDown());
        ITopic<Integer> topic2 = getTopicMember2ForShouldDetectClassIncompatibility();
        topic2.addMessageListener(message -> {
            try {
                int i = message.getMessageObject() + 1;
            } catch (ClassCastException e) {
                registeredBadListenerType.countDown();
            }
        });
        topic.publish("xyz");
        registeredBadListenerType.await();
        assertEquals(1, topic.getLocalTopicStats().getPublishOperationCount());
        topic.destroy();
        topic2.destroy();
    }

    protected abstract ITopic<String> getTopicForShouldCallMessageListenersOnTwoThreads();

    protected abstract ITopic<String> getTopicMember1ForShouldNotifyListenersIfOneThrowsException();

    protected abstract ITopic<String> getTopicMember2ForShouldNotifyListenersIfOneThrowsException();

    protected abstract ITopic<String> getTopicMember1ForShouldCallMultipleTimesMessageListener();

    protected abstract ITopic<String> getTopicMember2ForShouldCallMultipleTimesMessageListener();

    protected abstract ITopic<String> getTopicMember1ForShouldAddAndRemoveMessageListener();

    protected abstract ITopic<String> getTopicMember2ForShouldAddAndRemoveMessageListener();

    protected abstract ITopic<String> getTopicMember1ForShouldAllowAddAndRemoveFromMessageListenerDifferentThread();

    protected abstract ITopic<String> getTopicMember2ForShouldAllowAddAndRemoveFromMessageListenerDifferentThread();

    protected abstract ITopic<String> getTopicMember1ForShouldPubSubFromMessageListeners();

    protected abstract ITopic<String> getTopicMember2ForShouldPubSubFromMessageListeners();

    protected abstract ITopic<String> getTopicMember1ForShouldNotDeadlockNestedPublishOnDifferentThread();

    protected abstract ITopic<String> getTopicMember1ForShouldNotAddNullMessageListener();

    protected abstract ITopic<String> getTopicMember1ForShouldDetectClassIncompatibility();

    protected abstract ITopic<Integer> getTopicMember2ForShouldDetectClassIncompatibility();

}


text:
package com.speedment.runtime.config.mutator.trait;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;

import com.speedment.runtime.config.Document;
import com.speedment.runtime.config.mutator.DocumentMutator;
import com.speedment.runtime.config.parameter.OrderType;
import com.speedment.runtime.config.trait.HasOrderType;
import org.junit.jupiter.api.Test;

public interface HasOrderTypeMutatorMixin<TYPE extends Document & HasOrderType,
        MUTATOR extends DocumentMutator<TYPE> & HasOrderTypeMutator<TYPE>>
        extends BaseTraitMixin<TYPE, MUTATOR> {

    @Test
    default void setOrderType() {
        assertDoesNotThrow(() -> getMutatorInstance().setOrderType(OrderType.NONE));
    }
}


text:
package org.apache.flink.client.cli;

import org.apache.flink.configuration.Configuration;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;

/**
 * The default CLI which is used for interaction with standalone clusters.
 */
public class DefaultCLI extends AbstractCustomCommandLine {

	public static final String ID = "default";

	public DefaultCLI(Configuration configuration) {
		super(configuration);
	}

	@Override
	public boolean isActive(CommandLine commandLine) {
		// always active because we can try to read a JobManager address from the config
		return true;
	}

	@Override
	public String getId() {
		return ID;
	}

	@Override
	public void addGeneralOptions(Options baseOptions) {
		super.addGeneralOptions(baseOptions);
	}
}


text:
package com.ynov.android.gluciddiab.dataUtils;

import android.provider.BaseColumns;

/**
 * Created by Malo on 30/03/2017.
 */

public class KfcContract {
    public static final class KFCListEntry implements BaseColumns {
        public static final String TABLE_NAME = "kfcdata";
        public static final String CATEGORIE = "categorie";
        public static final String PRODUCT_NAME = "menuname";
        public static final String GLU_LENT = "glucoselent";
        public static final String GLU_RAPIDE = "glucoserapide";
        public static final String IMAGE_NAME = "image";
        public static final String COLUMN_TIMESTAMP = "timestamp";
    }
}


text:
package org.bitcoinj.params;

import org.bitcoinj.core.BitcoinSerializer;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.utils.MonetaryFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Parameters for Bitcoin-like networks.
 */
public abstract class AbstractNetParams extends NetworkParameters {

    private static final Logger log = LoggerFactory.getLogger(AbstractNetParams.class);

    /**
     * Constructor which defaults to bitcoin uri scheme.
     */
    public AbstractNetParams() {
        super();
    }

    @Override
    public Coin getMaxMoney() {
        return MAX_MONEY;
    }

    @Override
    public Coin getMinNonDustOutput() {
        return Transaction.MIN_NONDUST_OUTPUT;
    }

    @Override
    public MonetaryFormat getMonetaryFormat() {
        return new MonetaryFormat();
    }

    @Override
    public int getProtocolVersionNum(final ProtocolVersion version) {
        return version.getBitcoinProtocolVersion();
    }

    @Override
    public BitcoinSerializer getSerializer(boolean parseRetain) {
        return new BitcoinSerializer(this, parseRetain);
    }

    @Override
    public String getUriScheme() {
        return uriScheme;
    }

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


text:
const Knex = require('knex')
const knexConfig = require('../knexfile')[process.env.NODE_ENV || 'development']

const knex = Knex(knexConfig)

const getAllUsers = () => {
  console.log('Im in the function')
  return knex('bank')
}

const getUserByUsername = (name) => knex('bank').where('username', name)

const addUser = (user) => knex('bank').insert(user)

module.exports = {
  getAllUsers,
  getUserByUsername,
  addUser
}


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef nsChromeRegistry_h
#define nsChromeRegistry_h

#include "nsIChromeRegistry.h"
#include "nsIToolkitChromeRegistry.h"
#include "nsIObserver.h"
#include "nsWeakReference.h"
#include "nsIPrefBranch.h"

#ifdef MOZ_XUL
#include "nsIXULOverlayProvider.h"
#endif

#include "pldhash.h"

#include "nsCOMArray.h"
#include "nsString.h"
#include "nsTHashtable.h"
#include "nsURIHashKey.h"
#include "nsInterfaceHashtable.h"
#include "nsXULAppAPI.h"
#include "nsIResProtocolHandler.h"
#include "nsIXPConnect.h"

#include "mozilla/Omnijar.h"
#include "mozilla/FileLocation.h"

class nsIDOMWindow;
class nsIURL;

// The chrome registry is actually split between nsChromeRegistryChrome and
// nsChromeRegistryContent. The work/data that is common to both resides in
// the shared nsChromeRegistry implementation, with operations that only make
// sense for one side erroring out in the other.

// for component registration
// {47049e42-1d87-482a-984d-56ae185e367a}
#define NS_CHROMEREGISTRY_CID \
{ 0x47049e42, 0x1d87, 0x482a, { 0x98, 0x4d, 0x56, 0xae, 0x18, 0x5e, 0x36, 0x7a } }

class nsChromeRegistry : public nsIToolkitChromeRegistry,
#ifdef MOZ_XUL
                         public nsIXULOverlayProvider,
#endif
                         public nsIObserver,
                         public nsSupportsWeakReference
{
public:
  NS_DECL_ISUPPORTS

  // nsIXULChromeRegistry methods:
  NS_IMETHOD ReloadChrome();
  NS_IMETHOD RefreshSkins();
  NS_IMETHOD AllowScriptsForPackage(nsIURI* url,
                                    bool* _retval);
  NS_IMETHOD AllowContentToAccess(nsIURI* url,
                                  bool* _retval);

  // nsIChromeRegistry methods:
  NS_IMETHOD_(bool) WrappersEnabled(nsIURI *aURI);
  NS_IMETHOD ConvertChromeURL(nsIURI* aChromeURI, nsIURI* *aResult);

  // nsChromeRegistry methods:
  nsChromeRegistry() : mInitialized(false) { }
  virtual ~nsChromeRegistry();

  virtual nsresult Init();

  static already_AddRefed<nsIChromeRegistry> GetService();

  static nsChromeRegistry* gChromeRegistry;

  static nsresult Canonify(nsIURL* aChromeURL);

protected:
  void FlushSkinCaches();
  void FlushAllCaches();

  // Update the selected locale used by the chrome registry, and fire a
  // notification about this change
  virtual nsresult UpdateSelectedLocale() = 0;

  static void LogMessage(const char* aMsg, ...);
  static void LogMessageWithContext(nsIURI* aURL, uint32_t aLineNumber, uint32_t flags,
                                    const char* aMsg, ...);

  virtual nsIURI* GetBaseURIFromPackage(const nsCString& aPackage,
                                        const nsCString& aProvider,
                                        const nsCString& aPath) = 0;
  virtual nsresult GetFlagsFromPackage(const nsCString& aPackage,
                                       uint32_t* aFlags) = 0;

  nsresult SelectLocaleFromPref(nsIPrefBranch* prefs);

  static nsresult RefreshWindow(nsIDOMWindow* aWindow);
  static nsresult GetProviderAndPath(nsIURL* aChromeURL,
                                     nsACString& aProvider, nsACString& aPath);

public:
  static already_AddRefed<nsChromeRegistry> GetSingleton();

  struct ManifestProcessingContext
  {
    ManifestProcessingContext(NSLocationType aType, mozilla::FileLocation &aFile)
      : mType(aType)
      , mFile(aFile)
    { }

    ~ManifestProcessingContext()
    { }

    nsIURI* GetManifestURI();
    nsIXPConnect* GetXPConnect();

    already_AddRefed<nsIURI> ResolveURI(const char* uri);

    NSLocationType mType;
    mozilla::FileLocation mFile;
    nsCOMPtr<nsIURI> mManifestURI;
    nsCOMPtr<nsIXPConnect> mXPConnect;
  };

  virtual void ManifestContent(ManifestProcessingContext& cx, int lineno,
                               char *const * argv, bool platform,
                               bool contentaccessible) = 0;
  virtual void ManifestLocale(ManifestProcessingContext& cx, int lineno,
                              char *const * argv, bool platform,
                              bool contentaccessible) = 0;
  virtual void ManifestSkin(ManifestProcessingContext& cx, int lineno,
                            char *const * argv, bool platform,
                            bool contentaccessible) = 0;
  virtual void ManifestOverlay(ManifestProcessingContext& cx, int lineno,
                               char *const * argv, bool platform,
                               bool contentaccessible) = 0;
  virtual void ManifestStyle(ManifestProcessingContext& cx, int lineno,
                             char *const * argv, bool platform,
                             bool contentaccessible) = 0;
  virtual void ManifestOverride(ManifestProcessingContext& cx, int lineno,
                                char *const * argv, bool platform,
                                bool contentaccessible) = 0;
  virtual void ManifestResource(ManifestProcessingContext& cx, int lineno,
                                char *const * argv, bool platform,
                                bool contentaccessible) = 0;

  // Available flags
  enum {
    // This is a "platform" package (e.g. chrome://global-platform/).
    // Appends one of win/ unix/ mac/ to the base URI.
    PLATFORM_PACKAGE = 1 << 0,

    // This package should use the new XPCNativeWrappers to separate
    // content from chrome. This flag is currently unused (because we call
    // into xpconnect at registration time).
    XPCNATIVEWRAPPERS = 1 << 1,

    // Content script may access files in this package
    CONTENT_ACCESSIBLE = 1 << 2
  };

  bool mInitialized;

  // "Override" table (chrome URI string -> real URI)
  nsInterfaceHashtable<nsURIHashKey, nsIURI> mOverrideTable;
};

#endif // nsChromeRegistry_h


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import {dispatchSimpleEvent} from 'chrome://resources/js/cr.m.js';
import {NativeEventTarget as EventTarget} from 'chrome://resources/js/cr/event_target.m.js';

import {strf, util} from '../../../common/js/util.js';

/**
 * Formatter class for file metadatas.
 */
export class FileMetadataFormatter extends EventTarget {
  constructor() {
    super();
    this.setDateTimeFormat(true);

    /** @private {?Intl.DateTimeFormat} */
    this.timeFormatter_;

    /** @private {?Intl.DateTimeFormat} */
    this.dateFormatter_;
  }

  /**
   * Sets date and time format.
   * @param {boolean} use12hourClock True if 12 hours clock, False if 24 hours.
   */
  setDateTimeFormat(use12hourClock) {
    const locale = util.getCurrentLocaleOrDefault();
    this.timeFormatter_ = new Intl.DateTimeFormat(
        locale, {hour: 'numeric', minute: 'numeric', hour12: use12hourClock});
    this.dateFormatter_ = new Intl.DateTimeFormat(locale, {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: 'numeric',
      minute: 'numeric',
      hour12: use12hourClock
    });
    dispatchSimpleEvent(this, 'date-time-format-changed');
  }

  /**
   * Generates a formatted modification time text.
   * @param {Date} modTime
   * @return {string} A string that represents modification time.
   */
  formatModDate(modTime) {
    if (!modTime) {
      return '...';
    }
    const today = new Date();
    today.setHours(0);
    today.setMinutes(0);
    today.setSeconds(0);
    today.setMilliseconds(0);

    /**
     * Number of milliseconds in a day.
     */
    const MILLISECONDS_IN_DAY = 24 * 60 * 60 * 1000;

    if (isNaN(modTime.getTime())) {
      // In case of 'Invalid Date'.
      return '--';
    } else if (
        modTime >= today && modTime < today.getTime() + MILLISECONDS_IN_DAY) {
      return strf('TIME_TODAY', this.timeFormatter_.format(modTime));
    } else if (modTime >= today - MILLISECONDS_IN_DAY && modTime < today) {
      return strf('TIME_YESTERDAY', this.timeFormatter_.format(modTime));
    } else {
      return this.dateFormatter_.format(modTime);
    }
  }

  /**
   * Generates a formatted filesize text.
   * @param {number=} size
   * @param {boolean=} hosted
   * @param {boolean=} addPrecision addPrecision used to optionally add more
   *     precision digits to the formatted filesize text.
   * @return {string} A string that represents a file size.
   */
  formatSize(size, hosted, addPrecision = false) {
    if (size === null || size === undefined) {
      return '...';
    } else if (size === -1) {
      return '--';
    } else if (size === 0 && hosted) {
      return '--';
    } else {
      return util.bytesToString(size, addPrecision ? 1 : 0);
    }
  }
}


text:
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef FLUTTER_FLUTTERBINARYMESSENGER_H_
#define FLUTTER_FLUTTERBINARYMESSENGER_H_

#import <Foundation/Foundation.h>

#include "FlutterMacros.h"

NS_ASSUME_NONNULL_BEGIN
/**
 * A message reply callback.
 *
 * Used for submitting a binary reply back to a Flutter message sender. Also used
 * in for handling a binary message reply received from Flutter.
 *
 * @param reply The reply.
 */
typedef void (^FlutterBinaryReply)(NSData* _Nullable reply);

/**
 * A strategy for handling incoming binary messages from Flutter and to send
 * asynchronous replies back to Flutter.
 *
 * @param message The message.
 * @param reply A callback for submitting an asynchronous reply to the sender.
 */
typedef void (^FlutterBinaryMessageHandler)(NSData* _Nullable message, FlutterBinaryReply reply);

typedef int64_t FlutterBinaryMessengerConnection;

/**
 * A facility for communicating with the Flutter side using asynchronous message
 * passing with binary messages.
 *
 * Implementated by:
 * - `FlutterBasicMessageChannel`, which supports communication using structured
 * messages.
 * - `FlutterMethodChannel`, which supports communication using asynchronous
 * method calls.
 * - `FlutterEventChannel`, which supports commuication using event streams.
 */
FLUTTER_EXPORT
@protocol FlutterBinaryMessenger <NSObject>
/**
 * Sends a binary message to the Flutter side on the specified channel, expecting
 * no reply.
 *
 * @param channel The channel name.
 * @param message The message.
 */
- (void)sendOnChannel:(NSString*)channel message:(NSData* _Nullable)message;

/**
 * Sends a binary message to the Flutter side on the specified channel, expecting
 * an asynchronous reply.
 *
 * @param channel The channel name.
 * @param message The message.
 * @param callback A callback for receiving a reply.
 */
- (void)sendOnChannel:(NSString*)channel
              message:(NSData* _Nullable)message
          binaryReply:(FlutterBinaryReply _Nullable)callback;

/**
 * Registers a message handler for incoming binary messages from the Flutter side
 * on the specified channel.
 *
 * Replaces any existing handler. Use a `nil` handler for unregistering the
 * existing handler.
 *
 * @param channel The channel name.
 * @param handler The message handler.
 * @return An identifier that represents the connection that was just created to the channel.
 */
- (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(NSString*)channel
                                          binaryMessageHandler:
                                              (FlutterBinaryMessageHandler _Nullable)handler;

/**
 * Clears out a channel's message handler if that handler is still the one that
 * was created as a result of
 * `setMessageHandlerOnChannel:binaryMessageHandler:`.
 *
 * @param connection The result from `setMessageHandlerOnChannel:binaryMessageHandler:`.
 */
- (void)cleanupConnection:(FlutterBinaryMessengerConnection)connection;
@end
NS_ASSUME_NONNULL_END
#endif  // FLUTTER_FLUTTERBINARYMESSENGER_H_


text:
package net.mindengine.blogix.web.routes;

public class RouteParserException extends RuntimeException {

    /**
     *
     */
    private static final long serialVersionUID = 2131649402081052624L;

    public RouteParserException() {
        super();
    }

    public RouteParserException(String arg0, Throwable arg1) {
        super(arg0, arg1);
    }

    public RouteParserException(String arg0) {
        super(arg0);
    }

    public RouteParserException(Throwable arg0) {
        super(arg0);
    }
}


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
<hibernate-mapping>
	<class name="com.jcommerce.core.model.SearchEngine"
		table="tis_searchengine">
		<id name="id" column="id" type="string" length="32">
			<generator class="uuid.hex" />
		</id>
		<property name="searchEngine" column="searchengine" length="20" />
		<property name="count" column="count" length="8" />
		<property name="date" column="date" />

	</class>
</hibernate-mapping>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">GoldIndex</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="str_checkbox_autorefresh">AutoRefresh</string>
    <string name="str_toggle_button_refresh">Refresh</string>
    <string name="str_toggle_button_refreshing">Refreshing...</string>

</resources>


text:
package org.apache.flink.table.functions;

import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.table.annotation.DataTypeHint;
import org.apache.flink.table.annotation.FunctionHint;
import org.apache.flink.table.catalog.DataTypeFactory;

/**
 * Base class for user-defined {@link AggregateFunction} and {@link TableAggregateFunction}.
 *
 *
This class is used for unified handling of imperative aggregating functions. Concrete
 * implementations should extend from {@link AggregateFunction} or {@link TableAggregateFunction}.
 *
 * @param <T> final result type of the aggregation
 * @param <ACC> intermediate result type during the aggregation
 */
@PublicEvolving
public abstract class ImperativeAggregateFunction<T, ACC> extends UserDefinedFunction {

    /**
     * Creates and initializes the accumulator for this {@link ImperativeAggregateFunction}.
     *
     *
The accumulator is an intermediate data structure that stores the aggregated values until
     * a final aggregation result is computed.
     *
     * @return the accumulator with the initial value
     */
    public abstract ACC createAccumulator();

    /**
     * Returns the {@link TypeInformation} of the {@link ImperativeAggregateFunction}'s result.
     *
     * @return The {@link TypeInformation} of the {@link ImperativeAggregateFunction}'s result or
     *     null if the result type should be automatically inferred.
     * @deprecated This method uses the old type system and is based on the old reflective
     *     extraction logic. The method will be removed in future versions and is only called when
     *     using the deprecated {@code TableEnvironment.registerFunction(...)} method. The new
     *     reflective extraction logic (possibly enriched with {@link DataTypeHint} and {@link
     *     FunctionHint}) should be powerful enough to cover most use cases. For advanced users, it
     *     is possible to override {@link UserDefinedFunction#getTypeInference(DataTypeFactory)}.
     */
    @Deprecated
    public TypeInformation<T> getResultType() {
        return null;
    }

    /**
     * Returns the {@link TypeInformation} of the {@link ImperativeAggregateFunction}'s accumulator.
     *
     * @return The {@link TypeInformation} of the {@link ImperativeAggregateFunction}'s accumulator
     *     or null if the accumulator type should be automatically inferred.
     * @deprecated This method uses the old type system and is based on the old reflective
     *     extraction logic. The method will be removed in future versions and is only called when
     *     using the deprecated {@code TableEnvironment.registerFunction(...)} method. The new
     *     reflective extraction logic (possibly enriched with {@link DataTypeHint} and {@link
     *     FunctionHint}) should be powerful enough to cover most use cases. For advanced users, it
     *     is possible to override {@link UserDefinedFunction#getTypeInference(DataTypeFactory)}.
     */
    @Deprecated
    public TypeInformation<ACC> getAccumulatorType() {
        return null;
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <Button
            android:id="@+id/widget_button_garage_opener"
            android:layout_width="wrap_content"
            android:textColor="@drawable/widget_button_text_colour"
            android:paddingTop="10dp"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:background="@drawable/widget"/>

</RelativeLayout>


text:
package io.truthencode.ddo.model.feats

import io.truthencode.ddo.model.classes.HeroicCharacterClass
import io.truthencode.ddo.model.classes.HeroicCharacterClass.{Alchemist, Artificer}
import io.truthencode.ddo.support.requisite.{FeatRequisiteImpl, GrantsToClass, RequiresAllOfClass}

/**
 * Created by adarr on 2/16/2017.
 */
protected[feats] trait ArtificerKnowledgePotions
  extends FeatRequisiteImpl with ArtificerKnowledgePrefix with Passive with GrantsToClass
  with RequiresAllOfClass {
  self: ClassFeat =>
  private lazy val levels = List(2, 5, 8, 11, 14)
  private lazy val values = for {
    l <- levels
    c <- List(Artificer, Alchemist)
  } yield (c, l)
  override def anyOfClass: Seq[(HeroicCharacterClass, Int)] = values

  override def grantToClass: Seq[(HeroicCharacterClass, Int)] = values
}


text:
import ByteEncoder from '../ByteEncoder'
import Encoder from '../Encoder'
import StringUtil from '../StringUtil'

const meta = {
  name: 'base64',
  title: 'Base64',
  category: 'Encoding',
  type: 'encoder'
}

/**
 * The default Base64 base alphabet
 * @type {string}
 */
const defaultAlphabet =
  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'

/**
 * Array of Base64 variant options extending the default options.
 * @type {object[]}
 */
const variants = [
  {
    name: 'base64',
    label: 'Base64 (RFC 3548, RFC 4648)',
    description: null,
    alphabet: `${defaultAlphabet}+/`
  },
  {
    name: 'base64url',
    label: 'Base64url (RFC 4648 §5)',
    description: 'URL and Filename Safe Alphabet',
    alphabet: `${defaultAlphabet}-_`,
    paddingOptional: true
  },
  {
    name: 'rfc2045',
    label: 'Transfer encoding for MIME (RFC 2045)',
    description: null,
    alphabet: `${defaultAlphabet}+/`,
    foreignCharacters: true,
    maxLineLength: 76
  },
  {
    name: 'rfc1421',
    label: 'Original Base64 (RFC 1421)',
    description: 'Privacy-Enhanced Mail (PEM)',
    alphabet: `${defaultAlphabet}+/`,
    maxLineLength: 64
  },
  {
    name: 'custom',
    label: 'Custom'
  }
]

/**
 * Encoder brick for base64 encoding and decoding
 */
export default class Base64Encoder extends Encoder {
  /**
   * Returns brick meta.
   * @return {object}
   */
  static getMeta () {
    return meta
  }

  /**
   * Constructor
   */
  constructor () {
    super()
    this.addSettings([
      {
        name: 'variant',
        type: 'enum',
        value: variants[0].name,
        elements: variants.map(variant => variant.name),
        labels: variants.map(variant => variant.label),
        descriptions: variants.map(variant => variant.description),
        randomizable: false
      },
      {
        name: 'alphabet',
        type: 'text',
        value: variants[0].alphabet,
        uniqueChars: true,
        minLength: 64,
        maxLength: 64,
        caseSensitivity: true,
        visible: false
      },
      {
        name: 'padding',
        type: 'text',
        value: '=',
        blacklistChars: variants[0].alphabet,
        minLength: 1,
        maxLength: 1,
        randomizable: false,
        visible: false,
        width: 6
      },
      {
        name: 'paddingOptional',
        type: 'boolean',
        value: false,
        randomizable: false,
        visible: false,
        width: 6
      }
    ])
  }

  /**
   * Performs encode on given content.
   * @protected
   * @param {Chain} content
   * @return {number[]|string|Uint8Array|Chain} Encoded content
   */
  performEncode (content) {
    // Forward request to the internal byte encoder
    return ByteEncoder.base64StringFromBytes(
      content.getBytes(),
      this.getVariantOptions())
  }

  /**
   * Performs decode on given content.
   * @protected
   * @param {Chain} content
   * @return {number[]|string|Uint8Array|Chain} Decoded content
   */
  performDecode (content) {
    // Forward request to the internal byte encoder
    return ByteEncoder.bytesFromBase64String(
      content.getString(),
      this.getVariantOptions())
  }

  /**
   * Triggered when a setting field has changed.
   * @protected
   * @param {Field} setting Sender setting field
   * @param {mixed} value New field value
   */
  settingValueDidChange (setting, value) {
    switch (setting.getName()) {
      case 'variant': {
        // Make alphabet and padding settings available with the custom variant
        this.getSetting('alphabet').setVisible(value === 'custom')
        this.getSetting('padding').setVisible(value === 'custom')
        this.getSetting('paddingOptional').setVisible(value === 'custom')
        break
      }

      case 'alphabet': {
        // Alphabet characters are not allowed to be used as padding
        this.getSetting('padding').setBlacklistChars(value)
        break
      }
    }
  }

  /**
   * Returns the current variant options.
   * @return {object} Variant options
   */
  getVariantOptions () {
    const name = this.getSettingValue('variant')
    if (name === 'custom') {
      // Compose custom options
      return {
        alphabet: this.getSettingValue('alphabet').getString(),
        padding: this.getSettingValue('padding').getCharAt(0),
        paddingOptional: this.getSettingValue('paddingOptional')
      }
    }

    // Find variant options
    return variants.find(variant => variant.name === name)
  }
}


text:
import {CssSelector, SelectorMatcher, createElementCssSelector} from '@angular/compiler';
import {Compiler, CompilerOptions, ComponentFactory, Injector, NgModule, NgModuleRef, NgZone, Provider, Testability, Type} from '@angular/core';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';

import * as angular from './angular_js';
import {NG1_COMPILE, NG1_INJECTOR, NG1_PARSE, NG1_ROOT_SCOPE, NG1_TESTABILITY, NG2_COMPILER, NG2_COMPONENT_FACTORY_REF_MAP, NG2_INJECTOR, NG2_ZONE, REQUIRE_INJECTOR} from './constants';
import {DowngradeNg2ComponentAdapter} from './downgrade_ng2_adapter';
import {ComponentInfo, getComponentInfo} from './metadata';
import {UpgradeNg1ComponentAdapterBuilder} from './upgrade_ng1_adapter';
import {Deferred, controllerKey, getAttributesAsArray, onError} from './util';

let upgradeCount: number = 0;

/**
 * Use `UpgradeAdapter` to allow Angular 1 and Angular 2+ to coexist in a single application.
 *
 * The `UpgradeAdapter` allows:
 * 1. creation of Angular 2+ component from Angular 1 component directive
 *    (See [UpgradeAdapter#upgradeNg1Component()])
 * 2. creation of Angular 1 directive from Angular 2+ component.
 *    (See [UpgradeAdapter#downgradeNg2Component()])
 * 3. Bootstrapping of a hybrid Angular application which contains both of the frameworks
 *    coexisting in a single application.
 *
 * ## Mental Model
 *
 * When reasoning about how a hybrid application works it is useful to have a mental model which
 * describes what is happening and explains what is happening at the lowest level.
 *
 * 1. There are two independent frameworks running in a single application, each framework treats
 *    the other as a black box.
 * 2. Each DOM element on the page is owned exactly by one framework. Whichever framework
 *    instantiated the element is the owner. Each framework only updates/interacts with its own
 *    DOM elements and ignores others.
 * 3. Angular 1 directives always execute inside Angular 1 framework codebase regardless of
 *    where they are instantiated.
 * 4. Angular 2+ components always execute inside Angular 2+ framework codebase regardless of
 *    where they are instantiated.
 * 5. An Angular 1 component can be upgraded to an Angular 2+ component. This creates an
 *    Angular 2+ directive, which bootstraps the Angular 1 component directive in that location.
 * 6. An Angular 2+ component can be downgraded to an Angular 1 component directive. This creates
 *    an Angular 1 directive, which bootstraps the Angular 2+ component in that location.
 * 7. Whenever an adapter component is instantiated the host element is owned by the framework
 *    doing the instantiation. The other framework then instantiates and owns the view for that
 *    component. This implies that component bindings will always follow the semantics of the
 *    instantiation framework. The syntax is always that of Angular 2+ syntax.
 * 8. Angular 1 is always bootstrapped first and owns the bottom most view.
 * 9. The new application is running in Angular 2+ zone, and therefore it no longer needs calls to
 *    `$apply()`.
 *
 * ### Example
 *
 * ```
 * const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module), myCompilerOptions);
 * const module = angular.module('myExample', []);
 * module.directive('ng2Comp', adapter.downgradeNg2Component(Ng2Component));
 *
 * module.directive('ng1Hello', function() {
 *   return {
 *      scope: { title: '=' },
 *      template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)'
 *   };
 * });
 *
 *
 * @Component({
 *   selector: 'ng2-comp',
 *   inputs: ['name'],
 *   template: 'ng2[<ng1-hello [title]="name">transclude</ng1-hello>](<ng-content></ng-content>)',
 *   directives:
 * })
 * class Ng2Component {
 * }
 *
 * @NgModule({
 *   declarations: [Ng2Component, adapter.upgradeNg1Component('ng1Hello')],
 *   imports: [BrowserModule]
 * })
 * class MyNg2Module {}
 *
 *
 * document.body.innerHTML = '<ng2-comp name="World">project</ng2-comp>';
 *
 * adapter.bootstrap(document.body, ['myExample']).ready(function() {
 *   expect(document.body.textContent).toEqual(
 *       "ng2[ng1[Hello World!](transclude)](project)");
 * });
 *
 * ```
 *
 * @stable
 */
export class UpgradeAdapter {
  private idPrefix: string = `NG2_UPGRADE_${upgradeCount++}_`;
  private upgradedComponents: Type<any>[] = [];
  /**
   * An internal map of ng1 components which need to up upgraded to ng2.
   *
   * We can't upgrade until injector is instantiated and we can retrieve the component metadata.
   * For this reason we keep a list of components to upgrade until ng1 injector is bootstrapped.
   *
   * @internal
   */
  private ng1ComponentsToBeUpgraded: {[name: string]: UpgradeNg1ComponentAdapterBuilder} = {};
  private providers: Provider[] = [];
  private ngZone: NgZone;
  private ng1Module: angular.IModule;
  private moduleRef: NgModuleRef<any> = null;
  private ng2BootstrapDeferred: Deferred<angular.IInjectorService>;

  constructor(private ng2AppModule: Type<any>, private compilerOptions?: CompilerOptions) {
    if (!ng2AppModule) {
      throw new Error(
          'UpgradeAdapter cannot be instantiated without an NgModule of the Angular 2 app.');
    }
  }

  /**
   * Allows Angular 2+ Component to be used from Angular 1.
   *
   * Use `downgradeNg2Component` to create an Angular 1 Directive Definition Factory from
   * Angular 2+ Component. The adapter will bootstrap Angular 2+ component from within the
   * Angular 1 template.
   *
   * ## Mental Model
   *
   * 1. The component is instantiated by being listed in Angular 1 template. This means that the
   *    host element is controlled by Angular 1, but the component's view will be controlled by
   *    Angular 2+.
   * 2. Even thought the component is instantiated in Angular 1, it will be using Angular 2+
   *    syntax. This has to be done, this way because we must follow Angular 2+ components do not
   *    declare how the attributes should be interpreted.
   *
   * ## Supported Features
   *
   * - Bindings:
   *   - Attribute: `<comp name="World">`
   *   - Interpolation:  `<comp greeting="Hello {{name}}!">`
   *   - Expression:  `<comp [name]="username">`
   *   - Event:  `<comp (close)="doSomething()">`
   * - Content projection: yes
   *
   * ### Example
   *
   * ```
   * const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module));
   * const module = angular.module('myExample', []);
   * module.directive('greet', adapter.downgradeNg2Component(Greeter));
   *
   * @Component({
   *   selector: 'greet',
   *   template: '{{salutation}} {{name}}! - <ng-content></ng-content>'
   * })
   * class Greeter {
   *   @Input() salutation: string;
   *   @Input() name: string;
   * }
   *
   * @NgModule({
   *   declarations: [Greeter],
   *   imports: [BrowserModule]
   * })
   * class MyNg2Module {}
   *
   * document.body.innerHTML =
   *   'ng1 template: <greet salutation="Hello" [name]="world">text</greet>';
   *
   * adapter.bootstrap(document.body, ['myExample']).ready(function() {
   *   expect(document.body.textContent).toEqual("ng1 template: Hello world! - text");
   * });
   * ```
   */
  downgradeNg2Component(type: Type<any>): Function {
    this.upgradedComponents.push(type);
    const info: ComponentInfo = getComponentInfo(type);
    return ng1ComponentDirective(info, `${this.idPrefix}${info.selector}_c`);
  }

  /**
   * Allows Angular 1 Component to be used from Angular 2+.
   *
   * Use `upgradeNg1Component` to create an Angular 2+ component from Angular 1 Component
   * directive. The adapter will bootstrap Angular 1 component from within the Angular 2+
   * template.
   *
   * ## Mental Model
   *
   * 1. The component is instantiated by being listed in Angular 2+ template. This means that the
   *    host element is controlled by Angular 2+, but the component's view will be controlled by
   *    Angular 1.
   *
   * ## Supported Features
   *
   * - Bindings:
   *   - Attribute: `<comp name="World">`
   *   - Interpolation:  `<comp greeting="Hello {{name}}!">`
   *   - Expression:  `<comp [name]="username">`
   *   - Event:  `<comp (close)="doSomething()">`
   * - Transclusion: yes
   * - Only some of the features of
   *   [Directive Definition Object](https://docs.angularjs.org/api/ng/service/$compile) are
   *   supported:
   *   - `compile`: not supported because the host element is owned by Angular 2+, which does
   *     not allow modifying DOM structure during compilation.
   *   - `controller`: supported. (NOTE: injection of `$attrs` and `$transclude` is not supported.)
   *   - `controllerAs`: supported.
   *   - `bindToController`: supported.
   *   - `link`: supported. (NOTE: only pre-link function is supported.)
   *   - `name`: supported.
   *   - `priority`: ignored.
   *   - `replace`: not supported.
   *   - `require`: supported.
   *   - `restrict`: must be set to 'E'.
   *   - `scope`: supported.
   *   - `template`: supported.
   *   - `templateUrl`: supported.
   *   - `terminal`: ignored.
   *   - `transclude`: supported.
   *
   *
   * ### Example
   *
   * ```
   * const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module));
   * const module = angular.module('myExample', []);
   *
   * module.directive('greet', function() {
   *   return {
   *     scope: {salutation: '=', name: '=' },
   *     template: '{{salutation}} {{name}}! - <span ng-transclude></span>'
   *   };
   * });
   *
   * module.directive('ng2', adapter.downgradeNg2Component(Ng2Component));
   *
   * @Component({
   *   selector: 'ng2',
   *   template: 'ng2 template: <greet salutation="Hello" [name]="world">text</greet>'
   * })
   * class Ng2Component {
   * }
   *
   * @NgModule({
   *   declarations: [Ng2Component, adapter.upgradeNg1Component('greet')],
   *   imports: [BrowserModule]
   * })
   * class MyNg2Module {}
   *
   * document.body.innerHTML = '<ng2></ng2>';
   *
   * adapter.bootstrap(document.body, ['myExample']).ready(function() {
   *   expect(document.body.textContent).toEqual("ng2 template: Hello world! - text");
   * });
   * ```
   */
  upgradeNg1Component(name: string): Type<any> {
    if ((<any>this.ng1ComponentsToBeUpgraded).hasOwnProperty(name)) {
      return this.ng1ComponentsToBeUpgraded[name].type;
    } else {
      return (this.ng1ComponentsToBeUpgraded[name] = new UpgradeNg1ComponentAdapterBuilder(name))
          .type;
    }
  }

  /**
   * Registers the adapter's Angular 1 upgrade module for unit testing in Angular 1.
   * Use this instead of `angular.mock.module()` to load the upgrade module into
   * the Angular 1 testing injector.
   *
   * ### Example
   *
   * ```
   * const upgradeAdapter = new UpgradeAdapter(MyNg2Module);
   *
   * // configure the adapter with upgrade/downgrade components and services
   * upgradeAdapter.downgradeNg2Component(MyComponent);
   *
   * let upgradeAdapterRef: UpgradeAdapterRef;
   * let $compile, $rootScope;
   *
   * // We must register the adapter before any calls to `inject()`
   * beforeEach(() => {
   *   upgradeAdapterRef = upgradeAdapter.registerForNg1Tests(['heroApp']);
   * });
   *
   * beforeEach(inject((_$compile_, _$rootScope_) => {
   *   $compile = _$compile_;
   *   $rootScope = _$rootScope_;
   * }));
   *
   * it("says hello", (done) => {
   *   upgradeAdapterRef.ready(() => {
   *     const element = $compile("<my-component></my-component>")($rootScope);
   *     $rootScope.$apply();
   *     expect(element.html()).toContain("Hello World");
   *     done();
   *   })
   * });
   *
   * ```
   *
   * @param modules any Angular 1 modules that the upgrade module should depend upon
   * @returns an {@link UpgradeAdapterRef}, which lets you register a `ready()` callback to
   * run assertions once the Angular 2+ components are ready to test through Angular 1.
   */
  registerForNg1Tests(modules?: string[]): UpgradeAdapterRef {
    const windowNgMock = (window as any)['angular'].mock;
    if (!windowNgMock || !windowNgMock.module) {
      throw new Error('Failed to find \'angular.mock.module\'.');
    }
    this.declareNg1Module(modules);
    windowNgMock.module(this.ng1Module.name);
    const upgrade = new UpgradeAdapterRef();
    this.ng2BootstrapDeferred.promise.then(
        (ng1Injector) => { (<any>upgrade)._bootstrapDone(this.moduleRef, ng1Injector); }, onError);
    return upgrade;
  }

  /**
   * Bootstrap a hybrid Angular 1 / Angular 2+ application.
   *
   * This `bootstrap` method is a direct replacement (takes same arguments) for Angular 1
   * [`bootstrap`](https://docs.angularjs.org/api/ng/function/angular.bootstrap) method. Unlike
   * Angular 1, this bootstrap is asynchronous.
   *
   * ### Example
   *
   * ```
   * const adapter = new UpgradeAdapter(MyNg2Module);
   * const module = angular.module('myExample', []);
   * module.directive('ng2', adapter.downgradeNg2Component(Ng2));
   *
   * module.directive('ng1', function() {
   *   return {
   *      scope: { title: '=' },
   *      template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)'
   *   };
   * });
   *
   *
   * @Component({
   *   selector: 'ng2',
   *   inputs: ['name'],
   *   template: 'ng2[<ng1 [title]="name">transclude</ng1>](<ng-content></ng-content>)'
   * })
   * class Ng2 {
   * }
   *
   * @NgModule({
   *   declarations: [Ng2, adapter.upgradeNg1Component('ng1')],
   *   imports: [BrowserModule]
   * })
   * class MyNg2Module {}
   *
   * document.body.innerHTML = '<ng2 name="World">project</ng2>';
   *
   * adapter.bootstrap(document.body, ['myExample']).ready(function() {
   *   expect(document.body.textContent).toEqual(
   *       "ng2[ng1[Hello World!](transclude)](project)");
   * });
   * ```
   */
  bootstrap(element: Element, modules?: any[], config?: angular.IAngularBootstrapConfig):
      UpgradeAdapterRef {
    this.declareNg1Module(modules);

    const upgrade = new UpgradeAdapterRef();

    // Make sure resumeBootstrap() only exists if the current bootstrap is deferred
    const windowAngular = (window as any /** TODO #???? */)['angular'];
    windowAngular.resumeBootstrap = undefined;

    this.ngZone.run(() => { angular.bootstrap(element, [this.ng1Module.name], config); });
    const ng1BootstrapPromise = new Promise((resolve) => {
      if (windowAngular.resumeBootstrap) {
        const originalResumeBootstrap: () => void = windowAngular.resumeBootstrap;
        windowAngular.resumeBootstrap = function() {
          windowAngular.resumeBootstrap = originalResumeBootstrap;
          windowAngular.resumeBootstrap.apply(this, arguments);
          resolve();
        };
      } else {
        resolve();
      }
    });

    Promise.all([this.ng2BootstrapDeferred.promise, ng1BootstrapPromise]).then(([ng1Injector]) => {
      angular.element(element).data(controllerKey(NG2_INJECTOR), this.moduleRef.injector);
      this.moduleRef.injector.get(NgZone).run(
          () => { (<any>upgrade)._bootstrapDone(this.moduleRef, ng1Injector); });
    }, onError);
    return upgrade;
  }

  /**
   * Allows Angular 1 service to be accessible from Angular 2+.
   *
   *
   * ### Example
   *
   * ```
   * class Login { ... }
   * class Server { ... }
   *
   * @Injectable()
   * class Example {
   *   constructor(@Inject('server') server, login: Login) {
   *     ...
   *   }
   * }
   *
   * const module = angular.module('myExample', []);
   * module.service('server', Server);
   * module.service('login', Login);
   *
   * const adapter = new UpgradeAdapter(MyNg2Module);
   * adapter.upgradeNg1Provider('server');
   * adapter.upgradeNg1Provider('login', {asToken: Login});
   *
   * adapter.bootstrap(document.body, ['myExample']).ready((ref) => {
   *   const example: Example = ref.ng2Injector.get(Example);
   * });
   *
   * ```
   */
  public upgradeNg1Provider(name: string, options?: {asToken: any}) {
    const token = options && options.asToken || name;
    this.providers.push({
      provide: token,
      useFactory: (ng1Injector: angular.IInjectorService) => ng1Injector.get(name),
      deps: [NG1_INJECTOR]
    });
  }

  /**
   * Allows Angular 2+ service to be accessible from Angular 1.
   *
   *
   * ### Example
   *
   * ```
   * class Example {
   * }
   *
   * const adapter = new UpgradeAdapter(MyNg2Module);
   *
   * const module = angular.module('myExample', []);
   * module.factory('example', adapter.downgradeNg2Provider(Example));
   *
   * adapter.bootstrap(document.body, ['myExample']).ready((ref) => {
   *   const example: Example = ref.ng1Injector.get('example');
   * });
   *
   * ```
   */
  public downgradeNg2Provider(token: any): Function {
    const factory = function(injector: Injector) { return injector.get(token); };
    (<any>factory).$inject = [NG2_INJECTOR];
    return factory;
  }

  /**
   * Declare the Angular 1 upgrade module for this adapter without bootstrapping the whole
   * hybrid application.
   *
   * This method is automatically called by `bootstrap()` and `registerForNg1Tests()`.
   *
   * @param modules The Angular 1 modules that this upgrade module should depend upon.
   * @returns The Angular 1 upgrade module that is declared by this method
   *
   * ### Example
   *
   * ```
   * const upgradeAdapter = new UpgradeAdapter(MyNg2Module);
   * upgradeAdapter.declareNg1Module(['heroApp']);
   * ```
   */
  private declareNg1Module(modules: string[] = []): angular.IModule {
    const delayApplyExps: Function[] = [];
    let original$applyFn: Function;
    let rootScopePrototype: any;
    let rootScope: angular.IRootScopeService;
    const componentFactoryRefMap: ComponentFactoryRefMap = {};
    const upgradeAdapter = this;
    const ng1Module = this.ng1Module = angular.module(this.idPrefix, modules);
    const platformRef = platformBrowserDynamic();

    this.ngZone = new NgZone({enableLongStackTrace: Zone.hasOwnProperty('longStackTraceZoneSpec')});
    this.ng2BootstrapDeferred = new Deferred();
    ng1Module.factory(NG2_INJECTOR, () => this.moduleRef.injector.get(Injector))
        .constant(NG2_ZONE, this.ngZone)
        .constant(NG2_COMPONENT_FACTORY_REF_MAP, componentFactoryRefMap)
        .factory(NG2_COMPILER, () => this.moduleRef.injector.get(Compiler))
        .config([
          '$provide', '$injector',
          (provide: angular.IProvideService, ng1Injector: angular.IInjectorService) => {
            provide.decorator(NG1_ROOT_SCOPE, [
              '$delegate',
              function(rootScopeDelegate: angular.IRootScopeService) {
                // Capture the root apply so that we can delay first call to $apply until we
                // bootstrap Angular 2 and then we replay and restore the $apply.
                rootScopePrototype = rootScopeDelegate.constructor.prototype;
                if (rootScopePrototype.hasOwnProperty('$apply')) {
                  original$applyFn = rootScopePrototype.$apply;
                  rootScopePrototype.$apply = (exp: any) => delayApplyExps.push(exp);
                } else {
                  throw new Error('Failed to find \'$apply\' on \'$rootScope\'!');
                }
                return rootScope = rootScopeDelegate;
              }
            ]);
            if (ng1Injector.has(NG1_TESTABILITY)) {
              provide.decorator(NG1_TESTABILITY, [
                '$delegate',
                function(testabilityDelegate: angular.ITestabilityService) {
                  const originalWhenStable: Function = testabilityDelegate.whenStable;
                  // Cannot use arrow function below because we need the context
                  const newWhenStable = function(callback: Function) {
                    originalWhenStable.call(this, function() {
                      const ng2Testability: Testability =
                          upgradeAdapter.moduleRef.injector.get(Testability);
                      if (ng2Testability.isStable()) {
                        callback.apply(this, arguments);
                      } else {
                        ng2Testability.whenStable(newWhenStable.bind(this, callback));
                      }
                    });
                  };

                  testabilityDelegate.whenStable = newWhenStable;
                  return testabilityDelegate;
                }
              ]);
            }
          }
        ]);

    ng1Module.run([
      '$injector', '$rootScope',
      (ng1Injector: angular.IInjectorService, rootScope: angular.IRootScopeService) => {
        UpgradeNg1ComponentAdapterBuilder.resolve(this.ng1ComponentsToBeUpgraded, ng1Injector)
            .then(() => {
              // At this point we have ng1 injector and we have lifted ng1 components into ng2, we
              // now can bootstrap ng2.
              const DynamicNgUpgradeModule =
                  NgModule({
                    providers: [
                      {provide: NG1_INJECTOR, useFactory: () => ng1Injector},
                      {provide: NG1_COMPILE, useFactory: () => ng1Injector.get(NG1_COMPILE)},
                      this.providers
                    ],
                    imports: [this.ng2AppModule]
                  }).Class({
                    constructor: function DynamicNgUpgradeModule() {},
                    ngDoBootstrap: function() {}
                  });
              (platformRef as any)
                  ._bootstrapModuleWithZone(
                      DynamicNgUpgradeModule, this.compilerOptions, this.ngZone,
                      (componentFactories: ComponentFactory<any>[]) => {
                        componentFactories.forEach((componentFactory) => {
                          const type: Type<any> = componentFactory.componentType;
                          if (this.upgradedComponents.indexOf(type) !== -1) {
                            componentFactoryRefMap[getComponentInfo(type).selector] =
                                componentFactory;
                          }
                        });
                      })
                  .then((ref: NgModuleRef<any>) => {
                    this.moduleRef = ref;
                    let subscription = this.ngZone.onMicrotaskEmpty.subscribe({
                      next: (_: any) => this.ngZone.runOutsideAngular(() => rootScope.$evalAsync())
                    });
                    rootScope.$on('$destroy', () => { subscription.unsubscribe(); });
                    this.ngZone.run(() => {
                      if (rootScopePrototype) {
                        rootScopePrototype.$apply = original$applyFn;  // restore original $apply
                        while (delayApplyExps.length) {
                          rootScope.$apply(delayApplyExps.shift());
                        }
                        rootScopePrototype = null;
                      }
                    });
                  })
                  .then(() => this.ng2BootstrapDeferred.resolve(ng1Injector), onError);
            })
            .catch((e) => this.ng2BootstrapDeferred.reject(e));
      }
    ]);

    return ng1Module;
  }
}

interface ComponentFactoryRefMap {
  [selector: string]: ComponentFactory<any>;
}

/**
 * Synchronous promise-like object to wrap parent injectors,
 * to preserve the synchronous nature of Angular 1's $compile.
 */
class ParentInjectorPromise {
  private injector: Injector;
  private callbacks: ((injector: Injector) => any)[] = [];

  constructor(private element: angular.IAugmentedJQuery) {
    // store the promise on the element
    element.data(controllerKey(NG2_INJECTOR), this);
  }

  then(callback: (injector: Injector) => any) {
    if (this.injector) {
      callback(this.injector);
    } else {
      this.callbacks.push(callback);
    }
  }

  resolve(injector: Injector) {
    this.injector = injector;

    // reset the element data to point to the real injector
    this.element.data(controllerKey(NG2_INJECTOR), injector);

    // clean out the element to prevent memory leaks
    this.element = null;

    // run all the queued callbacks
    this.callbacks.forEach((callback) => callback(injector));
    this.callbacks.length = 0;
  }
}

function ng1ComponentDirective(info: ComponentInfo, idPrefix: string): Function {
  (<any>directiveFactory).$inject =
      [NG1_INJECTOR, NG1_COMPILE, NG2_COMPONENT_FACTORY_REF_MAP, NG1_PARSE];
  function directiveFactory(
      ng1Injector: angular.IInjectorService, ng1Compile: angular.ICompileService,
      componentFactoryRefMap: ComponentFactoryRefMap,
      parse: angular.IParseService): angular.IDirective {
    let idCount = 0;
    let dashSelector = info.selector.replace(/[A-Z]/g, char => '-' + char.toLowerCase());
    return {
      restrict: 'E',
      terminal: true,
      require: REQUIRE_INJECTOR,
      compile: (templateElement: angular.IAugmentedJQuery, templateAttributes: angular.IAttributes,
                transclude: angular.ITranscludeFunction) => {
        // We might have compile the contents lazily, because this might have been triggered by the
        // UpgradeNg1ComponentAdapterBuilder, when the ng2 templates have not been compiled yet
        return {
          post: (scope: angular.IScope, element: angular.IAugmentedJQuery,
                 attrs: angular.IAttributes, parentInjector: Injector | ParentInjectorPromise,
                 transclude: angular.ITranscludeFunction): void => {
            let id = idPrefix + (idCount++);
            (<any>element[0]).id = id;

            let injectorPromise = new ParentInjectorPromise(element);

            const ng2Compiler = ng1Injector.get(NG2_COMPILER) as Compiler;
            const ngContentSelectors = ng2Compiler.getNgContentSelectors(info.type);
            const linkFns = compileProjectedNodes(templateElement, ngContentSelectors);

            const componentFactory: ComponentFactory<any> = componentFactoryRefMap[info.selector];
            if (!componentFactory)
              throw new Error('Expecting ComponentFactory for: ' + info.selector);

            element.empty();
            let projectableNodes = linkFns.map(link => {
              let projectedClone: Node[];
              link(scope, (clone: Node[]) => {
                projectedClone = clone;
                element.append(clone);
              });
              return projectedClone;
            });

            parentInjector = parentInjector || ng1Injector.get(NG2_INJECTOR);

            if (parentInjector instanceof ParentInjectorPromise) {
              parentInjector.then((resolvedInjector: Injector) => downgrade(resolvedInjector));
            } else {
              downgrade(parentInjector);
            }

            function downgrade(injector: Injector) {
              const facade = new DowngradeNg2ComponentAdapter(
                  info, element, attrs, scope, injector, parse, componentFactory);
              facade.setupInputs();
              facade.bootstrapNg2(projectableNodes);
              facade.setupOutputs();
              facade.registerCleanup();
              injectorPromise.resolve(facade.componentRef.injector);
            }
          }
        };
      }
    };

    function compileProjectedNodes(
        templateElement: angular.IAugmentedJQuery,
        ngContentSelectors: string[]): angular.ILinkFn[] {
      if (!ngContentSelectors)
        throw new Error('Expecting ngContentSelectors for: ' + info.selector);
      // We have to sort the projected content before we compile it, hence the terminal: true
      let projectableTemplateNodes =
          sortProjectableNodes(ngContentSelectors, templateElement.contents());
      return projectableTemplateNodes.map(nodes => ng1Compile(nodes));
    }
  }
  return directiveFactory;
}

/**
 * Use `UpgradeAdapterRef` to control a hybrid Angular 1 / Angular 2+ application.
 *
 * @stable
 */
export class UpgradeAdapterRef {
  /* @internal */
  private _readyFn: (upgradeAdapterRef?: UpgradeAdapterRef) => void = null;

  public ng1RootScope: angular.IRootScopeService = null;
  public ng1Injector: angular.IInjectorService = null;
  public ng2ModuleRef: NgModuleRef<any> = null;
  public ng2Injector: Injector = null;

  /* @internal */
  private _bootstrapDone(ngModuleRef: NgModuleRef<any>, ng1Injector: angular.IInjectorService) {
    this.ng2ModuleRef = ngModuleRef;
    this.ng2Injector = ngModuleRef.injector;
    this.ng1Injector = ng1Injector;
    this.ng1RootScope = ng1Injector.get(NG1_ROOT_SCOPE);
    this._readyFn && this._readyFn(this);
  }

  /**
   * Register a callback function which is notified upon successful hybrid Angular 1 / Angular 2+
   * application has been bootstrapped.
   *
   * The `ready` callback function is invoked inside the Angular 2+ zone, therefore it does not
   * require a call to `$apply()`.
   */
  public ready(fn: (upgradeAdapterRef?: UpgradeAdapterRef) => void) { this._readyFn = fn; }

  /**
   * Dispose of running hybrid Angular 1 / Angular 2+ application.
   */
  public dispose() {
    this.ng1Injector.get(NG1_ROOT_SCOPE).$destroy();
    this.ng2ModuleRef.destroy();
  }
}

/**
 * Sort a set of DOM nodes that into groups based on the given content selectors
 */
export function sortProjectableNodes(ngContentSelectors: string[], childNodes: Node[]): Node[][] {
  let projectableNodes: Node[][] = [];
  let matcher = new SelectorMatcher();
  let wildcardNgContentIndex: number;
  for (let i = 0, ii = ngContentSelectors.length; i < ii; i++) {
    projectableNodes[i] = [];
    if (ngContentSelectors[i] === '*') {
      wildcardNgContentIndex = i;
    } else {
      matcher.addSelectables(CssSelector.parse(ngContentSelectors[i]), i);
    }
  }
  for (let node of childNodes) {
    let ngContentIndices: number[] = [];
    let selector =
        createElementCssSelector(node.nodeName.toLowerCase(), getAttributesAsArray(node));
    matcher.match(
        selector, (selector, ngContentIndex) => { ngContentIndices.push(ngContentIndex); });
    ngContentIndices.sort();
    if (wildcardNgContentIndex !== undefined) {
      ngContentIndices.push(wildcardNgContentIndex);
    }
    if (ngContentIndices.length > 0) {
      projectableNodes[ngContentIndices[0]].push(node);
    }
  }
  return projectableNodes;
}


text:
var button, field, ios, nav, statusBar;

ios = require("ios-kit");

statusBar = new ios.StatusBar({
  carrier: "Verizon",
  network: "3G",
  signal: 3,
  battery: 70,
  style: "dark"
});

nav = new ios.NavBar({
  right: "Next",
  left: "< Back",
  title: "Document",
  blur: true
});

nav.right.onClick(function() {
  return print(ios.utils.getTime());
});

button = new ios.Button({
  text: "Alert me",
  type: "big",
  style: "light",
  backgroundColor: "white",
  constraints: {
    top: 300
  }
});

button.onClick(function() {
  var alert;
  return alert = new ios.Alert({
    title: "Warning!",
    message: "This is awesome",
    actions: ["OK", "Cancel"]
  });
});

field = new ios.Field({
  placeholder: "Write here",
  constraints: {
    top: 200
  },
  width: 300
});

field.x = Align.center;


text:
class CreateSellers < ActiveRecord::Migration
  def change
    create_table :sellers do |t|
      t.string :name
      t.string :description
      t.string :email
      t.integer :user_id

      t.timestamps null: false
    end
  end
end


text:
from lib.util import Util

class NaiveG:
    def __init__(self, users, graph):
        self.users = users
        self.graph = graph

    def infer_one(self, user_id):
        points = []
        for fid in self.graph.get_followers(user_id):
            user = self.users.get(fid)
            if user != None:
                if user['location_point'] != None:
                    points.append(user['location_point'])
        if len(points) > 0:
            #centroid = Util.calc_centroid(points)
            centroid = Util.calc_medoid(points)
            return centroid
        else:
            return None

    def infer(self, params):
        for user in self.users.iter():
            if user['location_point'] == None:
                user['location_point'] = self.infer_one(user['id'])

    def get_users(self):
        return self.users

if __name__ == '__main__':
    import sys
    from lib.users import Users
    from lib.graph import Graph

    if len(sys.argv) < 3:
        print '[usage]: python %s [users file path] [graph file path]' % sys.argv[0]
        exit()

    users = Users()
    users.load_file(sys.argv[1])
    graph = Graph()
    graph.load_file(sys.argv[2])

    ng = NaiveG(users, graph)
    ng.infer()
    print ng.get_users()


text:
@interface YBZYHomeMinorActivityViewCell : UICollectionViewCell

@property (nonatomic, strong) YBZYHomeCategoryActivityModel *activityModel;

@end


text:
package com.intellij.build.events;

import org.jetbrains.annotations.ApiStatus;

/**
 * @author Vladislav.Soroka
 */
@ApiStatus.Experimental
public interface StartEvent extends BuildEvent {
}


text:
.ripple {
  position: relative;
  overflow: hidden;
  transform: translate3d(0, 0, 0);
}

.ripple::after {
  content: "";
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  pointer-events: none;
  background-image: radial-gradient(circle, #000 10%, transparent 10.01%);
  background-repeat: no-repeat;
  background-position: 50%;
  transform: scale(10, 10);
  opacity: 0;
  transition: transform 0.2s, opacity 1s;
}

.ripple:active::after {
  transform: scale(0, 0);
  opacity: 0.2;
  transition: 0s;
}


text:
import { app, BrowserWindow } from 'electron'

let mainWindow

const createWindow = () => {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    frame: false
  })

  mainWindow.loadURL(`file://${__dirname}/www/tmpl/index.jade`)

  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})