text:
using FlightNode.Common.Utility;
using FlightNode.Identity.Domain.Entities;
using Microsoft.AspNet.Identity;
using Moq;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;

namespace FlightNode.Identity.UnitTests.Domain.Managers.UserDomainManagerTests
{

    public class Approve : Fixture
    {
        [Fact]
        public void NullObjectNotAllowed()
        {
            Assert.ThrowsAsync<ArgumentNullException>(() => BuildSystem().Approve(null));
        }

        private Task RunTest(List<int> ids)
        {
            return BuildSystem().Approve(ids);
        }

        [Fact]
        public void SendEmailUsingRegisteredAddressAndName()
        {
            // Arrange
            var ids = new List<int>() { UserId };
            var expected = GivenName + " " + FamilyName + " <" + Email + ">";

            ExpectToLookupUser(UserId);
            ExpectSuccessfulUserUpdate();
            var notifierMock = ExpectToSendEmail();

            // Act
            RunTest(ids);

            // Assert
            notifierMock.Verify(x => x.SendAsync(It.Is<NotificationModel>(y => y.To == expected)));
        }

        [Fact]
        public void SendEmailUsingCustomizedMessage()
        {
            // Arrange
            var ids = new List<int>() { UserId };
            const string expected = @"Your account registration at FlightNode has been approved, and you can now start entering data.

Username: " + UserName + @"
";

            ExpectToLookupUser(UserId);
            ExpectSuccessfulUserUpdate();
            var notifierMock = ExpectToSendEmail();

            // Act
            RunTest(ids);

            // Assert
            notifierMock.Verify(x => x.SendAsync(It.Is<NotificationModel>(y => y.Body == expected)));
        }

        //" user registration has been approved";

        [Fact]
        public void SendEmailUsingCorrectSubject()
        {
            // Arrange
            var ids = new List<int>() { UserId };
            const string expected = "FlightNode user registration has been approved";

            ExpectToLookupUser(UserId);
            ExpectSuccessfulUserUpdate();
            var notifierMock = ExpectToSendEmail();

            // Act
            RunTest(ids);

            // Assert
            notifierMock.Verify(x => x.SendAsync(It.Is<NotificationModel>(y => y.Subject == expected)));
        }

        private void ExpectSuccessfulUserUpdate()
        {
            MockUserManager.Setup(x => x.UpdateAsync(It.IsAny<User>()))
                .Returns(Task.Run(() => SuccessResult.Create()));
        }

        private void ExpectToLookupUser(int id)
        {
            MockUserManager.Setup(x => x.FindByIdAsync(id))
               .Returns(Task.Run(() => new User
               {
                   Id = id,
                   Active = "pending",
                   Email = Email,
                   GivenName = GivenName,
                   FamilyName = FamilyName,
                   UserName = UserName
               }));
        }

        [Fact]
        public void ApproveTwoPeopleWhenBothExistSetsFirstStatusToActive()
        {
            //
            // Arrange
            var ids = new List<int>() { 14, 43 };

            ids.ForEach(x => ExpectToLookupUser(x));
            ExpectSuccessfulUserUpdate();
            ExpectToSendEmail();

            //
            // Act
            RunTest(ids);

            // Assert
            MockUserManager.Verify(x => x.UpdateAsync(It.Is<User>(y => y.Id == ids[0] && y.Active == "active")));
        }

        [Fact]
        public void ApproveTwoPeopleWhenBothExistSetsSecondStatusToActive()
        {
            //
            // Arrange
            var ids = new List<int>() { 14, 43 };

            ids.ForEach(x => ExpectToLookupUser(x));
            ExpectSuccessfulUserUpdate();

            ExpectToSendEmail();

            //
            // Act
            RunTest(ids);

            //
            // Assert
            MockUserManager.Verify(x => x.UpdateAsync(It.Is<User>(y => y.Id == ids[1] && y.Active == "active")));
        }

        [Fact]
        public void UnlocksAccount()
        {
            //
            // Arrange
            var ids = new List<int>() { UserId };

            ExpectToLookupUser(UserId);
            ExpectSuccessfulUserUpdate();

            ExpectToSendEmail();

            //
            // Act
            RunTest(ids);

            //
            // Assert
            MockUserManager.Verify(x => x.UpdateAsync(It.Is<User>(y => y.Id == UserId && !y.LockoutEnabled)));
        }

        [Fact]
        public void ConfirmSavesSecondRecordEvenWhenFirstRecordDoesNotExist()
        {

            var ids = new List<int>() { 14, 43 };

            MockUserManager.Setup(x => x.FindByIdAsync(ids[0]))
                .Returns(Task.Run(() => null as User));

            ExpectToLookupUser(ids[1]);
            ExpectSuccessfulUserUpdate();

            ExpectToSendEmail();

            //
            // Act
            RunTest(ids);

            //
            // Assert
            MockUserManager.Verify(x => x.UpdateAsync(It.Is<User>(y => y.Id == ids[1])));
        }

        [Fact]
        public void ConfirmSavesFirstRecordEvenWhenSecondRecordDoesNotExist()
        {

            var ids = new List<int>() { 14, 43 };

            MockUserManager.Setup(x => x.FindByIdAsync(ids[1]))
                .Returns(Task.Run(() => null as User));

            ExpectToLookupUser(ids[0]);
            ExpectSuccessfulUserUpdate();

            ExpectToSendEmail();

            //
            // Act
            RunTest(ids);

            //
            // Assert
            MockUserManager.Verify(x => x.UpdateAsync(It.Is<User>(y => y.Id == ids[0])));
        }

        [Fact]
        public void ConfirmSavesSecondRecordEvenWhenFirstRecordFailsToUpdate()
        {

            var ids = new List<int>() { 14, 43 };

            ids.ForEach(x => ExpectToLookupUser(x));

            ExpectSuccessfulUserUpdate();
            MockUserManager.Setup(x => x.UpdateAsync(It.Is<User>(y => y.Id == ids[0])))
                .Returns(Task.Run(() => new IdentityResult("errorrrrrrr")));

            ExpectToSendEmail();

            //
            // Act
            RunTest(ids);

            //
            // Assert
            MockUserManager.Verify(x => x.UpdateAsync(It.Is<User>(y => y.Id == ids[1])));
        }

        [Fact]
        public void ConfirmSavesFirstRecordEvenWhenSecondRecordFailsToUpdate()
        {

            var ids = new List<int>() { 14, 43 };
            ids.ForEach(x => ExpectToLookupUser(x));

            ExpectSuccessfulUserUpdate();
            MockUserManager.Setup(x => x.UpdateAsync(It.Is<User>(y => y.Id == ids[1])))
                .Returns(Task.Run(() => new IdentityResult("errorrrrrrr")));

            ExpectToSendEmail();

            //
            // Act
            RunTest(ids);

            //
            // Assert
            MockUserManager.Verify(x => x.UpdateAsync(It.Is<User>(y => y.Id == ids[0])));
        }

        // More detailed exception handling occurs in the controller class. In this case,
        // if one record succeeds and a subsequent record (from array of multiple id values)
        // fails, then it is acceptable that the first (or more) succeeded. That one+ will
        // be removed from the pending list as desired.

        [Fact]
        public void ConfirmDoesNotCatchExceptionOnFind()
        {
            var ids = new List<int>() { 14, 43 };

            MockUserManager.Setup(x => x.FindByIdAsync(It.Is<int>(y => y == ids[0])))
                .Throws<InvalidOperationException>();

            //
            // Act & Assert
            Assert.ThrowsAsync<InvalidOperationException>(() => RunTest(ids));
        }

        [Fact]
        public void ConfirmDoesNotCatchExceptionOnUpdate()
        {
            var ids = new List<int>() { 14, 43 };

            MockUserManager.Setup(x => x.FindByIdAsync(ids[0]))
                .ReturnsAsync(new User { Id = ids[0], Active = "pending" });

            //mockUserManager.Setup(x => x.FindByIdAsync(ids[1]))
            //    .ReturnsAsync(new User { Id = ids[1], Active = "pending" });

            MockUserManager.Setup(x => x.UpdateAsync(It.Is<User>(y => y.Id == ids[0])))
                .ThrowsAsync(new InvalidOperationException());

            //
            // Act & Assert
            Assert.ThrowsAsync<AggregateException>(() => RunTest(ids));
        }
    }
}


text:
bool isAbbr ( int64_t wid , bool *hasWordAfter = NULL ) ;

// to free the table's memory, Process::reset() will call this
void resetAbbrTable ( ) ;

#endif

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

<meta charset=utf-8>
<title>76 nips-2005-From Batch to Transductive Online Learning</title>

nips nips2005 nips2005-76 nips2005-76-reference knowledge-graph by maker-knowledge-mining

76 nips-2005-From Batch to Transductive Online Learning

Source: pdf

Author: Sham Kakade, Adam Tauman Kalai

Abstract: It is well-known that everything that is learnable in the difficult online setting, where an arbitrary sequences of examples must be labeled one at a time, is also learnable in the batch setting, where examples are drawn independently from a distribution. We show a result in the opposite direction. We give an efficient conversion algorithm from batch to online that is transductive: it uses future unlabeled data. This demonstrates the equivalence between what is properly and efficiently learnable in a batch model and a transductive online model.

reference text

[1] B. Awerbuch and R. Kleinberg. Adaptive routing with end-to-end feedback: Distributed learning and geometric approaches. In Proc. of the 36th ACM Symposium on Theory of Computing, 2004.

[2] S. Ben-David, E. Kushilevitz, and Y. Mansour. Online learning versus offline learning. Machine Learning 29:45-63, 1997.

[3] A. Blum. Separating Distribution-Free and Mistake-Bound Learning Models over the Boolean Domain. SIAM Journal on Computing 23(5): 990-1000, 1994.

[4] A. Blum, J. Hartline. Near-Optimal Online Auctions. In Proceedings of the Proceedings of the Sixteenth Annual ACM-SIAM Symposium on Discrete Algorithms (SODA), 2005.

[5] J. Hannan. Approximation to Bayes Risk in Repeated Plays. In M. Dresher, A. Tucker, and P. Wolfe editors, Contributions to the Theory of Games, Volume 3, p. 97-139, Princeton University Press, 1957.

[6] A. Kalai and S. Vempala. Efficient algorithms for the online decision problem. In Proceedings of the 16th Conference on Computational Learning Theory, 2003.

[7] M. Kearns, R. Schapire, and L. Sellie. Toward Efficient Agnostic Learning. Machine Learning, 17(2/3):115–141, 1994.

[8] N. Littlestone. From On-Line to Batch Learning. In Proceedings of the 2nd Workshop on Computational Learning Theory, p. 269-284, 1989.

[9] N. Littlestone and M. Warmuth. The Weighted Majority Algorithm. Information and Computation, 108:212-261, 1994.

[10] H. Brendan McMahan and Avrim Blum. Online Geometric Optimization in the Bandit Setting Against an Adaptive Adversary. In Proceedings of the 17th Annual Conference on Learning Theory, COLT 2004.

[11] N. Sauer. On the Densities of Families of Sets. Journal of Combinatorial Theory, Series A, 13, p 145-147, 1972.

[12] V. N. Vapnik. Estimation of Dependencies Based on Empirical Data, New York: Springer Verlag, 1982.

[13] V. N. Vapnik. Statistical Learning Theory, New York: Wiley Interscience, 1998.


text:
Public Issues repository for the Minecraft mod Tick Dynamic.

Development Releases:
There are currently development releases of version 0.2.0 on github.
- Forge 1.8.9
- Forge 1.7.10
- KCauldron

Check the "Releases" tab on the top. I would appreciate any feedback on the dev versions, so I can make the final releases as bug-free as possible. =)

Webpage & final release downloads: http://mods.stjerncraft.com/tickdynamic


text:
import I18nProvider from './I18nProvider';
import i18nLoader from './i18nLoader';

module.exports = {
  I18nProvider,
  i18nLoader,
};


text:
package com.jmb.springfactory.model.entity;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

@Entity
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class Comment extends BaseEntity {

  @ManyToOne(fetch = FetchType.LAZY)
  private User author;

  @ManyToOne(fetch = FetchType.LAZY)
  private WorkGroup group;

  private String text;

  @Temporal(TemporalType.TIMESTAMP)
  private Date creationDate;

  @Temporal(TemporalType.TIMESTAMP)
  private Date modificationDate;

  @ManyToOne(fetch = FetchType.LAZY)
  private Task task;

}


text:
import os
import sys

import journalimport
import sectionimport
import issueimport

from django.core.management import setup_environ
from django.core.exceptions import ObjectDoesNotExist

try:
    from scielomanager import settings
except ImportError:
    BASE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
    BASE_PATH_APP = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'scielomanager'))
    from sys import path
    path.append(BASE_PATH)
    path.append(BASE_PATH_APP)

    import settings

setup_environ(settings)

from journalmanager.models import Collection

collectionname = sys.argv[1]
collectionurl = sys.argv[2]

print u'Checking if Collection %s exists at JournalManager Database' % collectionname

try:
    collection = Collection.objects.get(name=collectionname)
    collectionname = collection.name
except ObjectDoesNotExist:
    print 'Collection %s does not exists' % (collectionname)
    collection = Collection()
    collection.name = collectionname
    collection.url = collectionurl
    collection.save()
    print 'Collection %s was created' % (collectionname)
except NameError:
    print 'Collection %s does not exists' % (collectionname)
else:
    print 'Collection %s exists' % (collectionname)

print 'Importing Journals and Institutions from SciELO %s' % (collectionname)
import_journal = journalimport.JournalImport()
import_result = import_journal.run_import('journal.json', collection)
print import_journal.get_summary()

print 'Importing Sections from SciELO %s' % (collection.name)
print 'Importing sectionimportSections from SciELO %s' % (collectionname)
import_section = sectionimport.SectionImport()
import_result = import_section.run_import('section.json', collection)
print import_section.get_summary()

print 'Importing Issues from SciELO %s' % (collectionname)
import_issue = issueimport.IssueImport(collection)
import_result = import_issue.run_import('issue.json')
print import_issue.get_summary()


text:
import {createClass, PropTypes} from 'react'
import {h} from 'react-markup'
import prefixer from 'bem-prefixer'

import TableView from './table-view'
import Modal from './modal'
const bem = prefixer('ManyToOneModal')

const ManyToOneModal = createClass({

    displayName: 'ManyToOneModal',

    render() {
        const {resourceName, onCancel, onSelect, context} = this.props

        return (
            h(bem('div'),
                h(Modal,
                    h(TableView, {
                        resourceName,
                        enableRecordSelect: true,
                        onRecordSelect: onSelect,
                        context,
                    }),
                    h('button', {onClick: onCancel}, 'Cancel')
                )
            )
        )
    },
})

ManyToOneModal.propTypes = {
    context: PropTypes.object.isRequired,
    resourceName: PropTypes.string.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
}

export default ManyToOneModal


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Method. Lich. 35 (1803)

#### Original name
Lecidea parasema (Ach.) Ach.

### Remarks
null


text:
package org.createnet.raptor.sdk.api;

import org.createnet.raptor.sdk.Routes;
import org.createnet.raptor.sdk.AbstractClient;
import org.createnet.raptor.sdk.Raptor;
import org.createnet.raptor.sdk.events.callback.ActionCallback;
import org.createnet.raptor.sdk.events.callback.ActionEventCallback;
import org.createnet.raptor.models.data.ActionStatus;
import org.createnet.raptor.models.objects.Action;
import org.createnet.raptor.models.objects.Device;
import org.createnet.raptor.models.payload.ActionPayload;
import org.createnet.raptor.models.payload.DispatcherPayload;

/**
 * Represent a Device action
 *
 * @author Luca Capra <lcapra@fbk.eu>
 */
public class ActionClient extends AbstractClient {

    public ActionClient(Raptor container) {
        super(container);
    }

    /**
     * Subscribe to a data stream
     *
     * @param action
     * @param ev
     */
    protected void subscribe(Action action, ActionEventCallback ev) {
        getEmitter().subscribe(action, ev);
    }

    /**
     * Subscribe to a data stream
     *
     * @param action
     * @param ev
     */
    public void subscribe(Action action, ActionCallback ev) {
        subscribe(action, new ActionEventCallback() {
            @Override
            public void trigger(DispatcherPayload payload) {
                ActionPayload apayload = (ActionPayload) payload;
                ev.callback(action, apayload);
            }
        });
    }

    /**
     * Get the action status for an object
     *
     * @param action
     * @return return the list of available action for an object
     */
    public ActionStatus getStatus(Action action) {
        return Device.getMapper().convertValue(
                getClient().get(
                        String.format(Routes.ACTION_STATUS, action.getDevice().id(), action.name())
                ),
                ActionStatus.class
        );
    }

    /**
     * Get the action status for an object
     *
     * @param deviceId id of the object
     * @param actionId name of the action
     * @return return the list of available action for an object
     */
    public ActionStatus getStatus(String deviceId, String actionId) {
        return ActionStatus.parseJSON(getClient().get(
            String.format(Routes.ACTION_STATUS, deviceId, actionId)
        ));
    }

    /**
     * Set the action status for an object
     *
     * @param action the action to set the status
     * @param status the current status
     * @return return the list of available action for an object
     */
    public ActionStatus setStatus(Action action, ActionStatus status) {
        return ActionStatus.parseJSON(getClient().put(
                String.format(Routes.ACTION_STATUS, action.getDevice().id(), action.name()), status.status
        ));
    }

    /**
     * Remove the action status for an object
     *
     * @param action the action to set the status
     */
    public void removeStatus(Action action) {
        getClient().delete(
                String.format(Routes.ACTION_STATUS, action.getDevice().id(), action.name())
        );
    }

    /**
     * Remove the action status for an object
     *
     * @param deviceId id of the object
     * @param actionId name of the action
     */
    public void removeStatus(String deviceId, String actionId) {
        getClient().delete(
                String.format(Routes.ACTION_STATUS, deviceId, actionId)
        );
    }

    /**
     * Set the action status for an object
     *
     * @param deviceId id of the object
     * @param actionId name of the action
     * @param status the current status
     * @return return the list of available action for an object
     */
    public ActionStatus setStatus(String deviceId, String actionId, ActionStatus status) {
        return Device.getMapper().convertValue(
                getClient().post(
                        String.format(Routes.ACTION_STATUS, deviceId, actionId), status.toJsonNode()
                ),
                ActionStatus.class
        );
    }

    /**
     * Invoke an action on the object
     *
     * @param action the action reference
     * @param payload the payload to send as string
     */
    public void invoke(Action action, String payload) {
        getClient().post(
                String.format(Routes.ACTION_INVOKE, action.getDevice().id(), action.name()), payload
        );
    }

}


text:
package alicloud

import (
	"fmt"
	"strings"
	"time"

	"github.com/alibaba/terraform-provider/alicloud/connectivity"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAliyunRouteTable() *schema.Resource {
	return &schema.Resource{
		Create: resourceAliyunRouteTableCreate,
		Read:   resourceAliyunRouteTableRead,
		Update: resourceAliyunRouteTableUpdate,
		Delete: resourceAliyunRouteTableDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"description": &schema.Schema{
				Type:         schema.TypeString,
				Optional:     true,
				ValidateFunc: validateInstanceDescription,
			},
			"name": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
					value := v.(string)
					if len(value) < 2 || len(value) > 128 {
						errors = append(errors, fmt.Errorf("%s cannot be longer than 128 characters", k))
					}

					if strings.HasPrefix(value, "http://") || strings.HasPrefix(value, "https://") {
						errors = append(errors, fmt.Errorf("%s cannot starts with http:// or https://", k))
					}

					return
				},
			},

			"vpc_id": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
		},
	}
}

func resourceAliyunRouteTableCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*connectivity.AliyunClient)
	routeTableService := RouteTableService{client}

	request := vpc.CreateCreateRouteTableRequest()
	request.RegionId = client.RegionId

	request.VpcId = d.Get("vpc_id").(string)
	request.RouteTableName = d.Get("name").(string)
	request.Description = d.Get("description").(string)
	request.ClientToken = buildClientToken("TF-AllocateRouteTable")

	raw, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
		return vpcClient.CreateRouteTable(request)
	})
	if err != nil {
		return err
	}
	routeTable, _ := raw.(*vpc.CreateRouteTableResponse)
	d.SetId(routeTable.RouteTableId)

	if err := routeTableService.WaitForRouteTable(routeTable.RouteTableId, DefaultTimeout); err != nil {
		return fmt.Errorf("Wait for route table got error: %#v", err)
	}

	return resourceAliyunRouteTableRead(d, meta)
}

func resourceAliyunRouteTableRead(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*connectivity.AliyunClient)
	routeTableService := RouteTableService{client}

	resp, err := routeTableService.DescribeRouteTable(d.Id())
	if err != nil {
		if NotFoundError(err) {
			d.SetId("")
			return nil
		}
		return fmt.Errorf("Error Describe Route Table Attribute: %#v", err)
	}

	d.Set("vpc_id", resp.VpcId)
	d.Set("name", resp.RouteTableName)
	d.Set("description", resp.Description)

	return nil
}

func resourceAliyunRouteTableUpdate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*connectivity.AliyunClient)

	update := false
	request := vpc.CreateModifyRouteTableAttributesRequest()
	request.RouteTableId = d.Id()

	if d.HasChange("description") {
		request.Description = d.Get("description").(string)
		update = true
	}

	if d.HasChange("name") {
		request.RouteTableName = d.Get("name").(string)
		update = true
	}

	if update {
		_, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
			return vpcClient.ModifyRouteTableAttributes(request)
		})
		if err != nil {
			return err
		}
	}

	return resourceAliyunRouteTableRead(d, meta)
}

func resourceAliyunRouteTableDelete(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*connectivity.AliyunClient)
	routeTableService := RouteTableService{client}

	request := vpc.CreateDeleteRouteTableRequest()
	request.RouteTableId = d.Id()

	return resource.Retry(5*time.Minute, func() *resource.RetryError {
		_, err := client.WithVpcClient(func(vpcClient *vpc.Client) (interface{}, error) {
			return vpcClient.DeleteRouteTable(request)
		})
		if err != nil {
			return resource.NonRetryableError(err)
		}
		if _, err := routeTableService.DescribeRouteTable(d.Id()); err != nil {
			if NotFoundError(err) {
				return nil
			}
			return resource.RetryableError(fmt.Errorf("Error describing route table failed when deleting route table: %#v", err))
		}
		return resource.RetryableError(fmt.Errorf("Delete Route Table timeout."))
	})
}


text:
package uk.theretiredprogrammer.photogallery.dataobjects;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import org.openide.util.Lookup;
import org.openide.util.lookup.ServiceProvider;
import static uk.theretiredprogrammer.photogallery.dataobjects.Image.ImageField;
import uk.theretiredprogrammer.nbpcglibrary.api.*;
import uk.theretiredprogrammer.nbpcglibrary.common.*;
import uk.theretiredprogrammer.nbpcglibrary.data.entity.*;
import uk.theretiredprogrammer.nbpcglibrary.data.entity.EntityStateChangeEventParams.EntityState;
import static uk.theretiredprogrammer.nbpcglibrary.data.entity.EntityStateChangeEventParams.EntityState.NEW;
import static uk.theretiredprogrammer.nbpcglibrary.data.entity.EntityStateChangeEventParams.EntityState.NEWEDITING;
import uk.theretiredprogrammer.nbpcglibrary.data.entityreferences.*;

/**
 * The Image Entity.
 *
 * (Class generated by NetBeans Platform Code Generator tools using script.xml.
 * Do not edit this file. Apply any changes to the definition file and
 * regenerate all files.)
 *
 * @author Richard Linsdale (richard at theretiredprogrammer.uk)
 */
public class Image extends Entity<Integer, Image, Album, ImageField> {

    /**
     * the Image field identifiers
     */
    public enum ImageField {

        /**
         * the title field
         */
        TITLE,
        /**
         * the filename field
         */
        FILENAME,
        /**
         * the displayimage field
         */
        DISPLAYIMAGE,
        /**
         * the allowndownload field
         */
        ALLOWNDOWNLOAD,
        /**
         * the album field
         */
        ALBUM,
        /**
         * the idx field
         */
        IDX,
    }

    private final Rules entityRules = new Rules();
    private String title = "";
    private String titleOriginal;
    private final Rules titleRules = new Rules();
    private String filename = "";
    private String filenameOriginal;
    private final Rules filenameRules = new Rules();
    private boolean displayimage = false;
    private boolean displayimageOriginal;
    private final Rules displayimageRules = new Rules();
    private boolean allowndownload = false;
    private boolean allowndownloadOriginal;
    private final Rules allowndownloadRules = new Rules();
    private final EntityReference<Integer, Album, AlbumRoot> album;
    private int id = 0;
    private int idx = Integer.MAX_VALUE;
    private int idxOriginal;
    private String createdby = "";
    private final Timestamp createdon = new Timestamp();
    private String updatedby = "";
    private final Timestamp updatedon = new Timestamp();

    /**
     * Constructor - Image.
     *
     * @param id the unique id for this entity
     * @param em - the entity manager for this entity type
     */
    public Image(int id, Image.EM em) {
        super("Image[" + Integer.toString(id) + "]", "photo", em);
        this.id = id;
        album = new EntityReference<>("Image>Album", Album.getEM());
        addRule(album.getDefinedRule());
        addRule(titleRules, new TitleMinRule());
        addRule(titleRules, new TitleMaxRule());
        addRule(filenameRules, new FilenameMinRule());
        addRule(filenameRules, new FilenameMaxRule());
        checkRulesAtLoad();
    }

    @Override
    public boolean isPersistent() {
        return id > 0;
    }

    @Override
    public final Integer getPK() {
        return getId();
    }

    /**
     * Get all rules for this entity
     *
     * @return the set of rules
     */
    public final Rules getEntityRules() {
        return entityRules;
    }

    @Override
    public final String instanceDescription() {
        return "".equals(title)
                ? LogBuilder.instanceDescription(this, Integer.toString(getId()))
                : LogBuilder.instanceDescription(this, Integer.toString(getId()) + "-" + title);
    }

    private class TitleMinRule extends Rule {

        public TitleMinRule() {
            super("title  too short");
        }

        @Override
        public boolean ruleCheck() {
            return title.length() >= 1;
        }
    }

    private class TitleMaxRule extends Rule {

        public TitleMaxRule() {
            super("title too long");
        }

        @Override
        public boolean ruleCheck() {
            return title.length() <= 50;
        }
    }

    private class FilenameMinRule extends Rule {

        public FilenameMinRule() {
            super("filename  too short");
        }

        @Override
        public boolean ruleCheck() {
            return filename.length() >= 1;
        }
    }

    private class FilenameMaxRule extends Rule {

        public FilenameMaxRule() {
            super("filename too long");
        }

        @Override
        public boolean ruleCheck() {
            return filename.length() <= 100;
        }
    }

    /**
     * Get the title field rules.
     *
     * @return the title
     */
    public Rules getTitleRules() {
        return titleRules;
    }

    /**
     * Get the title.
     *
     * @return the title
     */
    public final String getTitle() {
        return title;
    }

    /**
     * Define the Title.
     *
     * @param title the title
     */
    public void setTitle(String title) {
        if (!this.title.equals(title)) {
            ensureEditing();
            this.title = title;
            fireFieldChange(ImageField.TITLE);
            fireNameAndOrTitleChangeOnTitle();
        }
    }

    private void fireNameAndOrTitleChangeOnTitle() {
        nameListenerFire();
        titleListenerFire();
    }

    /**
     * Get the filename field rules.
     *
     * @return the filename
     */
    public Rules getFilenameRules() {
        return filenameRules;
    }

    /**
     * Get the filename.
     *
     * @return the filename
     */
    public final String getFilename() {
        return filename;
    }

    /**
     * Define the Filename.
     *
     * @param filename the filename
     */
    public void setFilename(String filename) {
        if (!this.filename.equals(filename)) {
            ensureEditing();
            this.filename = filename;
            fireFieldChange(ImageField.FILENAME);
            fireNameAndOrTitleChangeOnFilename();
        }
    }

    private void fireNameAndOrTitleChangeOnFilename() {
    }

    /**
     * Get the displayimage field rules.
     *
     * @return the displayimage
     */
    public Rules getDisplayimageRules() {
        return displayimageRules;
    }

    /**
     * Get the displayimage.
     *
     * @return the displayimage
     */
    public final boolean getDisplayimage() {
        return displayimage;
    }

    /**
     * Define the Displayimage.
     *
     * @param displayimage the displayimage
     */
    public void setDisplayimage(boolean displayimage) {
        if (this.displayimage != displayimage) {
            ensureEditing();
            this.displayimage = displayimage;
            fireFieldChange(ImageField.DISPLAYIMAGE);
            fireNameAndOrTitleChangeOnDisplayimage();
        }
    }

    private void fireNameAndOrTitleChangeOnDisplayimage() {
    }

    /**
     * Get the allowndownload field rules.
     *
     * @return the allowndownload
     */
    public Rules getAllowndownloadRules() {
        return allowndownloadRules;
    }

    /**
     * Get the allowndownload.
     *
     * @return the allowndownload
     */
    public final boolean getAllowndownload() {
        return allowndownload;
    }

    /**
     * Define the Allowndownload.
     *
     * @param allowndownload the allowndownload
     */
    public void setAllowndownload(boolean allowndownload) {
        if (this.allowndownload != allowndownload) {
            ensureEditing();
            this.allowndownload = allowndownload;
            fireFieldChange(ImageField.ALLOWNDOWNLOAD);
            fireNameAndOrTitleChangeOnAllowndownload();
        }
    }

    private void fireNameAndOrTitleChangeOnAllowndownload() {
    }

    /**
     * Get the parent Entity associated with this entity.
     *
     * @return the Album entity
     */
    public Album getParent() {
        return album.get();
    }

    /**
     * Set the parent (Album) Entity associated with this entity. Called from
     * the parent entity as part of the addImage method
     *
     * @param e the parent album entity
     */
    protected void linkToParent(Album e) {
        ensureEditing();
        if (album.set(e.getPK())) {
            fireFieldChange(ImageField.ALBUM);
            fireNameAndOrTitleChangeOnAlbum();
        }
    }

    /**
     * Clear the parent (Album) Entity associated with this entity. Called from
     * the parent entity as part of the removeImage method
     */
    protected void unlinkFromParent() {
        ensureEditing();
        if (album.set()) {
            fireFieldChange(ImageField.ALBUM);
            fireNameAndOrTitleChangeOnAlbum();
        }
    }

    private void fireNameAndOrTitleChangeOnAlbum() {
    }

    /**
     * Get the id.
     *
     * @return the id
     */
    public final int getId() {
        return id;
    }

    @Override
    public final int getIdx() {
        return idx;
    }

    @Override
    public void setIdx(int idx) {
        if (this.idx != idx) {
            ensureEditing();
            this.idx = idx;
            fireFieldChange(ImageField.IDX);
        }
    }

    /**
     * Get the createdby.
     *
     * @return the createdby
     */
    public final String getCreatedby() {
        return createdby;
    }

    /**
     * Get the createdon.
     *
     * @return the createdon
     */
    public final Timestamp getCreatedon() {
        return createdon;
    }

    /**
     * Get the updatedby.
     *
     * @return the updatedby
     */
    public final String getUpdatedby() {
        return updatedby;
    }

    /**
     * Get the updatedon.
     *
     * @return the updatedon
     */
    public final Timestamp getUpdatedon() {
        return updatedon;
    }

    @Override
    protected final void entitySaveState() {
        titleOriginal = title;
        filenameOriginal = filename;
        displayimageOriginal = displayimage;
        allowndownloadOriginal = allowndownload;
        album.saveState();
        idxOriginal = idx;
    }

    @Override
    protected final void entityRestoreState() {
        title = titleOriginal;
        filename = filenameOriginal;
        displayimage = displayimageOriginal;
        allowndownload = allowndownloadOriginal;
        album.restoreState();
        idx = idxOriginal;
    }

    @Override
    protected final void entityRemove() {
        {
            Album.EM em = Album.getEM();
            em.getEntityPersistenceProvider().find("image", getPK()).stream().forEach((pk) -> {
                Album e = em.get(pk);
                e.setImage(null);
                e.save();
            });
        }
        getParent().removeImage(this);
    }

    @Override
    protected final void entityLoad(EntityFields data) {
        title = (String) data.get("title");
        filename = (String) data.get("filename");
        displayimage = (Boolean) data.get("displayimage");
        allowndownload = (Boolean) data.get("allowndownload");
        album.set((Integer) data.get("album"));
        id = (Integer) data.get("id");
        idx = (Integer) data.get("idx");
        createdby = (String) data.get("createdby");
        try {
            createdon.setDateUsingSQLString((String) data.get("createdon"));
        } catch (BadFormatException ex) {
            throw new LogicException("Load reported bad Timestamp format - should never happen!!");
        }
        updatedby = (String) data.get("updatedby");
        try {
            updatedon.setDateUsingSQLString((String) data.get("updatedon"));
        } catch (BadFormatException ex) {
            throw new LogicException("Load reported bad Timestamp format - should never happen!!");
        }
    }

    @Override
    protected final void entityCopy(Image from) {
        title = from.getTitle();
        filename = from.getFilename();
        displayimage = from.getDisplayimage();
        allowndownload = from.getAllowndownload();
        idx = from.getIdx();
    }

    @Override
    protected final void entityDiffs(EntityFields data) {
        if (!title.equals(titleOriginal)) {
            data.put("title", title);
        }
        if (!filename.equals(filenameOriginal)) {
            data.put("filename", filename);
        }
        if (displayimage != displayimageOriginal) {
            data.put("displayimage", displayimage);
        }
        if (allowndownload != allowndownloadOriginal) {
            data.put("allowndownload", allowndownload);
        }
        if (album.isDirty()) {
            int idrefAlbum = album.getPK();
            if (idrefAlbum < 0) {
                album.get().save();
                idrefAlbum = album.get().getPK();
            }
            data.put("album", idrefAlbum);
        }
        if (idx != idxOriginal) {
            data.put("idx", idx);
        }
    }

    @Override
    protected final void entityValues(EntityFields data) {
        data.put("title", title);
        data.put("filename", filename);
        data.put("displayimage", displayimage);
        data.put("allowndownload", allowndownload);
        int idrefAlbum = album.getPK();
        if (idrefAlbum < 0) {
            album.get().save();
            idrefAlbum = album.get().getPK();
        }
        data.put("album", idrefAlbum);
        data.put("idx", idx);
    }

    @Override
    public final boolean save() {
        EntityState state = getState();
        if (state == NEW || state == NEWEDITING) {
            if (getIdx() == Integer.MAX_VALUE) {
                setIdx(epp.findNextIdx());
            }
        }
        return super.save();
    }

    /**
     * Get the Image Entity Manager
     *
     * @return the Image Entity Manager
     */
    public static Image.EM getEM() {
        return Lookup.getDefault().lookup(Image.EM.class);
    }

    /**
     * The Image Entity Manager
     */
    @ServiceProvider(service = Image.EM.class)
    public static class EM extends EntityManager<Integer, Image, Album> {

        private static int tpk = -1;

        /**
         * Constructor.
         */
        public EM() {
            super("Image");
        }

        @Override
        protected final void link2parent(Image e, Album parent) {
            parent.addImage(e);
        }

        @Override
        protected final Image createNewEntity() {
            return new Image(tpk--, this);
        }

        @Override
        protected final Image createNewEntity(Integer pk) {
            return new Image(pk, this);
        }

        @Override
        protected final EntityPersistenceProvider createEntityPersistenceProvider() {
            return EntityPersistenceProviderManager.getEntityPersistenceProvider("photogallery", "Image", "idx");
        }

        @Override
        protected boolean isPersistent(Integer pkey) {
            return pkey > 0;
        }
    }

    /**
     * Get the set of all Images.
     *
     * @return the set of all Images
     */
    public static List<Entity> getAllImages() {
        List<Entity> list = new ArrayList<>();
        Album.getAllAlbums().stream().forEach((parent) -> {
            list.addAll(((Album) parent).getImages());
        });
        return list;
    }

    @Override
    public String getDisplayName() {
        return MessageFormat.format("{0}", formatTitle());
    }

    @Override
    public String getDisplayTitle() {
        return MessageFormat.format("{0} in {1}", formatTitle(), formatAlbum());
    }

    @Override
    public String getSortKey() {
        return getDisplayTitle();
    }

    /**
     * Get the formatted text version of title field
     *
     * @return the formatted String
     */
    public String formatTitle() {
        return getTitle();
    }

    /**
     * Get the formatted text version of filename field
     *
     * @return the formatted String
     */
    public String formatFilename() {
        return getFilename();
    }

    /**
     * Get the formatted text version of displayimage field
     *
     * @return the formatted String
     */
    public String formatDisplayimage() {
        return getDisplayimage() ? "Yes" : "No";
    }

    /**
     * Get the formatted text version of allowndownload field
     *
     * @return the formatted String
     */
    public String formatAllowndownload() {
        return getAllowndownload() ? "Yes" : "No";
    }

    /**
     * Get the formatted text version of album field
     *
     * @return the formatted String
     */
    public String formatAlbum() {
        return getParent() != null ? getParent().getDisplayName() : "undefined";
    }

    /**
     * Get the formatted text version of id field
     *
     * @return the formatted String
     */
    public String formatId() {
        return Integer.toString(getId());
    }

    /**
     * Get the formatted text version of idx field
     *
     * @return the formatted String
     */
    public String formatIdx() {
        return Integer.toString(getIdx());
    }

    /**
     * Get the formatted text version of createdby field
     *
     * @return the formatted String
     */
    public String formatCreatedby() {
        return getCreatedby();
    }

    /**
     * Get the formatted text version of createdon field
     *
     * @return the formatted String
     */
    public String formatCreatedon() {
        return getCreatedon().toString();
    }

    /**
     * Get the formatted text version of updatedby field
     *
     * @return the formatted String
     */
    public String formatUpdatedby() {
        return getUpdatedby();
    }

    /**
     * Get the formatted text version of updatedon field
     *
     * @return the formatted String
     */
    public String formatUpdatedon() {
        return getUpdatedon().toString();
    }

    /**
     * Get the formatted text version of title field left padded with zeros if
     * less than minimum size.
     *
     * @param minChars minimum size
     * @return the formatted String
     */
    public String formatTitle(int minChars) {
        return StringX.padLeftIfInt(formatTitle(), minChars, '0');
    }

    /**
     * Get the formatted text version of filename field left padded with zeros
     * if less than minimum size.
     *
     * @param minChars minimum size
     * @return the formatted String
     */
    public String formatFilename(int minChars) {
        return StringX.padLeftIfInt(formatFilename(), minChars, '0');
    }

    /**
     * Get the formatted text version of id field left padded with zeros if less
     * than minimum size.
     *
     * @param minDigits minimum size
     * @return the formatted String
     */
    public String formatId(int minDigits) {
        return StringX.padLeft(formatId(), minDigits, '0');
    }

    /**
     * Get the formatted text version of createdby field left padded with zeros
     * if less than minimum size.
     *
     * @param minChars minimum size
     * @return the formatted String
     */
    public String formatCreatedby(int minChars) {
        return StringX.padLeftIfInt(formatCreatedby(), minChars, '0');
    }

    /**
     * Get the formatted text version of updatedby field left padded with zeros
     * if less than minimum size.
     *
     * @param minChars minimum size
     * @return the formatted String
     */
    public String formatUpdatedby(int minChars) {
        return StringX.padLeftIfInt(formatUpdatedby(), minChars, '0');
    }
}


text:
mod peer;
mod stream;
mod handler;
mod action;
mod msg;
mod peer_info;
mod strategy;

pub use wire::stream::{Protocol, ChanMsg};
pub use wire::msg::PeerMsg;


text:
using namespace nano;

static bool load_json(const string_t& path, json_t& json)
{
        string_t config;
        const auto ret = load_string(path, config);
        json = json_t::parse(config);
        return ret;
}

static bool load_json(const string_t& path, json_t& json, string_t& id)
{
        return  load_json(path, json) &&
                from_json(json, "type", id);
}

int main(int argc, const char *argv[])
{
        // parse the command line
        cmdline_t cmdline("evaluate a model");
        cmdline.add("", "task",         join(get_tasks().ids()) + " (.json)");
        cmdline.add("", "fold",         "fold index to use for evaluation", "0");
        cmdline.add("", "loss",         join(get_losses().ids()) + " (.json)");
        cmdline.add("", "model",        "path to the trained model (.model)");

        cmdline.process(argc, argv);

        // check arguments and options
        const auto cmd_task = cmdline.get<string_t>("task");
        const auto cmd_fold = cmdline.get<size_t>("fold");
        const auto cmd_model = cmdline.get<string_t>("model");
        const auto cmd_loss = cmdline.get<string_t>("loss");

        checkpoint_t checkpoint;
        json_t json;
        string_t id;

        // load task
        checkpoint.step(strcat("load task configuration from <", cmd_task, ">"));
        checkpoint.critical(load_json(cmd_task, json, id));

        rtask_t task;
        checkpoint.step(strcat("search task <", id, ">"));
        checkpoint.critical((task = get_tasks().get(id)) != nullptr);

        task->from_json(json);
        checkpoint.step(strcat("load task <", id, ">"));
        checkpoint.measure(task->load());

        task->describe(id);

        // load loss
        checkpoint.step(strcat("load loss configuration from <", cmd_loss, ">"));
        checkpoint.critical(load_json(cmd_loss, json, id));

        rloss_t loss;
        checkpoint.step(strcat("search loss <", id, ">"));
        checkpoint.critical((loss = get_losses().get(id)) != nullptr);

        // load model
        checkpoint.step(strcat("load model from <", cmd_model, ">"));

        model_t model;
        checkpoint.critical(model.load(cmd_model));

        model.random();
        model.describe();
        if (model != *task)
        {
                log_error() << "model not compatible with the task!";
                return EXIT_FAILURE;
        }

        // test model
        accumulator_t acc(model, *loss);
        acc.mode(accumulator_t::type::value);

        checkpoint.step("evaluate model");
        acc.update(*task, fold_t{cmd_fold, protocol::test});
        checkpoint.measure();

        log_info() << std::fixed << std::setprecision(3)
                << "test=" << acc.vstats().avg() << "|" << acc.estats().avg() << "+/-" << acc.estats().var() << ".";

        // OK
        log_info() << done;
        return EXIT_SUCCESS;
}


text:
"""
This module implements a renderer that renders another renderer but rotated.
"""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from builtins import range

from asciimatics.renderers.base import StaticRenderer

class RotatedDuplicate(StaticRenderer):
    """
    Chained renderer to add a rotated version of the original renderer underneath and centre the
    whole thing within within the specified dimensions.
    """

    def __init__(self, width, height, renderer):
        """
        :param width: The maximum width of the rendered text.
        :param height: The maximum height of the rendered text.
        :param renderer: The renderer to wrap.
        """
        super(RotatedDuplicate, self).__init__()
        for image in renderer.images:
            mx = (width - max([len(x) for x in image])) // 2
            my = height // 2 - len(image)
            tab = (" " * mx if mx > 0 else "") + "\n" + (" " * mx if mx > 0 else "")
            new_image = []
            new_image.extend(["" for _ in range(max(0, my))])
            new_image.extend(image)
            new_image.extend([x[::-1] for x in reversed(image)])
            new_image.extend(["" for _ in range(max(0, my))])
            if mx < 0:
                new_image = [x[-mx:mx] for x in new_image]
            if my < 0:
                new_image = new_image[-my:my]
            self._images.append(tab.join(new_image))


text:
package vidoomy

import (
	"testing"

	"github.com/stretchr/testify/assert"

	"github.com/prebid/prebid-server/adapters/adapterstest"
	"github.com/prebid/prebid-server/config"
	"github.com/prebid/prebid-server/openrtb_ext"
)

func TestVidoomyBidderEndpointConfig(t *testing.T) {
	bidder, buildErr := Builder(openrtb_ext.BidderVidoomy, config.Adapter{
		Endpoint: "http://localhost/bid",
	}, config.Server{ExternalUrl: "http://hosturl.com", GvlID: 1, DataCenter: "2"})

	if buildErr != nil {
		t.Fatalf("Builder returned unexpected error %v", buildErr)
	}

	bidderVidoomy := bidder.(*adapter)

	assert.Equal(t, "http://localhost/bid", bidderVidoomy.endpoint)
}

func TestJsonSamples(t *testing.T) {
	bidder, buildErr := Builder(openrtb_ext.BidderVidoomy, config.Adapter{}, config.Server{ExternalUrl: "http://hosturl.com", GvlID: 1, DataCenter: "2"})

	if buildErr != nil {
		t.Fatalf("Builder returned unexpected error %v", buildErr)
	}

	adapterstest.RunJSONBidderTest(t, "vidoomytest", bidder)
}


text:
package uk.ac.ic.wlgitbridge.snapshot.servermock.exception;

/**
 * Created by Winston on 09/01/15.
 */
public class InvalidAPICallException extends Exception {

    public InvalidAPICallException(String target) {
        super(target);
    }

}


text:
package org.apache.jasper.servlet;

import static org.jboss.web.JasperMessages.MESSAGES;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.CodeSource;
import java.security.PermissionCollection;

import org.apache.jasper.Constants;

/**
 * Class loader for loading servlet class files (corresponding to JSP files)
 * and tag handler class files (corresponding to tag files).
 *
 * @author Anil K. Vijendran
 * @author Harish Prabandham
 * @author Jean-Francois Arcand
 */
public class JasperLoader extends URLClassLoader {

    private static final String JSP_PACKAGE_PREFIX = Constants.JSP_PACKAGE_NAME + ".";
    private PermissionCollection permissionCollection;
    private CodeSource codeSource;
    private String className;
    private ClassLoader parent;
    private SecurityManager securityManager;

    public JasperLoader(URL[] urls, ClassLoader parent,
			PermissionCollection permissionCollection,
			CodeSource codeSource) {
	super(urls, parent);
	this.permissionCollection = permissionCollection;
	this.codeSource = codeSource;
	this.parent = parent;
	this.securityManager = System.getSecurityManager();
    }

    /**
     * Load the class with the specified name.  This method searches for
     * classes in the same manner as loadClass(String, boolean)
     * with false as the second argument.
     *
     * @param name Name of the class to be loaded
     *
     * @exception ClassNotFoundException if the class was not found
     */
    public Class loadClass(String name) throws ClassNotFoundException {

        return (loadClass(name, false));
    }

    /**
     * Load the class with the specified name, searching using the following
     * algorithm until it finds and returns the class.  If the class cannot
     * be found, returns ClassNotFoundException.
     *

     *
Call findLoadedClass(String) to check if the
     *     class has already been loaded.  If it has, the same
     *     Class object is returned.

     *
If the delegate property is set to true,
     *     call the loadClass() method of the parent class
     *     loader, if any.

     *
Call findClass() to find this class in our locally
     *     defined repositories.

     *
Call the loadClass() method of our parent
     *     class loader, if any.

     *

     * If the class was found using the above steps, and the
     * resolve flag is true, this method will then
     * call resolveClass(Class) on the resulting Class object.
     *
     * @param name Name of the class to be loaded
     * @param resolve If true then resolve the class
     *
     * @exception ClassNotFoundException if the class was not found
     */
    public Class<?> loadClass(final String name, boolean resolve)
            throws ClassNotFoundException {

        Class<?> clazz = null;

        // (0) Check our previously loaded class cache
        clazz = findLoadedClass(name);
        if (clazz != null) {
            if (resolve)
                resolveClass(clazz);
            return (clazz);
        }

        // (.5) Permission to access this class when using a SecurityManager
        if (securityManager != null) {
            int dot = name.lastIndexOf('.');
            if (dot >= 0) {
                try {
                    // Do not call the security manager since by default, we
                    // grant that package.
                    if (!"org.apache.jasper.runtime".equalsIgnoreCase(name
                            .substring(0, dot))) {
                        securityManager.checkPackageAccess(name.substring(0,
                                dot));
                    }
                } catch (SecurityException se) {
                    throw new ClassNotFoundException(MESSAGES.securityExceptionLoadingClass(name), se);
                }
            }
        }

        if (!name.startsWith(JSP_PACKAGE_PREFIX)) {
            // Class is not in org.apache.jsp, therefore, have our
            // parent load it
            clazz = parent.loadClass(name);
            if (resolve)
                resolveClass(clazz);
            return clazz;
        }

        return findClass(name);
    }

    /**
     * Delegate to parent
     *
     * @see java.lang.ClassLoader#getResourceAsStream(java.lang.String)
     */
    public InputStream getResourceAsStream(String name) {
        InputStream is = parent.getResourceAsStream(name);
        if (is == null) {
            URL url = findResource(name);
            if (url != null) {
                try {
                    is = url.openStream();
                } catch (IOException e) {
                    is = null;
                }
            }
        }
        return is;
    }

    /**
     * Get the Permissions for a CodeSource.
     *
     * Since this ClassLoader is only used for a JSP page in
     * a web application context, we just return our preset
     * PermissionCollection for the web app context.
     *
     * @param codeSource Code source where the code was loaded from
     * @return PermissionCollection for CodeSource
     */
    public final PermissionCollection getPermissions(CodeSource codeSource) {
        return permissionCollection;
    }
}


text:
package org.artifactory.ui.rest.service.admin.security.signingkeys.keystore;

import org.artifactory.addon.AddonsManager;
import org.artifactory.addon.webstart.ArtifactWebstartAddon;
import org.artifactory.api.config.CentralConfigService;
import org.artifactory.api.context.ContextHelper;
import org.artifactory.rest.common.service.ArtifactoryRestRequest;
import org.artifactory.rest.common.service.RestResponse;
import org.artifactory.rest.common.service.RestService;
import org.artifactory.ui.rest.model.admin.security.signingkey.KeyStore;
import org.artifactory.ui.rest.model.utils.FileUpload;
import org.artifactory.ui.utils.MultiPartUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Chen Keinan
 */
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class AddKeyStoreService implements RestService {

    @Autowired
    CentralConfigService centralConfigService;

    @Override
    public void execute(ArtifactoryRestRequest request, RestResponse response) {
        List<String> fileNames = new ArrayList<>();
        String password = request.getQueryParamByKey("pass");
        // save keystore to temp folder
        saveKeyFileToTempFolder(request, fileNames, response);
        // load keystore to server
        loadKeyStore(response, fileNames, password);
    }

    /**
     * load KeyStore
     *
     * @param artifactoryResponse - encapsulate data related to response
     * @param fileNames           - key store name
     * @param password            - key store pass
     */
    private void loadKeyStore(RestResponse artifactoryResponse, List<String> fileNames, String password) {
        String uploadDir = ContextHelper.get().getArtifactoryHome().getTempUploadDir().getAbsolutePath();
        String keyName = fileNames.get(0);
        File file = new File(uploadDir, keyName);
        if (validateKeyStore(file, password, artifactoryResponse)) {
            int endIndex = keyName.indexOf(".");
            String alias;
            if (endIndex == -1) {
                alias = keyName;
            } else {
                alias = keyName.substring(0, endIndex);
            }
            KeyStore key = new KeyStore(true, alias, keyName, password);
            // delete keystore on temp folder
            artifactoryResponse.iModel(key);
            artifactoryResponse.info("Key Pair uploaded successfully");
        }
    }

    /**
     * save key file to temp folder
     *
     * @param artifactoryRequest - encapsulate data related to request
     * @param fileNames          - file names
     */
    private void saveKeyFileToTempFolder(ArtifactoryRestRequest artifactoryRequest, List<String> fileNames, RestResponse response) {
        FileUpload uploadFile = (FileUpload) artifactoryRequest.getImodel();
        String uploadDir = ContextHelper.get().getArtifactoryHome().getTempUploadDir().getAbsolutePath();
        MultiPartUtils.createTempFolderIfNotExist(uploadDir);
        // save file to temp folder
        try {
            MultiPartUtils.saveFileDataToTemp(centralConfigService, uploadFile.getFormDataMultiPart(), uploadDir,
                    fileNames, false);
        }catch (Exception e){
            response.error(e.getMessage());
        }
    }

    /**
     * @param file     - key store
     * @param password - key store password
     * @param response - encapsulate data relate to response
     * @return
     */
    public boolean validateKeyStore(File file, String password, RestResponse response) {
        try {
            AddonsManager addonsManager = ContextHelper.get().beanForType(AddonsManager.class);
            ArtifactWebstartAddon artifactWebstartAddon = addonsManager.addonByType(ArtifactWebstartAddon.class);
            artifactWebstartAddon.loadKeyStore(file, password);
        } catch (Exception e) {
            response.error(e.getMessage());
            return false;
        }
        return true;
    }
}


text:
import AppRoot from './AppRoot.component.js';
import React from 'react';
import ReactDOM from 'react-dom';

const app = {
  initialize() {
    ReactDOM.render(<AppRoot/>, document.getElementById('react-app-hook'));
  }
};

app.initialize();


text:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/share';
import { Subject } from 'rxjs/Subject';
var ToasterService = (function () {
    /**
     * Creates an instance of ToasterService.
     */
    function ToasterService() {
        var _this = this;
        this.addToast = new Observable(function (observer) { return _this._addToast = observer; }).share();
        this.clearToasts = new Observable(function (observer) { return _this._clearToasts = observer; }).share();
        this._removeToastSubject = new Subject();
        this.removeToast = this._removeToastSubject.share();
    }
    /**
     * Synchronously create and show a new toast instance.
     *
     * @param {(string | Toast)} type The type of the toast, or a Toast object.
     * @param {string=} title The toast title.
     * @param {string=} body The toast body.
     * @returns {Toast}
     *          The newly created Toast instance with a randomly generated GUID Id.
     */
    ToasterService.prototype.pop = function (type, title, body) {
        var toast = typeof type === 'string' ? { type: type, title: title, body: body } : type;
        toast.toastId = Guid.newGuid();
        if (!this._addToast) {
            throw new Error("No Toaster Containers have been initialized to receive toasts.");
        }
        this._addToast.next(toast);
        return toast;
    };
    /**
     * Asynchronously create and show a new toast instance.
     *
     * @param {(string | Toast)} type The type of the toast, or a Toast object.
     * @param {string=} title The toast title.
     * @param {string=} body The toast body.
     * @returns {Observable<Toast>}
     *          A hot Observable that can be subscribed to in order to receive the Toast instance
     *          with a randomly generated GUID Id.
     */
    ToasterService.prototype.popAsync = function (type, title, body) {
        var _this = this;
        setTimeout(function () {
            _this.pop(type, title, body);
        }, 0);
        return this.addToast;
    };
    /**
     * Clears a toast by toastId and/or toastContainerId.
     *
     * @param {string} toastId The toastId to clear.
     * @param {number=} toastContainerId
     *        The toastContainerId of the container to remove toasts from.
     */
    ToasterService.prototype.clear = function (toastId, toastContainerId) {
        var clearWrapper = {
            toastId: toastId, toastContainerId: toastContainerId
        };
        this._clearToasts.next(clearWrapper);
    };
    return ToasterService;
}());
export { ToasterService };
ToasterService.decorators = [
    { type: Injectable },
];
/** @nocollapse */
ToasterService.ctorParameters = function () { return []; };
// http://stackoverflow.com/questions/26501688/a-typescript-guid-class
var Guid = (function () {
    function Guid() {
    }
    Guid.newGuid = function () {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    };
    return Guid;
}());
//# sourceMappingURL=toaster.service.js.map


text:
package org.jenkinsci.plugins.rabbitmqconsumer;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

import mockit.Mocked;
import mockit.NonStrictExpectations;

import org.jenkinsci.plugins.rabbitmqconsumer.channels.ConsumeRMQChannel;
import org.jenkinsci.plugins.rabbitmqconsumer.extensions.MessageQueueListener;
import org.jenkinsci.plugins.rabbitmqconsumer.listeners.RMQConnectionListener;
import org.jenkinsci.plugins.rabbitmqconsumer.watchdog.ReconnectTimer;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * Test for RMQConnection class.
 *
 * @author rinrinne a.k.a. rin_ne
 *
 */
public class RMQConnectionTest {

    @Mocked
    ConnectionFactory factory = new ConnectionFactory();

    @Mocked
    ReconnectTimer timer = new ReconnectTimer();

    @Mocked
    MessageQueueListener mqListener = null;     /* dummy */

    @Mocked
    Connection connection;

    RMQConnectionListener connListener = new Mocks.RMQConnectionListenerMock();

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        new Mocks.RMQConnectionMock();
        new Mocks.ConsumeRMQChannelMock();
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    }

    @Before
    public void setUp() throws Exception {

        new NonStrictExpectations() {{
            connection.createChannel(); result = new Mocks.ChannelMock().getMockInstance();
            MessageQueueListener.all();
            factory.setConnectionTimeout(anyInt);
            factory.setRequestedHeartbeat(anyInt);
            factory.setUri(anyString);
            factory.newConnection(); result = connection;
            ReconnectTimer.get(); result = timer;
            timer.start();
            timer.stop();
        }};
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testOpenChannels() {
        RMQConnection conn = new RMQConnection("", "", null);
        conn.addRMQConnectionListener(connListener);
        List<RabbitmqConsumeItem> items = new ArrayList<RabbitmqConsumeItem>();
        items.add(new RabbitmqConsumeItem("app-1-a", "queue-1"));
        items.add(new RabbitmqConsumeItem("app-1-b", "queue-1"));
        items.add(new RabbitmqConsumeItem("app-2", "queue-2"));
        items.add(new RabbitmqConsumeItem("app-3", "queue-3"));

        HashSet<String> queueNameSet = new HashSet<String>();
        queueNameSet.addAll(Arrays.asList("queue-1","queue-2","queue-3"));

        try {
            conn.open();
            conn.updateChannels(items);
            Collection<ConsumeRMQChannel> channels = conn.getConsumeRMQChannels();
            assertEquals(3, channels.size());
            for (ConsumeRMQChannel ch : channels) {
                assertTrue(queueNameSet.contains(ch.getQueueName()));
                if ("queue-1".equals(ch.getQueueName())) {
                    assertEquals(2, ch.getAppIds().size());
                } else {
                    assertEquals(1, ch.getAppIds().size());
                }
            }
            conn.close();
        } catch (Exception ex) {
            fail(ex.toString());
        }
    }

    @Test
    public void testAddChannels() {
        RMQConnection conn = new RMQConnection("", "", null);
        conn.addRMQConnectionListener(connListener);
        List<RabbitmqConsumeItem> items = new ArrayList<RabbitmqConsumeItem>();
        items.add(new RabbitmqConsumeItem("app-1-a", "queue-1"));
        items.add(new RabbitmqConsumeItem("app-1-b", "queue-1"));
        items.add(new RabbitmqConsumeItem("app-2", "queue-2"));
        items.add(new RabbitmqConsumeItem("app-3", "queue-3"));

        try {
            Collection<ConsumeRMQChannel> channels;
            conn.open();
            conn.updateChannels(items);
            channels = conn.getConsumeRMQChannels();
            assertEquals(3, channels.size());

            items.add(new RabbitmqConsumeItem("app-4", "queue-4"));
            conn.updateChannels(items);
            channels = conn.getConsumeRMQChannels();
            assertEquals(4, channels.size());

            conn.close();
        } catch (Exception ex) {
            fail(ex.toString());
        }
    }

    @Test
    public void testDeleteChannels() {
        RMQConnection conn = new RMQConnection("", "", null);
        conn.addRMQConnectionListener(connListener);
        RabbitmqConsumeItem item = new RabbitmqConsumeItem("app-4", "queue-4");
        List<RabbitmqConsumeItem> items = new ArrayList<RabbitmqConsumeItem>();
        items.add(new RabbitmqConsumeItem("app-1-a", "queue-1"));
        items.add(new RabbitmqConsumeItem("app-1-b", "queue-1"));
        items.add(new RabbitmqConsumeItem("app-2", "queue-2"));
        items.add(new RabbitmqConsumeItem("app-3", "queue-3"));
        items.add(item);

        try {
            Collection<ConsumeRMQChannel> channels;
            conn.open();
            conn.updateChannels(items);
            channels = conn.getConsumeRMQChannels();
            assertEquals(4, channels.size());

            items.remove(item);
            conn.updateChannels(items);
            channels = conn.getConsumeRMQChannels();
            assertEquals(3, channels.size());

            conn.close();
        } catch (Exception ex) {
            fail(ex.toString());
        }
    }

    @Test
    public void testDeleteAndAddChannels() {
        RMQConnection conn = new RMQConnection("", "", null);
        conn.addRMQConnectionListener(connListener);
        RabbitmqConsumeItem item3 = new RabbitmqConsumeItem("app-3", "queue-3");
        RabbitmqConsumeItem item4 = new RabbitmqConsumeItem("app-4", "queue-4");
        List<RabbitmqConsumeItem> items = new ArrayList<RabbitmqConsumeItem>();
        items.add(new RabbitmqConsumeItem("app-1-a", "queue-1"));
        items.add(new RabbitmqConsumeItem("app-1-b", "queue-1"));
        items.add(new RabbitmqConsumeItem("app-2", "queue-2"));
        items.add(item3);

        try {
            Collection<ConsumeRMQChannel> channels;
            conn.open();
            conn.updateChannels(items);
            channels = conn.getConsumeRMQChannels();
            assertEquals(3, channels.size());

            items.remove(item3);
            items.add(item4);
            conn.updateChannels(items);
            channels = conn.getConsumeRMQChannels();
            assertEquals(3, channels.size());
            HashSet<String> queueNames = new HashSet<String>();
            for (ConsumeRMQChannel ch : channels) {
                queueNames.add(ch.getQueueName());
            }
            assertFalse(queueNames.contains("queue-3"));
            assertTrue(queueNames.contains("queue-4"));
            conn.close();
        } catch (Exception ex) {
            fail(ex.toString());
        }
    }

}


text:
@interface KTMenuLayer : CCLayer
{
    //Menu for aligning items.
    CCMenu *menu;
    CCMenu *infoMenu;

    CCSprite *background;

    //Two buttons
    CCMenuItemImage *hirItem;
    CCMenuItemImage *katItem;

    CCMenuItemImage *infoItem;

}

+(CCScene *) scene;
@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Globalization;

namespace Contractual.DomainModel
{
    [DataContract]
    public class Money : IFormattable
    {
        [DataMember]
        public decimal Amount { get; set; }

        [DataMember]
        public string CurrencyNumeric3
        {
            get;
            private set;
        }

        public readonly string CurrencyAlpha3;

        public Money(decimal amount, string currencyNumber)
        {
            Amount = amount;
            CurrencyNumeric3 = currencyNumber;
            CurrencyAlpha3 = MoneyFormatInfo.GetIsoField(currencyNumber);
        }

        public override string ToString()
        {
            return this.ToString("G", null);
        }

        public string ToString(string format)
        {
            return this.ToString(format, null);
        }

        public string ToString(string format, IFormatProvider formatProvider)
        {
            var check = formatProvider as MoneyFormatInfo;
            if (check != null && check.IsoField != CurrencyAlpha3)
            {
                //Force an override of the general Iso currency code request to instead use this object's specific code.
                formatProvider = check.Provider;
            }
            format = !String.IsNullOrWhiteSpace(format) ? format.ToLower() : "g";

            bool useIsoSymbol = format == "m";
            format = useIsoSymbol ? "c" : format;

            formatProvider = format == "c" ?
                new MoneyFormatInfo(CurrencyNumeric3, useIsoSymbol, formatProvider) :
                formatProvider ?? CultureInfo.CurrentCulture;

            string result = Amount.ToString(format, formatProvider);

            return result;
        }

    }

}


text:
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__),"..",".."))
require 'puppet/util/firewall'

Puppet::Type.newtype(:firewall) do
  include Puppet::Util::Firewall

  @doc = <<-EOS
    This type provides the capability to manage firewall rules within
    puppet.
  EOS

  feature :rate_limiting, "Rate limiting features."
  feature :snat, "Source NATing"
  feature :dnat, "Destination NATing"
  feature :interface_match, "Interface matching"
  feature :icmp_match, "Matching ICMP types"
  feature :owner, "Matching owners"
  feature :state_match, "Matching stateful firewall states"
  feature :reject_type, "The ability to control reject messages"
  feature :log_level, "The ability to control the log level"
  feature :log_prefix, "The ability to add prefixes to log messages"

  # provider specific features
  feature :iptables, "The provider provides iptables features."

  ensurable do
    desc <<-EOS
      Manage the state of this rule. The default action is *present*.
    EOS

    newvalue(:present) do
      provider.insert
    end

    newvalue(:absent) do
      provider.delete
    end

    defaultto :present
  end

  newparam(:name) do
    desc <<-EOS
      The canonical name of the rule. This name is also used for ordering
      so make sure you prefix the rule with a number:

          000 this runs first
          999 this runs last

      Depending on the provider, the name of the rule can be stored using
      the comment feature of the underlying firewall subsystem.
    EOS
    isnamevar

    # Keep rule names simple - they must start with a number
    newvalues(/^\d+[[:alpha:][:digit:][:punct:][:space:]]+$/)
  end

  newproperty(:action) do
    desc <<-EOS
      This is the action to perform on a match. Can be one of:

      * accept - the packet is accepted
      * reject - the packet is rejected with a suitable ICMP response
      * drop - the packet is dropped

      If you specify no value it will simply match the rule but perform no
      action unless you provide a provider specific parameter (such as *jump*).
    EOS
    newvalues(:accept, :reject, :drop)
  end

  # Generic matching properties
  newproperty(:source) do
    desc <<-EOS
      An array of source addresses. For example:

          source => '192.168.2.0/24'

      The source can also be an IPv6 address if your provider supports it.
    EOS

    munge do |value|
      @resource.host_to_ip(value)
    end
  end

  newproperty(:destination) do
    desc <<-EOS
      An array of destination addresses to match. For example:

          destination => '192.168.1.0/24'

      The destination can also be an IPv6 address if your provider supports it.
    EOS

    munge do |value|
      @resource.host_to_ip(value)
    end
  end

  newproperty(:sport, :array_matching => :all) do
    desc <<-EOS
      The source port to match for this filter (if the protocol supports
      ports). Will accept a single element or an array.

      For some firewall providers you can pass a range of ports in the format:

          <start_number>-<ending_number>

      For example:

          1-1024

      This would cover ports 1 to 1024.
    EOS

    munge do |value|
      @resource.string_to_port(value)
    end

    def should_to_s(value)
      value = [value] unless value.is_a?(Array)
      value.join(',')
    end
  end

  newproperty(:dport, :array_matching => :all) do
    desc <<-EOS
      The destination port to match for this filter (if the protocol supports
      ports). Will accept a single element or an array.

      For some firewall providers you can pass a range of ports in the format:

          <start_number>-<ending_number>

      For example:

          1-1024

      This would cover ports 1 to 1024.
    EOS

    munge do |value|
      @resource.string_to_port(value)
    end

    def should_to_s(value)
      value = [value] unless value.is_a?(Array)
      value.join(',')
    end
  end

  newproperty(:port, :array_matching => :all) do
    desc <<-EOS
      The destination or source port to match for this filter (if the protocol
      supports ports). Will accept a single element or an array.

      For some firewall providers you can pass a range of ports in the format:

          <start_number>-<ending_number>

      For example:

          1-1024

      This would cover ports 1 to 1024.
    EOS

    munge do |value|
      @resource.string_to_port(value)
    end

    def should_to_s(value)
      value = [value] unless value.is_a?(Array)
      value.join(',')
    end
  end

  newproperty(:proto) do
    desc <<-EOS
      The specific protocol to match for this rule. By default this is
      *tcp*.
    EOS

    newvalues(:tcp, :udp, :icmp, :"ipv6-icmp", :esp, :ah, :vrrp, :igmp, :ipencap, :all)
    defaultto "tcp"
  end

  # Iptables specific
  newproperty(:chain, :required_features => :iptables) do
    desc <<-EOS
      Name of the chain to use. Can be one of the built-ins:

      * INPUT
      * FORWARD
      * OUTPUT
      * PREROUTING
      * POSTROUTING

      Or you can provide a user-based chain.

      The default value is 'INPUT'.
    EOS

    defaultto "INPUT"
    newvalue(/^[a-zA-Z0-9\-_]+$/)
  end

  newproperty(:table, :required_features => :iptables) do
    desc <<-EOS
      Table to use. Can be one of:

      * nat
      * mangle
      * filter
      * raw
      * rawpost

      By default the setting is 'filter'.
    EOS

    newvalues(:nat, :mangle, :filter, :raw, :rawpost)
    defaultto "filter"
  end

  newproperty(:jump, :required_features => :iptables) do
    desc <<-EOS
      The value for the iptables --jump parameter. Normal values are:

      * QUEUE
      * RETURN
      * DNAT
      * SNAT
      * LOG
      * MASQUERADE
      * REDIRECT

      But any valid chain name is allowed.

      For the values ACCEPT, DROP and REJECT you must use the generic
      'action' parameter. This is to enfore the use of generic parameters where
      possible for maximum cross-platform modelling.

      If you set both 'accept' and 'jump' parameters, you will get an error as
      only one of the options should be set.
    EOS

    validate do |value|
      unless value =~ /^[a-zA-Z0-9\-_]+$/
        raise ArgumentError, <<-EOS
          Jump destination must consist of alphanumeric characters, an
          underscore or a yphen.
        EOS
      end

      if ["accept","reject","drop"].include?(value.downcase)
        raise ArgumentError, <<-EOS
          Jump destination should not be one of ACCEPT, REJECT or DENY. Use
          the action property instead.
        EOS
      end

    end
  end

  # Interface specific matching properties
  newproperty(:iniface, :required_features => :interface_match) do
    desc <<-EOS
      Input interface to filter on.
    EOS
    newvalues(/^[a-zA-Z0-9\-_]+$/)
  end

  newproperty(:outiface, :required_features => :interface_match) do
    desc <<-EOS
      Output interface to filter on.
    EOS
    newvalues(/^[a-zA-Z0-9\-_]+$/)
  end

  # NAT specific properties
  newproperty(:tosource, :required_features => :snat) do
    desc <<-EOS
      When using jump => "SNAT" you can specify the new source address using
      this parameter.
    EOS
  end

  newproperty(:todest, :required_features => :dnat) do
    desc <<-EOS
      When using jump => "DNAT" you can specify the new destination address
      using this paramter.
    EOS
  end

  newproperty(:toports, :required_features => :dnat) do
    desc <<-EOS
      For DNAT this is the port that will replace the destination port.
    EOS
  end

  # Reject ICMP type
  newproperty(:reject, :required_features => :reject_type) do
    desc <<-EOS
      When combined with jump => "REJECT" you can specify a different icmp
      response to be sent back to the packet sender.
    EOS
  end

  # Logging properties
  newproperty(:log_level, :required_features => :log_level) do
    desc <<-EOS
      When combined with jump => "LOG" specifies the system log level to log
      to.
    EOS

    munge do |value|
      if value.kind_of?(String)
        value = @resource.log_level_name_to_number(value)
      else
        value
      end

      if value == nil && value != ""
        self.fail("Unable to determine log level")
      end
      value
    end
  end

  newproperty(:log_prefix, :required_features => :log_prefix) do
    desc <<-EOS
      When combined with jump => "LOG" specifies the log prefix to use when
      logging.
    EOS
  end

  # ICMP matching property
  newproperty(:icmp, :required_features => :icmp_match) do
    desc <<-EOS
      When matching ICMP packets, this is the type of ICMP packet to match.
    EOS

    munge do |value|
      if value.kind_of?(String)
        value = @resource.icmp_name_to_number(value)
      else
        value
      end

      if value == nil && value != ""
        self.fail("cannot work out icmp type")
      end
      value
    end
  end

  newproperty(:state, :array_matching => :all, :required_features =>
    :state_match) do

    desc <<-EOS
      Matches a packet based on its state in the firewall stateful inspection
      table. Values can be:

      * INVALID
      * ESTABLISHED
      * NEW
      * RELATED
    EOS

    newvalues(:INVALID,:ESTABLISHED,:NEW,:RELATED)

    # States should always be sorted. This normalizes the resource states to
    # keep it consistent with the sorted result from iptables-save.
    def should=(values)
      @should = super(values).sort
    end

    def should_to_s(value)
      value = [value] unless value.is_a?(Array)
      value.join(',')
    end
  end

  # Rate limiting properties
  newproperty(:limit, :required_features => :rate_limiting) do
    desc <<-EOS
      Rate limiting value for matched packets. The format is:
      rate/[/second/|/minute|/hour|/day].

      Example values are: '50/sec', '40/min', '30/hour', '10/day'."
    EOS
  end

  newproperty(:burst, :required_features => :rate_limiting) do
    desc <<-EOS
      Rate limiting burst value (per second) before limit checks apply.
    EOS
    newvalue(/^\d+$/)
  end

  newproperty(:uid, :array_matching =>:all, :required_features => :owner) do
    desc <<-EOS
      UID or Username owner matching rule.  Accepts a string argument
      only, as iptables does not accept multiple uid in a single
      statement.
    EOS
  end

  newproperty(:gid, :array_matching =>:all, :required_features => :owner) do
    desc <<-EOS
      GID or Group owner matching rule.  Accepts a string argument
      only, as iptables does not accept multiple gid in a single
      statement.
    EOS
  end

  newparam(:line) do
    desc <<-EOS
      Read-only property for caching the rule line.
    EOS
  end

  validate do
    debug("[validate]")

    # TODO: this is put here to skip validation if ensure is not set. This
    # is because there is a revalidation stage called later where the values
    # are not set correctly. I tried tracing it - but have put in this
    # workaround instead to skip. Must get to the bottom of this.
    if ! value(:ensure)
      return
    end

    # First we make sure the chains and tables are valid combinations
    if value(:table).to_s == "filter" &&
      value(:chain) =~ /PREROUTING|POSTROUTING/

      self.fail "PREROUTING and POSTROUTING cannot be used in table 'filter'"
    end

    if value(:table).to_s == "nat" && value(:chain) =~ /INPUT|FORWARD/
      self.fail "INPUT and FORWARD cannot be used in table 'nat'"
    end

    if value(:table).to_s == "raw" &&
      value(:chain) =~ /INPUT|FORWARD|POSTROUTING/

      self.fail "INPUT, FORWARD and POSTROUTING cannot be used in table raw"
    end

    # Now we analyse the individual properties to make sure they apply to
    # the correct combinations.
    if value(:iniface)
      unless value(:chain).to_s =~ /INPUT|FORWARD|PREROUTING/
        self.fail "Parameter iniface only applies to chains " \
          "INPUT,FORWARD,PREROUTING"
      end
    end

    if value(:outiface)
      unless value(:chain).to_s =~ /OUTPUT|FORWARD|POSTROUTING/
        self.fail "Parameter outiface only applies to chains " \
          "OUTPUT,FORWARD,POSTROUTING"
      end
    end

    if value(:uid)
      unless value(:chain).to_s =~ /OUTPUT|POSTROUTING/
        self.fail "Parameter uid only applies to chains " \
          "OUTPUT,POSTROUTING"
      end
    end

    if value(:gid)
      unless value(:chain).to_s =~ /OUTPUT|POSTROUTING/
        self.fail "Parameter gid only applies to chains " \
          "OUTPUT,POSTROUTING"
      end
    end

    if value(:dport)
      unless value(:proto).to_s =~ /tcp|udp|sctp/
        self.fail "[%s] Parameter dport only applies to sctp, tcp and udp " \
          "protocols. Current protocol is [%s] and dport is [%s]" %
          [value(:name), should(:proto), should(:dport)]
      end
    end

    if value(:jump).to_s == "DNAT"
      unless value(:table).to_s =~ /nat/
        self.fail "Parameter jump => DNAT only applies to table => nat"
      end

      unless value(:todest)
        self.fail "Parameter jump => DNAT must have todest parameter"
      end
    end

    if value(:jump).to_s == "SNAT"
      unless value(:table).to_s =~ /nat/
        self.fail "Parameter jump => SNAT only applies to table => nat"
      end

      unless value(:tosource)
        self.fail "Parameter jump => DNAT must have tosource parameter"
      end
    end

    if value(:jump).to_s == "REDIRECT"
      unless value(:toports)
        self.fail "Parameter jump => REDIRECT missing mandatory toports " \
          "parameter"
      end
    end

    if value(:jump).to_s == "MASQUERADE"
      unless value(:table).to_s =~ /nat/
        self.fail "Parameter jump => MASQUERADE only applies to table => nat"
      end
    end

    if value(:burst) && ! value(:limit)
      self.fail "burst makes no sense without limit"
    end

    if value(:action) && value(:jump)
      self.fail "Only one of the parameters 'action' and 'jump' can be set"
    end
  end
end


text:
![Android-ActionButton](https://raw.githubusercontent.com/klinker41/Android-ActionButton/master/preview.png)

### Information

[Video](https://www.youtube.com/watch?v=AU8RalwVOXU)

Implementing an ActionButton in your Android apps is extremely simple, it works very similarly to creating a toast
or AlertDialog.

Here is a sample to show a button:
``` java
final ActionButton button = new ActionButton(mContext);
button.setImageResource(R.drawable.icon);
button.setColors(getResources().getColor(android.R.color.holo_blue_light),
    getResources().getColor(android.R.color.holo_blue_dark));
button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // do something with click
        button.hide();
    }
});
button.show();
```

Note: Currently only supported for API version 14 and higher, if I have time I may be able to backport it to lower, but
I highly suggest people begin setting their minSdkVersion to 14, there are so many more possibilities and Gingerbread
is dying!

## Gradle

To include in your gradle projects:

```groovy
compile 'com.klinkerapps:android-actionbutton:+@aar'
```
## License

    Copyright 2013-2014 Jacob Klinker

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


text:
package com.facebook.buck.jvm.java;

import com.facebook.buck.model.Either;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.RuleKeyObjectSink;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.util.HumanReadableException;
import com.google.common.base.Preconditions;

import java.util.Optional;

import javax.annotation.Nullable;

/**
 * Provides either an {@link ExternalJavac} or {@link JarBackedJavac}, depending on its parameters.
 * This is here to support {@link JvmLibraryArg#compiler}.
 */
public class ExternalOrJarBackedJavacProvider implements JavacProvider {
  private final SourcePath compiler;
  @Nullable
  private final String compilerClassName;
  @Nullable
  private Javac javac;

  public ExternalOrJarBackedJavacProvider(
      SourcePath compiler,
      @Nullable String compilerClassName) {
    this.compiler = compiler;
    this.compilerClassName = compilerClassName;
  }

  @Override
  public void appendToRuleKey(RuleKeyObjectSink sink) {
    sink
        .setReflectively("compiler", compiler)
        .setReflectively("compilerClassName", compilerClassName);
  }

  @Override
  public Javac resolve(SourcePathRuleFinder ruleFinder) {
    if (javac == null) {
      Optional<BuildRule> possibleRule = ruleFinder.getRule(compiler);
      if (possibleRule.isPresent() && possibleRule.get() instanceof JavaLibrary) {
        SourcePath javacJarPath = possibleRule.get().getSourcePathToOutput();
        if (javacJarPath == null) {
          throw new HumanReadableException(String.format(
              "%s isn't a valid value for javac_jar because it does not produce output",
              compiler));
        }

        javac =
            new JarBackedJavacProvider(
                javacJarPath,
                Preconditions.checkNotNull(compilerClassName),
                Javac.Location.IN_PROCESS)
            .resolve(ruleFinder);
      } else {
        javac = new ExternalJavac(Either.ofRight(compiler));
      }
    }

    return javac;
  }
}


text:
package twitter4j.internal.json;

import twitter4j.*;

import javax.annotation.Generated;
import java.util.Map;

/**
 * @author Yusuke Yamamoto - yusuke at mac.com
 * @since Twitter4J 2.2.3
 */
@Generated(
        value = "generate-lazy-objects.sh",
        comments = "This is Tool Generated Code. DO NOT EDIT",
        date = "2011-07-13"
)
final class LazyTwitterAPIConfiguration implements twitter4j.TwitterAPIConfiguration {
    private twitter4j.internal.http.HttpResponse res;
    private z_T4JInternalFactory factory;
    private TwitterAPIConfiguration target = null;

    LazyTwitterAPIConfiguration(twitter4j.internal.http.HttpResponse res, z_T4JInternalFactory factory) {
        this.res = res;
        this.factory = factory;
    }

    private TwitterAPIConfiguration getTarget() {
        if (target == null) {
            try {
                target = factory.createTwitterAPIConfiguration(res);
            } catch (TwitterException e) {
                throw new TwitterRuntimeException(e);
            }
        }
        return target;
    }

    public int getPhotoSizeLimit() {
        return getTarget().getPhotoSizeLimit();
    }

    public int getShortURLLength() {
        return getTarget().getShortURLLength();
    }

    public int getShortURLLengthHttps() {
        return getTarget().getShortURLLengthHttps();
    }

    public int getCharactersReservedPerMedia() {
        return getTarget().getCharactersReservedPerMedia();
    }

    public Map<Integer, MediaEntity.Size> getPhotoSizes() {
        return getTarget().getPhotoSizes();
    }

    public String[] getNonUsernamePaths() {
        return getTarget().getNonUsernamePaths();
    }

    public int getMaxMediaPerUpload() {
        return getTarget().getMaxMediaPerUpload();
    }

    public RateLimitStatus getRateLimitStatus() {
        return getTarget().getRateLimitStatus();
    }

    public int getAccessLevel() {
        return getTarget().getAccessLevel();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof TwitterAPIConfiguration)) return false;
        return getTarget().equals(o);
    }

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

    @Override
    public String toString() {
        return "LazyTwitterAPIConfiguration{" +
                "target=" + getTarget() +
                "}";
    }
}


text:
namespace autofill {

// static
LogRouter* AutofillLogRouterFactory::GetForBrowserState(
    ChromeBrowserState* browser_state) {
  return static_cast<LogRouter*>(
      GetInstance()->GetServiceForBrowserState(browser_state, true));
}

// static
AutofillLogRouterFactory* AutofillLogRouterFactory::GetInstance() {
  static base::NoDestructor<AutofillLogRouterFactory> instance;
  return instance.get();
}

AutofillLogRouterFactory::AutofillLogRouterFactory()
    : BrowserStateKeyedServiceFactory(
          "AutofillInternalsService",
          BrowserStateDependencyManager::GetInstance()) {}

AutofillLogRouterFactory::~AutofillLogRouterFactory() = default;

std::unique_ptr<KeyedService> AutofillLogRouterFactory::BuildServiceInstanceFor(
    web::BrowserState* context) const {
  return std::make_unique<LogRouter>();
}

}  // namespace autofill


text:
  Fontains est
       un village
       géographiquement positionné dans le département de Seine-et-Marne en Île-de-France. Elle comptait 261 habitants en 2008.

Le parc d'habitations, à Fontains, se décomposait en 2011 en un appartements et 118 maisons soit
 un marché plutôt équilibré.

Si vous envisagez de demenager à Fontains, vous pourrez aisément trouver une maison à vendre.

À proximité de Fontains sont positionnées géographiquement les communes de
Saint-Ouen-en-Brie située à 7 km, 843 habitants,
Rampillon localisée à 5 km, 762 habitants,
Nangis localisée à 3 km, 7 557 habitants,
La Chapelle-Rablais située à 2 km, 889 habitants,
Fontenailles à 4 km, 982 habitants,
Villeneuve-les-Bordes à 5 km, 560 habitants,
 entre autres. De plus, Fontains est située à seulement 25 km de Melun.

La commune compte quelques  aménagements, elle dispose, entre autres, de un terrain de tennis et un terrain de sport.


text:
#include <linux/moduleloader.h>
#include <linux/elf.h>
#include <linux/vmalloc.h>
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/slab.h>

#if 0
#define DEBUGP printk
#else
#define DEBUGP(fmt , ...)
#endif

#ifdef CONFIG_ETRAX_KMALLOCED_MODULES
void *module_alloc(unsigned long size)
{
	if (size == 0)
		return NULL;
	return kmalloc(size, GFP_KERNEL);
}

/* Free memory returned from module_alloc */
void module_free(struct module *mod, void *module_region)
{
	kfree(module_region);
}
#endif

int apply_relocate_add(Elf32_Shdr *sechdrs,
		       const char *strtab,
		       unsigned int symindex,
		       unsigned int relsec,
		       struct module *me)
{
  	unsigned int i;
	Elf32_Rela *rela = (void *)sechdrs[relsec].sh_addr;

	DEBUGP ("Applying add relocate section %u to %u\n", relsec,
		sechdrs[relsec].sh_info);

	for (i = 0; i < sechdrs[relsec].sh_size / sizeof (*rela); i++) {
		/* This is where to make the change */
		uint32_t *loc
			= ((void *)sechdrs[sechdrs[relsec].sh_info].sh_addr
			   + rela[i].r_offset);
		/* This is the symbol it is referring to.  Note that all
		   undefined symbols have been resolved.  */
		Elf32_Sym *sym
			= ((Elf32_Sym *)sechdrs[symindex].sh_addr
			   + ELF32_R_SYM (rela[i].r_info));
		switch (ELF32_R_TYPE(rela[i].r_info)) {
		case R_CRIS_32:
			*loc = sym->st_value + rela[i].r_addend;
			break;
		case R_CRIS_32_PCREL:
			*loc = sym->st_value - (unsigned)loc + rela[i].r_addend - 4;
			 break;
		default:
			printk(KERN_ERR "module %s: Unknown relocation: %u\n",
			       me->name, ELF32_R_TYPE(rela[i].r_info));
			return -ENOEXEC;
		}
	}

	return 0;
}


text:
package org.apache.servicemix.specs.activation;

import java.util.Map;
import java.util.HashMap;

import javax.activation.MailcapCommandMap;
import javax.activation.CommandInfo;
import javax.activation.DataContentHandler;

import org.osgi.framework.Bundle;

/**
 * An OSGi enabled MailcapCommandMap
 */
public class OsgiMailcapCommandMap extends MailcapCommandMap {

    private Bundle currentBundle;
    private Map<CommandInfo, Bundle> bundles = new HashMap<CommandInfo, Bundle>();

    public void addMailcap(String line, Bundle bundle) {
        currentBundle = bundle;
        addMailcap(line);
    }

    protected void addCommand(Map commandList, String mimeType, CommandInfo command) {
        super.addCommand(commandList, mimeType, command);
        if (currentBundle != null) {
            bundles.put(command, currentBundle);
        }
    }

    @Override
    public DataContentHandler createDataContentHandler(String mimeType) {
        CommandInfo info = getCommand(mimeType, "content-handler");
        if (info == null) {
            return null;
        }

        Bundle bundle = bundles.get(info);
        if (bundle != null) {
            try {
                return (DataContentHandler) bundle.loadClass(info.getCommandClass()).newInstance();
            } catch (ClassNotFoundException e) {
                return null;
            } catch (IllegalAccessException e) {
                return null;
            } catch (InstantiationException e) {
                return null;
            }
        }

        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        if (cl == null) {
            cl = getClass().getClassLoader();
        }
        try {
            return (DataContentHandler) cl.loadClass(info.getCommandClass()).newInstance();
        } catch (ClassNotFoundException e) {
            return null;
        } catch (IllegalAccessException e) {
            return null;
        } catch (InstantiationException e) {
            return null;
        }
    }
}


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch07/7.6/7.6.1/7.6.1-7-3.js
 * @description Allow reserved words as property names by index assignment, accessed via indexing: instanceof, typeof, else
 */

function testcase() {
        var tokenCodes = {};
        tokenCodes['instanceof'] = 0;
        tokenCodes['typeof'] = 1;
        tokenCodes['else'] = 2;
        var arr = [
            'instanceof',
            'typeof',
            'else'
        ];
        for (var i = 0; i < arr.length; i++) {
            if (tokenCodes[arr[i]] !== i) {
                return false;
            };
        }
        return true;
    }
runTestCase(testcase);