text:
package com.cisco.oss.foundation.directory.impl;

import static org.junit.Assert.fail;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Assert;
import org.junit.Test;

import com.cisco.oss.foundation.directory.ServiceDirectory;
import com.cisco.oss.foundation.directory.ServiceInstanceHealth;
import com.cisco.oss.foundation.directory.entity.OperationResult;
import com.cisco.oss.foundation.directory.entity.OperationalStatus;
import com.cisco.oss.foundation.directory.entity.ProvidedServiceInstance;
import com.cisco.oss.foundation.directory.entity.ServiceInstanceHeartbeat;
import com.cisco.oss.foundation.directory.exception.ErrorCode;
import com.cisco.oss.foundation.directory.exception.ServiceException;

public class RegistrationManagerImplTest {

    @Test
    public void testRegisterService(){

        ServiceDirectory.getServiceDirectoryConfig().setProperty(HeartbeatDirectoryRegistrationService.SD_API_HEARTBEAT_INTERVAL_PROPERTY, 1);
        ServiceDirectory.getServiceDirectoryConfig().setProperty(HeartbeatDirectoryRegistrationService.SD_API_REGISTRY_HEALTH_CHECK_INTERVAL_PROPERTY, 1);

        final ProvidedServiceInstance instance = new ProvidedServiceInstance("odrm", "192.168.7.4", 8901);
        instance.setMonitorEnabled(true);
        instance.setStatus(OperationalStatus.UP);
        instance.setUri("http://cisco.com/vbo/odrm/setupsession");
        Map<String, String> metadata = new HashMap<String, String>();
        metadata.put("datacenter", "dc01");
        metadata.put("solution", "core");
        instance.setMetadata(metadata);

        final ProvidedServiceInstance instance2 = new ProvidedServiceInstance("odrm", "192.168.7.4", 8902);
        instance2.setMonitorEnabled(false);
        instance2.setStatus(OperationalStatus.UP);
        instance2.setUri("http://cisco.com/vbo/odrm/setupsession");
        instance2.setMetadata(metadata);

        final AtomicInteger registerInvoked = new AtomicInteger(0);
        final AtomicInteger hbInvoked = new AtomicInteger(0);
        final AtomicInteger healthInvoked = new AtomicInteger(0);
        final AtomicInteger statusInvoked = new AtomicInteger(0);
        final AtomicInteger unregisterInvoked = new AtomicInteger(0);

        HeartbeatRegistrationManagerImpl impl = new HeartbeatRegistrationManagerImpl(new HeartbeatDirectoryRegistrationService(new DirectoryServiceClient(){
            @Override
            public void registerInstance(ProvidedServiceInstance inst) {
                Assert.assertTrue(instance == inst || instance2 == inst);
                registerInvoked.incrementAndGet();
            }

            @Override
            public Map<String, OperationResult<String>> sendHeartBeat(Map<String, ServiceInstanceHeartbeat> heartbeatMap) {

                Assert.assertEquals(heartbeatMap.size(), 1);
                Assert.assertTrue(heartbeatMap.containsKey("odrm-192.168.7.4-8901"));
                Map<String, OperationResult<String>> result = new HashMap<String, OperationResult<String>>();
                result.put("odrm-192.168.7.4-8901", new OperationResult<String>(true, "it is OK", null));
                hbInvoked.incrementAndGet();
                return result;
            }

            @Override
            public void updateInstanceStatus(String serviceName, String instanceId, OperationalStatus status, boolean isOwned) {
                statusInvoked.incrementAndGet();
                Assert.assertEquals(serviceName, "odrm");
                Assert.assertEquals(instanceId, "192.168.7.4-8901");
                Assert.assertEquals(OperationalStatus.DOWN, status);
                Assert.assertTrue(isOwned);
            }

            @Override
            public void unregisterInstance(String serviceName, String instanceId, boolean isOwned) {
                unregisterInvoked.incrementAndGet();
                Assert.assertEquals(serviceName, "odrm");
                Assert.assertEquals(instanceId, "192.168.7.4-8901");
                Assert.assertTrue(isOwned);
            }
        }));
        impl.start();

        final AtomicBoolean ret = new AtomicBoolean(false);
        ServiceInstanceHealth health = new ServiceInstanceHealth(){
            @Override
            public boolean isHealthy() {
                healthInvoked.incrementAndGet();
                return ret.get();
            }
        };

        try {
            impl.registerService(instance);
            impl.registerService(instance2);
            instance.setStatus(OperationalStatus.UP);
            impl.registerService(instance);
//            impl.registerService(instance, OperationalStatus.UP, health);
        } catch (ServiceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Check the RegistrationManager send heartbeat and do the register.
        Assert.assertTrue(registerInvoked.get()==3);
        Assert.assertTrue(hbInvoked.get() > 0);

        try {
            impl.registerService(instance, health);
        } catch (ServiceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Check the ServiceInstanceHealth invoked.
        Assert.assertTrue(healthInvoked.get() > 0);
        Assert.assertEquals(statusInvoked.get(), 0);

        // Since the ServiceInstanceHealth return false, the heartbeat should stop fine.
        hbInvoked.set(0);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Assert.assertEquals(hbInvoked.get(), 0);

        //set the ServiceInstanceHealth return true, check the heartbeat should send again.
        ret.set(true);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Assert.assertTrue(hbInvoked.get()>0);

        try {
            impl.unregisterService(instance.getServiceName(), instance.getProviderId());
        } catch (ServiceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        hbInvoked.set(0);

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Assert.assertTrue(hbInvoked.get()==0);
        Assert.assertTrue(unregisterInvoked.get()==1);

    }

    @Test
    public void testUpdateService(){
        ServiceDirectory.getServiceDirectoryConfig().setProperty(HeartbeatDirectoryRegistrationService.SD_API_HEARTBEAT_INTERVAL_PROPERTY, 1);
        ServiceDirectory.getServiceDirectoryConfig().setProperty(HeartbeatDirectoryRegistrationService.SD_API_REGISTRY_HEALTH_CHECK_INTERVAL_PROPERTY, 1);

        final ProvidedServiceInstance instance = new ProvidedServiceInstance("odrm", "192.168.7.4", 8901);
        instance.setMonitorEnabled(true);
        instance.setStatus(OperationalStatus.UP);
        instance.setUri("http://cisco.com/vbo/odrm/setupsession");
        Map<String, String> metadata = new HashMap<String, String>();
        metadata.put("datacenter", "dc01");
        metadata.put("solution", "core");
        instance.setMetadata(metadata);

        final AtomicInteger updateInvoked = new AtomicInteger(0);
        final AtomicInteger uriInvoked = new AtomicInteger(0);
        final AtomicInteger statusInvoked = new AtomicInteger(0);
        final AtomicInteger hbInvoked = new AtomicInteger(0);

        RegistrationManagerImpl impl = new RegistrationManagerImpl(new HeartbeatDirectoryRegistrationService(new DirectoryServiceClient(){

            @Override
            public void registerInstance(ProvidedServiceInstance inst) {
            }

            @Override
            public Map<String, OperationResult<String>> sendHeartBeat(Map<String, ServiceInstanceHeartbeat> heartbeatMap) {

                Assert.assertEquals(heartbeatMap.size(), 1);
                Assert.assertTrue(heartbeatMap.containsKey("odrm-192.168.7.4-8901"));
                Map<String, OperationResult<String>> result = new HashMap<String, OperationResult<String>>();
                result.put("odrm-192.168.7.4-8901", new OperationResult<String>(true, "it is OK", null));
                hbInvoked.incrementAndGet();
                return result;
            }

            @Override
            public void updateInstance(ProvidedServiceInstance inst) {
                updateInvoked.incrementAndGet();
                Assert.assertTrue(inst == instance);
            }

            @Override
            public void updateInstanceStatus(String serviceName, String instanceId, OperationalStatus status, boolean isOwned) {
                statusInvoked.incrementAndGet();
                Assert.assertEquals(serviceName, "odrm");
                Assert.assertEquals(instanceId, "192.168.7.4-8901");
                Assert.assertEquals(OperationalStatus.DOWN, status);
                Assert.assertTrue(isOwned);
            }

            @Override
            public void updateInstanceUri(String serviceName, String instanceId, String uri, boolean isOwned) {
                uriInvoked.incrementAndGet();
                Assert.assertEquals(serviceName, "odrm");
                Assert.assertEquals(instanceId, "192.168.7.4-8901");
                Assert.assertEquals("new", uri);
                Assert.assertTrue(isOwned);
            }

            @Override
            public void unregisterInstance(String serviceName, String instanceId, boolean isOwned) {
                Assert.assertEquals(serviceName, "odrm");
                Assert.assertEquals(instanceId, "192.168.7.4-8901");
                Assert.assertTrue(isOwned);
            }

        }));
        impl.start();

        try {
            impl.registerService(instance);
            impl.updateService(instance);
            impl.updateServiceOperationalStatus("odrm", "192.168.7.4-8901", OperationalStatus.DOWN);
            impl.updateServiceUri("odrm", "192.168.7.4-8901", "new");
        } catch (ServiceException e) {
            e.printStackTrace();
        }

        Assert.assertTrue(updateInvoked.get() > 0);
        Assert.assertTrue(statusInvoked.get() > 0);
        Assert.assertTrue(uriInvoked.get() > 0);

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        hbInvoked.set(0);

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Updated the ServiceInstance to DOWN, it should have no heartbeat.
        Assert.assertTrue(hbInvoked.get() ==0);

        try {
            impl.unregisterService(instance.getServiceName(), instance.getProviderId());
        } catch (ServiceException e) {
            e.printStackTrace();
            fail("unregisterService failed.");
        }

        try {
            impl.updateService(instance);
            fail(); //should not go there
        } catch (ServiceException e) {
            Assert.assertEquals(ErrorCode.ILLEGAL_SERVICE_INSTANCE_OWNER_ERROR, e.getServiceDirectoryError().getExceptionCode());
        }

    }

//    private static DirectoryServiceClientManager manager ;
//    public static DirectoryServiceClientManager getDirectoryServiceClientManager(){
//        if(manager == null){
//            manager = new DirectoryServiceClientManager(){
//                @Override
//                public DirectoryServiceClient getDirectoryServiceClient() {
//                    // TODO Auto-generated method stub
//                    return null;
//                }
//            };
//        }
//        return manager;
//    }
}


text:
package fr.paris.lutece.portal.service.insert;

import fr.paris.lutece.portal.service.util.AppLogService;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Manager of the InsertServices (Insert + HTML). Responsible for (un)registering them.
 */
public final class InsertServiceManager
{
    // //////////////////////////////////////////////////////////////////////////
    // Class attributes

    /** Insert Service registry */
    private static Map<String, InsertService> _mapInsertServicesRegistry = new HashMap<>( );

    // //////////////////////////////////////////////////////////////////////////
    // Methods

    /**
     * Creates a new InsertServiceManager object
     */
    private InsertServiceManager( )
    {
    }

    /**
     * Registers a new Index Service
     *
     * @param is
     *            the service
     */
    public static void registerInsertService( InsertService is )
    {
        _mapInsertServicesRegistry.put( is.getId( ), is );
        AppLogService.info( "New Insert Service registered : {}", is.getId( ) );
    }

    /**
     * Unregisters a new Index Service
     *
     * @param is
     *            the service
     */
    public static void unregisterInsertService( InsertService is )
    {
        _mapInsertServicesRegistry.remove( is.getId( ) );
        AppLogService.info( "Service unregistered : {}", is.getId( ) );
    }

    /**
     * Returns all registered Insert services
     *
     * @return A collection containing all registered Insert services
     */
    public static Collection<InsertService> getInsertServicesList( )
    {
        ArrayList<InsertService> listServices = new ArrayList<>( );

        for ( InsertService service : _mapInsertServicesRegistry.values( ) )
        {
            if ( service.isEnabled( ) )
            {
                listServices.add( service );
            }
        }

        return listServices;
    }

    /**
     * Get a particular Insert service
     *
     * @param strId
     *            Identifier of the seeked service
     * @return the selected Insert service
     */
    public static InsertService getInsertService( String strId )
    {
        return _mapInsertServicesRegistry.get( strId );
    }

    /**
     * Returns the names of all registered Insert Service
     *
     * @return An enumeration containing the names of all registered Insert Service
     */
    public static List<String> getInsertsLabels( )
    {
        List<String> listInserts = new ArrayList<>( );

        for ( InsertService ls : getInsertServicesList( ) )
        {
            listInserts.add( ls.getLabelKey( ) );
        }

        return listInserts;
    }
}

redpajama_set_name: RedPajamaGithub


text:
(function () {
    'use strict';

    angular.module('app.core').service('BookStatusService', BookStatusService);

    BookStatusService.$inject = ['$resource'];

    function BookStatusService($resource) {
        return $resource('/library/api/bookStatus', {}, {
            get: {
                method: 'GET',
                isArray: true,
                headers: {Accept: 'application/json'}
            }
        });
    }
}());


text:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using Serilog;
using Thinktecture.Relay.Server.Config;
using Thinktecture.Relay.Server.Dto;
using Thinktecture.Relay.Server.Repository.DbModels;
using Thinktecture.Relay.Server.Security;

namespace Thinktecture.Relay.Server.Repository
{
	public class UserRepository : IUserRepository
	{
		private readonly ILogger _logger;
		private readonly IPasswordHash _passwordHash;
		private readonly IConfiguration _configuration;

		public UserRepository(ILogger logger, IPasswordHash passwordHash, IConfiguration configuration)
		{
			_logger = logger;

			_passwordHash = passwordHash ?? throw new ArgumentNullException(nameof(passwordHash));
			_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
		}

		public Guid Create(string userName, string password)
		{
			if ((String.IsNullOrWhiteSpace(userName)) || (String.IsNullOrWhiteSpace(password)))
			{
				return Guid.Empty;
			}

			var passwordInformation = _passwordHash.CreatePasswordInformation(Encoding.UTF8.GetBytes(password));

			var dbUser = new DbUser
			{
				Id = Guid.NewGuid(),
				Iterations = passwordInformation.Iterations,
				Password = passwordInformation.Hash,
				Salt = passwordInformation.Salt,
				UserName = userName,
				CreationDate = DateTime.Now,
			};

			using (var context = new RelayContext())
			{
				context.Users.Add(dbUser);
				context.SaveChanges();

				return dbUser.Id;
			}
		}

		public User Authenticate(string userName, string password)
		{
			if ((String.IsNullOrWhiteSpace(userName)) || (String.IsNullOrWhiteSpace(password)))
			{
				return null;
			}

			using (var context = new RelayContext())
			{
				var user = context.Users.SingleOrDefault(u => u.UserName == userName);

				if (user == null || IsUserLockedOut(user))
				{
					return null;
				}

				var passwordInformation = new PasswordInformation
				{
					Hash = user.Password,
					Salt = user.Salt,
					Iterations = user.Iterations,
				};

				if (_passwordHash.ValidatePassword(Encoding.UTF8.GetBytes(password), passwordInformation))
				{
					if (user.FailedLoginAttempts.HasValue || user.LastFailedLoginAttempt.HasValue)
					{
						// login was successful, so reset potential previous failed attempts
						UnlockUser(context, user);
					}

					return new User()
					{
						UserName = user.UserName,
						Id = user.Id,
						CreationDate = user.CreationDate,
					};
				}

				// We found a user, but validation failed, so record this failed attempt
				RecordFailedLoginAttempt(context, user);
				return null;
			}
		}

		public IEnumerable<User> List()
		{
			using (var context = new RelayContext())
			{
				return context.Users.Select(u => new
					{
						u.Id,
						u.UserName,
						u.CreationDate,
						u.FailedLoginAttempts,
						u.LastFailedLoginAttempt,
					})
					.ToList()
					.Select(u => new User()
					{
						Id = u.Id,
						UserName = u.UserName,
						CreationDate = u.CreationDate,
						LockedUntil = LockedOutUntil(u.FailedLoginAttempts, u.LastFailedLoginAttempt),
					});
			}
		}

		public bool Delete(Guid id)
		{
			using (var context = new RelayContext())
			{
				var dbUser = new DbUser
				{
					Id = id,
				};

				context.Users.Attach(dbUser);
				context.Users.Remove(dbUser);

				return context.SaveChanges() == 1;
			}
		}

		public bool Update(Guid id, string password)
		{
			if ((id == Guid.Empty)
				|| (String.IsNullOrWhiteSpace(password)))
			{
				return false;
			}

			using (var context = new RelayContext())
			{
				var dbUser = context.Users.SingleOrDefault(u => u.Id == id);

				if (dbUser == null)
				{
					return false;
				}

				var passwordInformation = _passwordHash.CreatePasswordInformation(Encoding.UTF8.GetBytes(password));

				dbUser.Iterations = passwordInformation.Iterations;
				dbUser.Salt = passwordInformation.Salt;
				dbUser.Password = passwordInformation.Hash;

				context.Entry(dbUser).State = EntityState.Modified;

				return context.SaveChanges() == 1;
			}
		}

		public User Get(Guid id)
		{
			using (var context = new RelayContext())
			{
				var dbUser = context.Users.SingleOrDefault(u => u.Id == id);

				if (dbUser == null)
				{
					return null;
				}

				return new User()
				{
					CreationDate = dbUser.CreationDate,
					Id = dbUser.Id,
					UserName = dbUser.UserName,
				};
			}
		}

		public bool Any()
		{
			using (var context = new RelayContext())
			{
				return context.Users.Any();
			}
		}

		public bool IsUserNameAvailable(string userName)
		{
			using (var context = new RelayContext())
			{
				var user = context.Users.SingleOrDefault(u => u.UserName == userName);

				return user == null;
			}
		}

		private DateTime? LockedOutUntil(int? failedAttempts, DateTime? lastFailedAttempt)
		{
			if (!failedAttempts.HasValue)
				return null;

			if (failedAttempts < _configuration.MaxFailedLoginAttempts)
				return null;

			if (!lastFailedAttempt.HasValue)
				return null;

			var result = lastFailedAttempt + _configuration.FailedLoginLockoutPeriod;
			if (result < DateTime.UtcNow)
				return null;

			return result;
		}

		private bool IsUserLockedOut(DbUser user)
		{
			var lockedOutUntil = LockedOutUntil(user.FailedLoginAttempts, user.LastFailedLoginAttempt);
			if (!lockedOutUntil.HasValue)
				return false;

			_logger?.Information("User {UserName} is locked out until {LockoutEnd} due to {FailedLoginAttempts} failed login attempts (last try was at {LastFailedLoginAttempt})",
				user.UserName,
				lockedOutUntil,
				user.FailedLoginAttempts,
				user.LastFailedLoginAttempt
			);

			return true;
		}

		private void RecordFailedLoginAttempt(RelayContext ctx, DbUser user)
		{
			user.LastFailedLoginAttempt = DateTime.UtcNow;
			user.FailedLoginAttempts = user.FailedLoginAttempts.GetValueOrDefault() + 1;

			ctx.Entry(user).State = EntityState.Modified;
			ctx.SaveChanges();

			_logger?.Information("User {UserName} failed logging in for {FailedLoginAttempts} attempts",
				user.UserName,
				user.FailedLoginAttempts
			);
		}

		private void UnlockUser(RelayContext ctx, DbUser user)
		{
			user.LastFailedLoginAttempt = null;
			user.FailedLoginAttempts = null;

			ctx.Entry(user).State = EntityState.Modified;
			ctx.SaveChanges();

			_logger?.Information("Unlocking user account {UserName}", user.UserName);
		}
	}
}


text:
local out = io.open("../Data/3_0/Misc.lua", "w")

out:write('local data = ...\n')
local evasion = ""
local accuracy = ""
local life = ""
local allyLife = ""
local damage = ""
for i = 0, DefaultMonsterStats.maxRow do
	local stats = DefaultMonsterStats[i]
	evasion = evasion .. stats.Evasion .. ", "
	accuracy = accuracy .. stats.Accuracy .. ", "
	life = life .. stats.Life .. ", "
	allyLife = allyLife .. stats.AllyLife .. ", "
	damage = damage .. stats.Damage .. ", "
end
out:write('-- From DefaultMonsterStats.dat\n')
out:write('data.monsterEvasionTable = { '..evasion..'}\n')
out:write('data.monsterAccuracyTable = { '..accuracy..'}\n')
out:write('data.monsterLifeTable = { '..life..'}\n')
out:write('data.monsterAllyLifeTable = { '..allyLife..'}\n')
out:write('data.monsterDamageTable = { '..damage..'}\n')

local totemMult = ""
local keys = { }
for i = 0, SkillTotemVariations.maxRow do
	local var = SkillTotemVariations[i]
	if not keys[var.SkillTotemsKey] then
		keys[var.SkillTotemsKey] = true
		totemMult = totemMult .. "[" .. var.SkillTotemsKey .. "] = " .. MonsterVarieties[var.MonsterVarietiesKey].LifeMultiplier / 100 .. ", "
	end
end
out:write('-- From MonsterVarieties.dat combined with SkillTotemVariations.dat\n')
out:write('data.totemLifeMult = { '..totemMult..'}\n')

out:close()

print("Misc data exported.")


text:
#ifndef SORTDLG_H
#define SORTDLG_H

#include "console/screen.h"

class SortDialog : public Popup {
    int& mrSortType;
    int& mrSortDirection;
    int  mSortType;
    int  mSortDirection;
    void draw ();
    void drawFields ();
public:
    SortDialog (Screen& screen, int& sortType, int& sortDir);
    virtual ~SortDialog ();
    virtual int processEvent (const Event& event);
};

#endif


text:
require_relative '../../spec_helper'
require_relative 'fixtures/common'

describe "NoMethodError.new" do
  it "allows passing method args" do
    NoMethodError.new("msg", "name", ["args"]).args.should == ["args"]
  end

  it "does not require a name" do
    NoMethodError.new("msg").message.should == "msg"
  end

  it "accepts a :receiver keyword argument" do
    receiver = mock("receiver")

    error = NoMethodError.new("msg", :name, receiver: receiver)

    error.receiver.should == receiver
    error.name.should == :name
  end
end

describe "NoMethodError#args" do
  it "returns an empty array if the caller method had no arguments" do
    begin
      NoMethodErrorSpecs::NoMethodErrorB.new.foo
    rescue Exception => e
      e.args.should == []
    end
  end

  it "returns an array with the same elements as passed to the method" do
    begin
      a = NoMethodErrorSpecs::NoMethodErrorA.new
      NoMethodErrorSpecs::NoMethodErrorB.new.foo(1,a)
    rescue Exception => e
      e.args.should == [1,a]
      e.args[1].should equal a
    end
  end
end

describe "NoMethodError#message" do
  it "for an undefined method match /undefined method/" do
    begin
      NoMethodErrorSpecs::NoMethodErrorD.new.foo
    rescue Exception => e
      e.should be_kind_of(NoMethodError)
    end
  end

  it "for an protected method match /protected method/" do
    begin
      NoMethodErrorSpecs::NoMethodErrorC.new.a_protected_method
    rescue Exception => e
      e.should be_kind_of(NoMethodError)
    end
  end

  it "for private method match /private method/" do
    begin
      NoMethodErrorSpecs::NoMethodErrorC.new.a_private_method
    rescue Exception => e
      e.should be_kind_of(NoMethodError)
      e.message.lines[0].should =~ /private method `a_private_method' called for #<NoMethodErrorSpecs::NoMethodErrorC:0x[\h]+>/
    end
  end

  it "calls receiver.inspect only when calling Exception#message" do
    ScratchPad.record []
    test_class = Class.new do
      def inspect
        ScratchPad << :inspect_called
        "<inspect>"
      end
    end
    instance = test_class.new
    begin
      instance.bar
    rescue Exception => e
      e.name.should == :bar
      ScratchPad.recorded.should == []
      e.message.should =~ /undefined method.+\bbar\b/
      ScratchPad.recorded.should == [:inspect_called]
    end
  end

  it "fallbacks to a simpler representation of the receiver when receiver.inspect raises an exception" do
    test_class = Class.new do
      def inspect
        raise NoMethodErrorSpecs::InstanceException
      end
    end
    instance = test_class.new
    begin
      instance.bar
    rescue Exception => e
      e.name.should == :bar
      message = e.message
      message.should =~ /undefined method.+\bbar\b/
      message.should include test_class.inspect
    end
  end

  ruby_version_is "3.0" do
    it "uses #name to display the receiver if it is a class or a module" do
      klass = Class.new { def self.name; "MyClass"; end }
      begin
        klass.foo
      rescue NoMethodError => error
        error.message.lines.first.chomp.should == "undefined method `foo' for MyClass:Class"
      end

      mod = Module.new { def self.name; "MyModule"; end }
      begin
        mod.foo
      rescue NoMethodError => error
        error.message.lines.first.chomp.should == "undefined method `foo' for MyModule:Module"
      end
    end
  end
end

describe "NoMethodError#dup" do
  it "copies the name, arguments and receiver" do
    begin
      receiver = Object.new
      receiver.foo(:one, :two)
    rescue NoMethodError => nme
      no_method_error_dup = nme.dup
      no_method_error_dup.name.should == :foo
      no_method_error_dup.receiver.should == receiver
      no_method_error_dup.args.should == [:one, :two]
    end
  end
end


text:
package lang.celadon.old;

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

/**
 * Abstract class to be extended by classes that can be run as Celadon code and return one Token as a result. This makes
 * it different from IMorph because an IMorph can return zero or more tokens, but also because this stores parameter
 * names and a body as Token lists, as well as storing a copy of the Context at the time this ARun was declared.
 * Created by Tommy Ettinger on 1/9/2017.
 */
public abstract class ARun implements Serializable {
    private static final long serialVersionUID = 0;
    public Context context;
    public List<Token> names, body;
    public String title;
    protected final List<Token> bodyFixed;
    public ARun()
    {
        this(new Context(true));
    }
    public ARun(final Context context, final List<Token> tokens,
                final int nameStart, final int nameEnd, final int bodyStart, final int bodyEnd)
    {
        this(context, null, tokens, nameStart, nameEnd, bodyStart, bodyEnd);
    }
    public ARun(final Context context, final String title, final List<Token> tokens,
                final int nameStart, final int nameEnd, final int bodyStart, final int bodyEnd)
    {
        this.context = new Context(context);
        this.title = title;
        names = new ArrayList<>(tokens.subList(nameStart, nameEnd));
        body = new ArrayList<>(tokens.subList(bodyStart, bodyEnd));
        bodyFixed = new ArrayList<>(body);
    }
    public ARun(final Context context)
    {
        this(context, null);
    }
    public ARun(final Context context, final String title)
    {
        this.context = new Context(context);
        this.title = title;
        names = null;
        body = null;
        bodyFixed = null;
    }

    /**
     * Abstract method that gets a value from a defined ARun by assigning values to {@link #names} from the items in
     * {@code parameters} and running through {@link #body}, possibly starting other ARun instances.
     * @param parameters values to assign to names; must have size no less that the size of {@link #names}
     * @return a single returned Token; this can potentially be a Token that resolves to an IMorph and so yields more
     */
    public abstract Token run(List<Token> parameters);

    @Override
    public String toString()
    {
        if(title != null)
            return "{fn " + title + "}";
        if(names == null || bodyFixed == null) {
                return "{fn ~|/unknown name, non-native/|~)";
        }
        StringBuilder sb = new StringBuilder(128);
        sb.append("{fn [");
        if(!names.isEmpty()) {
            sb.append(names.get(0));
            for (int i = 1; i < names.size(); ++i) {
                sb.append(' ').append(names.get(i));
            }
        }
        sb.append(" ] ");
        if(!bodyFixed.isEmpty()) {
            sb.append(bodyFixed.get(0));
            for (int i = 1; i < bodyFixed.size(); ++i) {
                sb.append(' ').append(bodyFixed.get(i));
            }
        }
        sb.append('}');
        return sb.toString();

    }
}


text:
package integeruser.jgltut.tut05;

import integeruser.jgltut.Tutorial;
import integeruser.jgltut.framework.Framework;
import org.lwjgl.BufferUtils;

import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;

import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.glBindVertexArray;
import static org.lwjgl.opengl.GL30.glGenVertexArrays;

/**
 * Visit https://github.com/integeruser/jgltut for info and updates.
 * Original: https://bitbucket.org/alfonse/gltut/src/default/Tut%2005%20Objects%20in%20Depth/OverlapNoDepth.cpp
 * <p>
 * Part II. Positioning
 * Chapter 5. Objects in Depth
 */
public class OverlapNoDepth extends Tutorial {
    public static void main(String[] args) {
        Framework.CURRENT_TUTORIAL_DATAPATH = "/integeruser/jgltut/tut05/data/";
        new OverlapNoDepth().start(500, 500);
    }

    @Override
    protected void init() {
        initializeProgram();
        initializeVertexBuffer();
        initializeVertexArrayObjects();

        glEnable(GL_CULL_FACE);
        glCullFace(GL_BACK);
        glFrontFace(GL_CW);
    }

    @Override
    protected void display() {
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        glUseProgram(theProgram);

        glBindVertexArray(vaoObject1);
        glUniform3f(offsetUniform, 0.0f, 0.0f, 0.0f);
        glDrawElements(GL_TRIANGLES, indexData.length, GL_UNSIGNED_SHORT, 0);

        glBindVertexArray(vaoObject2);
        glUniform3f(offsetUniform, 0.0f, 0.0f, -1.0f);
        glDrawElements(GL_TRIANGLES, indexData.length, GL_UNSIGNED_SHORT, 0);

        glBindVertexArray(0);
        glUseProgram(0);
    }

    @Override
    protected void reshape(int w, int h) {
        perspectiveMatrix[0] = frustumScale * (h / (float) w);
        perspectiveMatrix[5] = frustumScale;

        FloatBuffer perspectiveMatrixBuffer = BufferUtils.createFloatBuffer(perspectiveMatrix.length);
        perspectiveMatrixBuffer.put(perspectiveMatrix);
        perspectiveMatrixBuffer.flip();

        glUseProgram(theProgram);
        glUniformMatrix4fv(perspectiveMatrixUnif, false, perspectiveMatrixBuffer);
        glUseProgram(0);

        glViewport(0, 0, w, h);
    }

    @Override
    protected void update() {
    }

    ////////////////////////////////
    private int theProgram;

    private int offsetUniform;
    private int perspectiveMatrixUnif;

    private float perspectiveMatrix[];
    private final float frustumScale = 1.0f;

    private void initializeProgram() {
        ArrayList<Integer> shaderList = new ArrayList<>();
        shaderList.add(Framework.loadShader(GL_VERTEX_SHADER, "Standard.vert"));
        shaderList.add(Framework.loadShader(GL_FRAGMENT_SHADER, "Standard.frag"));
        theProgram = Framework.createProgram(shaderList);

        offsetUniform = glGetUniformLocation(theProgram, "offset");
        perspectiveMatrixUnif = glGetUniformLocation(theProgram, "perspectiveMatrix");

        float zNear = 1.0f;
        float zFar = 3.0f;
        perspectiveMatrix = new float[16];
        perspectiveMatrix[0] = frustumScale;
        perspectiveMatrix[5] = frustumScale;
        perspectiveMatrix[10] = (zFar + zNear) / (zNear - zFar);
        perspectiveMatrix[14] = (2 * zFar * zNear) / (zNear - zFar);
        perspectiveMatrix[11] = -1.0f;

        FloatBuffer perspectiveMatrixBuffer = BufferUtils.createFloatBuffer(perspectiveMatrix.length);
        perspectiveMatrixBuffer.put(perspectiveMatrix);
        perspectiveMatrixBuffer.flip();

        glUseProgram(theProgram);
        glUniformMatrix4fv(perspectiveMatrixUnif, false, perspectiveMatrixBuffer);
        glUseProgram(0);
    }

    ////////////////////////////////
    private final float RIGHT_EXTENT = 0.8f;
    private final float LEFT_EXTENT = -RIGHT_EXTENT;
    private final float TOP_EXTENT = 0.20f;
    private final float MIDDLE_EXTENT = 0.0f;
    private final float BOTTOM_EXTENT = -TOP_EXTENT;
    private final float FRONT_EXTENT = -1.25f;
    private final float REAR_EXTENT = -1.75f;

    private final float vertexData[] = {
            // Object 1 positions
            LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT,
            LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
            RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
            RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT,

            LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
            LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
            RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
            RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,

            LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT,
            LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
            LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,

            RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT,
            RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
            RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,

            LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
            LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT,
            RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT,
            RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,

            // Object 2 positions
            TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
            MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT,
            MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT,
            TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT,

            BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
            MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT,
            MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT,
            BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT,

            TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
            MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT,
            BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT,

            TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT,
            MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT,
            BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT,

            BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
            TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
            TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT,
            BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT,

            // Object 1 colors
            0.75f, 0.75f, 1.0f, 1.0f,   // BLUE_COLOR
            0.75f, 0.75f, 1.0f, 1.0f,
            0.75f, 0.75f, 1.0f, 1.0f,
            0.75f, 0.75f, 1.0f, 1.0f,

            0.0f, 0.5f, 0.0f, 1.0f,     // GREEN_COLOR
            0.0f, 0.5f, 0.0f, 1.0f,
            0.0f, 0.5f, 0.0f, 1.0f,
            0.0f, 0.5f, 0.0f, 1.0f,

            1.0f, 0.0f, 0.0f, 1.0f,     // RED_COLOR
            1.0f, 0.0f, 0.0f, 1.0f,
            1.0f, 0.0f, 0.0f, 1.0f,

            0.8f, 0.8f, 0.8f, 1.0f,     // GREY_COLOR
            0.8f, 0.8f, 0.8f, 1.0f,
            0.8f, 0.8f, 0.8f, 1.0f,

            0.5f, 0.5f, 0.0f, 1.0f,     // BROWN_COLOR
            0.5f, 0.5f, 0.0f, 1.0f,
            0.5f, 0.5f, 0.0f, 1.0f,
            0.5f, 0.5f, 0.0f, 1.0f,

            // Object 2 colors
            1.0f, 0.0f, 0.0f, 1.0f,     // RED_COLOR
            1.0f, 0.0f, 0.0f, 1.0f,
            1.0f, 0.0f, 0.0f, 1.0f,
            1.0f, 0.0f, 0.0f, 1.0f,

            0.5f, 0.5f, 0.0f, 1.0f,     // BROWN_COLOR
            0.5f, 0.5f, 0.0f, 1.0f,
            0.5f, 0.5f, 0.0f, 1.0f,
            0.5f, 0.5f, 0.0f, 1.0f,

            0.0f, 0.5f, 0.0f, 1.0f,     // GREEN_COLOR
            0.0f, 0.5f, 0.0f, 1.0f,
            0.0f, 0.5f, 0.0f, 1.0f,

            0.75f, 0.75f, 1.0f, 1.0f,   // BLUE_COLOR
            0.75f, 0.75f, 1.0f, 1.0f,
            0.75f, 0.75f, 1.0f, 1.0f,

            0.8f, 0.8f, 0.8f, 1.0f,     // GREY_COLOR
            0.8f, 0.8f, 0.8f, 1.0f,
            0.8f, 0.8f, 0.8f, 1.0f,
            0.8f, 0.8f, 0.8f, 1.0f
    };

    private final short indexData[] = {
            0, 2, 1,
            3, 2, 0,

            4, 5, 6,
            6, 7, 4,

            8, 9, 10,
            11, 13, 12,

            14, 16, 15,
            17, 16, 14
    };

    private int vertexBufferObject;
    private int indexBufferObject;

    private int vaoObject1;
    private int vaoObject2;

    private void initializeVertexBuffer() {
        FloatBuffer vertexDataBuffer = BufferUtils.createFloatBuffer(vertexData.length);
        vertexDataBuffer.put(vertexData);
        vertexDataBuffer.flip();

        vertexBufferObject = glGenBuffers();
        glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject);
        glBufferData(GL_ARRAY_BUFFER, vertexDataBuffer, GL_STATIC_DRAW);
        glBindBuffer(GL_ARRAY_BUFFER, 0);

        ShortBuffer indexDataBuffer = BufferUtils.createShortBuffer(indexData.length);
        indexDataBuffer.put(indexData);
        indexDataBuffer.flip();

        indexBufferObject = glGenBuffers();
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferObject);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexDataBuffer, GL_STATIC_DRAW);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    }

    private void initializeVertexArrayObjects() {
        vaoObject1 = glGenVertexArrays();
        glBindVertexArray(vaoObject1);

        glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject);
        glEnableVertexAttribArray(0);
        glEnableVertexAttribArray(1);
        glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);
        final int numberOfVertices = 36;
        int colorDataOffset = Float.BYTES * 3 * numberOfVertices;
        glVertexAttribPointer(1, 4, GL_FLOAT, false, 0, colorDataOffset);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferObject);

        glBindVertexArray(0);

        vaoObject2 = glGenVertexArrays();
        glBindVertexArray(vaoObject2);

        // Use the same buffer object previously bound to GL_ARRAY_BUFFER.
        glEnableVertexAttribArray(0);
        glEnableVertexAttribArray(1);
        int posDataOffset = Float.BYTES * 3 * (numberOfVertices / 2);
        colorDataOffset += Float.BYTES * 4 * (numberOfVertices / 2);
        glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, posDataOffset);
        glVertexAttribPointer(1, 4, GL_FLOAT, false, 0, colorDataOffset);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferObject);

        glBindVertexArray(0);
    }
}


text:
package org.apache.nifi.processors.pgp;

import org.apache.nifi.pgp.service.api.PGPPublicKeyService;
import org.apache.nifi.pgp.util.PGPOperationUtils;
import org.apache.nifi.processors.pgp.attributes.CompressionAlgorithm;
import org.apache.nifi.processors.pgp.attributes.DecryptionStrategy;
import org.apache.nifi.processors.pgp.attributes.FileEncoding;
import org.apache.nifi.processors.pgp.attributes.SymmetricKeyAlgorithm;
import org.apache.nifi.processors.pgp.io.KeyIdentifierConverter;
import org.apache.nifi.reporting.InitializationException;
import org.apache.nifi.stream.io.StreamUtils;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.apache.nifi.pgp.util.PGPSecretKeyGenerator;

import org.bouncycastle.bcpg.ArmoredInputStream;
import org.bouncycastle.openpgp.PGPCompressedData;
import org.bouncycastle.openpgp.PGPEncryptedData;
import org.bouncycastle.openpgp.PGPEncryptedDataList;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPObjectFactory;
import org.bouncycastle.openpgp.PGPPBEEncryptedData;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory;
import org.bouncycastle.openpgp.operator.PBEDataDecryptorFactory;
import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor;
import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory;
import org.bouncycastle.openpgp.operator.bc.BcPBEDataDecryptorFactory;
import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider;
import org.bouncycastle.openpgp.operator.bc.BcPublicKeyDataDecryptorFactory;
import org.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.StreamSupport;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
public class EncryptContentPGPTest {
    private static final String PASSPHRASE = UUID.randomUUID().toString();

    private static final String DATA = String.class.getName();

    private static final byte[] DATA_BINARY = DATA.getBytes(StandardCharsets.UTF_8);

    private static final SymmetricKeyAlgorithm DEFAULT_SYMMETRIC_KEY_ALGORITHM = SymmetricKeyAlgorithm.valueOf(EncryptContentPGP.SYMMETRIC_KEY_ALGORITHM.getDefaultValue());

    private static final String SERVICE_ID = PGPPublicKeyService.class.getName();

    private static PGPSecretKey rsaSecretKey;

    private static PGPPrivateKey rsaPrivateKey;

    private static PGPPublicKey elGamalPublicKey;

    private static PGPPrivateKey elGamalPrivateKey;

    private TestRunner runner;

    @Mock
    private PGPPublicKeyService publicKeyService;

    @BeforeAll
    public static void setKeys() throws Exception {
        rsaSecretKey = PGPSecretKeyGenerator.generateRsaSecretKey(PASSPHRASE.toCharArray());
        final PGPSecretKeyRing dsaElGamalSecretKeyRing = PGPSecretKeyGenerator.generateDsaElGamalSecretKeyRing(PASSPHRASE.toCharArray());

        final PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder().build(PASSPHRASE.toCharArray());
        rsaPrivateKey = rsaSecretKey.extractPrivateKey(decryptor);
        for (final PGPSecretKey secretKey : dsaElGamalSecretKeyRing) {
            final PGPPublicKey publicKey = secretKey.getPublicKey();
            if (PGPPublicKey.ELGAMAL_ENCRYPT == publicKey.getAlgorithm()) {
                elGamalPrivateKey = secretKey.extractPrivateKey(decryptor);
                elGamalPublicKey = publicKey;
            }
        }
    }

    @BeforeEach
    public void setRunner() {
        runner = TestRunners.newTestRunner(new EncryptContentPGP());
    }

    @Test
    public void testMissingProperties() {
        runner.assertNotValid();
    }

    @Test
    public void testPublicKeyServiceMissingPublicKeySearch() throws InitializationException {
        when(publicKeyService.getIdentifier()).thenReturn(SERVICE_ID);
        runner.addControllerService(SERVICE_ID, publicKeyService);
        runner.enableControllerService(publicKeyService);
        runner.setProperty(EncryptContentPGP.PUBLIC_KEY_SERVICE, SERVICE_ID);

        runner.assertNotValid();
    }

    @Test
    public void testPublicKeySearchMissingPublicKeyService() {
        runner.setProperty(EncryptContentPGP.PUBLIC_KEY_SEARCH, String.class.getSimpleName());

        runner.assertNotValid();
    }

    @Test
    public void testSuccessPasswordBasedEncryptionDefaultProperties() throws IOException, PGPException {
        runner.setProperty(EncryptContentPGP.PASSPHRASE, PASSPHRASE);
        runner.enqueue(DATA);
        runner.run();

        assertSuccess(DEFAULT_SYMMETRIC_KEY_ALGORITHM, PASSPHRASE.toCharArray());
    }

    @Test
    public void testSuccessPasswordBasedEncryptionSymmetricKeyAlgorithms() throws IOException, PGPException {
        for (final SymmetricKeyAlgorithm symmetricKeyAlgorithm : SymmetricKeyAlgorithm.values()) {
            runner = TestRunners.newTestRunner(new EncryptContentPGP());
            runner.setProperty(EncryptContentPGP.PASSPHRASE, PASSPHRASE);
            runner.setProperty(EncryptContentPGP.SYMMETRIC_KEY_ALGORITHM, symmetricKeyAlgorithm.toString());
            runner.enqueue(DATA);
            runner.run();
            assertSuccess(symmetricKeyAlgorithm, PASSPHRASE.toCharArray());
        }
    }

    @Test
    public void testSuccessPasswordBasedEncryptionCompressionAlgorithms() throws IOException, PGPException {
        for (final CompressionAlgorithm compressionAlgorithm : CompressionAlgorithm.values()) {
            runner = TestRunners.newTestRunner(new EncryptContentPGP());
            runner.setProperty(EncryptContentPGP.PASSPHRASE, PASSPHRASE);
            runner.setProperty(EncryptContentPGP.COMPRESSION_ALGORITHM, compressionAlgorithm.toString());
            runner.enqueue(DATA);
            runner.run();
            assertSuccess(DEFAULT_SYMMETRIC_KEY_ALGORITHM, PASSPHRASE.toCharArray());
        }
    }

    @Test
    public void testSuccessPasswordBasedEncryptionFileEncodingAscii() throws IOException, PGPException {
        runner.setProperty(EncryptContentPGP.PASSPHRASE, PASSPHRASE);
        runner.setProperty(EncryptContentPGP.FILE_ENCODING, FileEncoding.ASCII.toString());
        runner.enqueue(DATA);
        runner.run();
        assertSuccess(DEFAULT_SYMMETRIC_KEY_ALGORITHM, PASSPHRASE.toCharArray());
    }

    @Test
    public void testSuccessPublicKeyEncryptionRsaPublicKey() throws IOException, InitializationException, PGPException {
        final PGPPublicKey publicKey = rsaSecretKey.getPublicKey();
        setPublicKeyService(publicKey);
        final String publicKeyIdSearch = KeyIdentifierConverter.format(publicKey.getKeyID());
        when(publicKeyService.findPublicKey(eq(publicKeyIdSearch))).thenReturn(Optional.of(publicKey));

        runner.enqueue(DATA);
        runner.run();
        assertSuccess(rsaPrivateKey, DecryptionStrategy.DECRYPTED, DATA_BINARY);
    }

    @Test
    public void testSuccessPublicKeyEncryptionRsaPublicKeySignedDataPackaged() throws IOException, InitializationException, PGPException {
        final PGPPublicKey publicKey = rsaSecretKey.getPublicKey();
        setPublicKeyService(publicKey);
        final String publicKeyIdSearch = KeyIdentifierConverter.format(publicKey.getKeyID());
        when(publicKeyService.findPublicKey(eq(publicKeyIdSearch))).thenReturn(Optional.of(publicKey));

        final byte[] contents = DATA.getBytes(StandardCharsets.UTF_8);
        final byte[] signedData = PGPOperationUtils.getOnePassSignedLiteralData(contents, rsaPrivateKey);

        runner.enqueue(signedData);
        runner.run();
        assertSuccess(rsaPrivateKey, DecryptionStrategy.PACKAGED, signedData);
    }

    @Test
    public void testSuccessPasswordBasedAndPublicKeyEncryptionRsaPublicKey() throws IOException, InitializationException, PGPException {
        final PGPPublicKey publicKey = rsaSecretKey.getPublicKey();
        setPublicKeyService(publicKey);
        final String publicKeyIdSearch = KeyIdentifierConverter.format(publicKey.getKeyID());
        when(publicKeyService.findPublicKey(eq(publicKeyIdSearch))).thenReturn(Optional.of(publicKey));

        runner.setProperty(EncryptContentPGP.PASSPHRASE, PASSPHRASE);

        runner.enqueue(DATA);
        runner.run();

        assertSuccess(rsaPrivateKey, DecryptionStrategy.DECRYPTED, DATA_BINARY);
        assertSuccess(DEFAULT_SYMMETRIC_KEY_ALGORITHM, PASSPHRASE.toCharArray());
    }

    @Test
    public void testSuccessPublicKeyEncryptionElGamalPublicKey() throws IOException, InitializationException, PGPException {
        setPublicKeyService(elGamalPublicKey);
        final String publicKeyIdSearch = KeyIdentifierConverter.format(elGamalPublicKey.getKeyID());
        when(publicKeyService.findPublicKey(eq(publicKeyIdSearch))).thenReturn(Optional.of(elGamalPublicKey));

        runner.enqueue(DATA);
        runner.run();
        assertSuccess(elGamalPrivateKey, DecryptionStrategy.DECRYPTED, DATA_BINARY);
    }

    @Test
    public void testFailurePublicKeyEncryptionKeyNotFound() throws InitializationException {
        final PGPPublicKey publicKey = rsaSecretKey.getPublicKey();
        setPublicKeyService(publicKey);

        final String publicKeyIdNotFound = KeyIdentifierConverter.format(Long.MAX_VALUE);
        runner.setProperty(EncryptContentPGP.PUBLIC_KEY_SEARCH, publicKeyIdNotFound);

        runner.enqueue(DATA);
        runner.run();
        runner.assertAllFlowFilesTransferred(EncryptContentPGP.FAILURE);
    }

    private void setPublicKeyService(final PGPPublicKey publicKey) throws InitializationException {
        when(publicKeyService.getIdentifier()).thenReturn(SERVICE_ID);
        runner.addControllerService(SERVICE_ID, publicKeyService);
        runner.enableControllerService(publicKeyService);

        runner.setProperty(EncryptContentPGP.PUBLIC_KEY_SERVICE, SERVICE_ID);
        final String publicKeyId = KeyIdentifierConverter.format(publicKey.getKeyID());
        runner.setProperty(EncryptContentPGP.PUBLIC_KEY_SEARCH, publicKeyId);
    }

    private void assertSuccess(final PGPPrivateKey privateKey, final DecryptionStrategy decryptionStrategy, final byte[] expected) throws IOException, PGPException {
        runner.assertAllFlowFilesTransferred(EncryptContentPGP.SUCCESS);
        final MockFlowFile flowFile = runner.getFlowFilesForRelationship(EncryptContentPGP.SUCCESS).iterator().next();
        assertAttributesFound(DEFAULT_SYMMETRIC_KEY_ALGORITHM, flowFile);

        final PGPEncryptedDataList encryptedDataList = getEncryptedDataList(flowFile);
        final Optional<PGPEncryptedData> encryptedData = StreamSupport.stream(encryptedDataList.spliterator(), false)
                .filter(pgpEncryptedData -> pgpEncryptedData instanceof PGPPublicKeyEncryptedData)
                .findFirst();
        assertTrue(encryptedData.isPresent(), "Public Key Encrypted Data not found");

        final PGPPublicKeyEncryptedData publicKeyEncryptedData = (PGPPublicKeyEncryptedData) encryptedData.get();
        final byte[] decryptedData = getDecryptedData(publicKeyEncryptedData, privateKey, decryptionStrategy);
        assertArrayEquals(expected, decryptedData);
    }

    private void assertSuccess(final SymmetricKeyAlgorithm symmetricKeyAlgorithm, final char[] passphrase) throws IOException, PGPException {
        runner.assertAllFlowFilesTransferred(EncryptContentPGP.SUCCESS);
        final MockFlowFile flowFile = runner.getFlowFilesForRelationship(EncryptContentPGP.SUCCESS).iterator().next();
        assertAttributesFound(symmetricKeyAlgorithm, flowFile);

        final PGPEncryptedDataList encryptedDataList = getEncryptedDataList(flowFile);
        final Optional<PGPEncryptedData> encryptedData = StreamSupport.stream(encryptedDataList.spliterator(), false)
                .filter(pgpEncryptedData -> pgpEncryptedData instanceof PGPPBEEncryptedData)
                .findFirst();
        assertTrue(encryptedData.isPresent(), "Password Based Encrypted Data not found");

        final PGPPBEEncryptedData passwordBasedEncryptedData = (PGPPBEEncryptedData) encryptedData.get();
        final byte[] decryptedData = getDecryptedData(passwordBasedEncryptedData, passphrase);
        assertArrayEquals(DATA_BINARY, decryptedData);
    }

    private void assertAttributesFound(final SymmetricKeyAlgorithm symmetricKeyAlgorithm, final MockFlowFile flowFile) {
        flowFile.assertAttributeEquals(PGPAttributeKey.SYMMETRIC_KEY_ALGORITHM, symmetricKeyAlgorithm.toString());
        flowFile.assertAttributeEquals(PGPAttributeKey.SYMMETRIC_KEY_ALGORITHM_BLOCK_CIPHER, symmetricKeyAlgorithm.getBlockCipher().toString());
        flowFile.assertAttributeEquals(PGPAttributeKey.SYMMETRIC_KEY_ALGORITHM_KEY_SIZE, Integer.toString(symmetricKeyAlgorithm.getKeySize()));
        flowFile.assertAttributeEquals(PGPAttributeKey.SYMMETRIC_KEY_ALGORITHM_ID, Integer.toString(symmetricKeyAlgorithm.getId()));
        flowFile.assertAttributeExists(PGPAttributeKey.FILE_ENCODING);
        flowFile.assertAttributeExists(PGPAttributeKey.COMPRESS_ALGORITHM);
        flowFile.assertAttributeExists(PGPAttributeKey.COMPRESS_ALGORITHM_ID);
    }

    private PGPEncryptedDataList getEncryptedDataList(final MockFlowFile flowFile) throws IOException {
        final FileEncoding fileEncoding = FileEncoding.valueOf(flowFile.getAttribute(PGPAttributeKey.FILE_ENCODING));
        InputStream contentStream = flowFile.getContentStream();
        if (FileEncoding.ASCII.equals(fileEncoding)) {
            contentStream = new ArmoredInputStream(contentStream);
        }

        final PGPObjectFactory objectFactory = new JcaPGPObjectFactory(contentStream);
        final Object firstObject = objectFactory.nextObject();
        assertEquals(PGPEncryptedDataList.class, firstObject.getClass());

        return (PGPEncryptedDataList) firstObject;
    }

    private byte[] getDecryptedData(final PGPPBEEncryptedData passwordBasedEncryptedData, final char[] passphrase) throws PGPException, IOException {
        final PBEDataDecryptorFactory decryptorFactory = new BcPBEDataDecryptorFactory(passphrase, new BcPGPDigestCalculatorProvider());
        final InputStream decryptedDataStream = passwordBasedEncryptedData.getDataStream(decryptorFactory);
        return getDecryptedData(decryptedDataStream, DecryptionStrategy.DECRYPTED);
    }

    private byte[] getDecryptedData(final PGPPublicKeyEncryptedData publicKeyEncryptedData,
                                    final PGPPrivateKey privateKey,
                                    final DecryptionStrategy decryptionStrategy) throws PGPException, IOException {
        final PublicKeyDataDecryptorFactory decryptorFactory = new BcPublicKeyDataDecryptorFactory(privateKey);
        final InputStream decryptedDataStream = publicKeyEncryptedData.getDataStream(decryptorFactory);
        return getDecryptedData(decryptedDataStream, decryptionStrategy);
    }

    private byte[] getDecryptedData(final InputStream decryptedDataStream, final DecryptionStrategy decryptionStrategy) throws PGPException, IOException {
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        if (DecryptionStrategy.PACKAGED == decryptionStrategy) {
            StreamUtils.copy(decryptedDataStream, outputStream);
        } else {
            final PGPObjectFactory objectFactory = new JcaPGPObjectFactory(decryptedDataStream);
            final PGPLiteralData literalData = getLiteralData(objectFactory);
            StreamUtils.copy(literalData.getDataStream(), outputStream);
        }
        return outputStream.toByteArray();
    }

    private PGPLiteralData getLiteralData(final PGPObjectFactory objectFactory) throws PGPException {
        PGPLiteralData literalData = null;
        for (final Object object : objectFactory) {
            if (object instanceof PGPLiteralData) {
                literalData = (PGPLiteralData) object;
                break;
            } else if (object instanceof PGPCompressedData) {
                final PGPCompressedData compressedData = (PGPCompressedData) object;
                final PGPObjectFactory compressedObjectFactory = new JcaPGPObjectFactory(compressedData.getDataStream());
                literalData = getLiteralData(compressedObjectFactory);
                break;
            }
        }
        return literalData;
    }
}


text:
var rtb = require('rtb');

//only create a Google endpoint
var server = rtb.google.createServer(function (req, res) {
    //Process req, decide on bids / creative
    //Call res.end() when done
}).listen();

console.log('RTB.js server running at http://127.0.0.1/');

server.endpoints.map(function(endpoint) {
    console.log(endpoint.name + " listening at " + endpoint.url);
});


text:
package org.elasticsearch.test.integration.search.scriptfilter;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.test.integration.AbstractNodesTests;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.elasticsearch.client.AdminRequests.refreshRequest;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.FilterBuilders.scriptFilter;
import static org.elasticsearch.index.query.QueryBuilders.filteredQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

/**
 *
 */
@Test
public class ScriptFilterSearchTests extends AbstractNodesTests {

    private Client client;

    @BeforeMethod
    public void createNodes() throws Exception {
        Settings nodeSettings = ImmutableSettings.settingsBuilder()
                .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
                .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0)
                .build();
        startNode("server1", nodeSettings);
        client = getClient();
    }

    @AfterMethod
    public void closeNodes() {
        client.close();
        closeAllNodes();
    }

    protected Client getClient() {
        return client("server1");
    }

    @Test
    public void testCustomScriptBoost() throws Exception {
        client.admin().indices().prepareCreate("test").execute().actionGet();
        client.prepareIndex("test", "type1", "1")
                .setSource(jsonBuilder().startObject().field("test", "value beck").field("num1", 1.0f).endObject())
                .execute().actionGet();
        client.admin().indices().prepareFlush().execute().actionGet();
        client.prepareIndex("test", "type1", "2")
                .setSource(jsonBuilder().startObject().field("test", "value beck").field("num1", 2.0f).endObject())
                .execute().actionGet();
        client.admin().indices().prepareFlush().execute().actionGet();
        client.prepareIndex("test", "type1", "3")
                .setSource(jsonBuilder().startObject().field("test", "value beck").field("num1", 3.0f).endObject())
                .execute().actionGet();
        client.admin().indices().refresh(refreshRequest()).actionGet();

        logger.info("running doc['num1'].value > 1");
        SearchResponse response = client.prepareSearch()
                .setQuery(filteredQuery(matchAllQuery(), scriptFilter("doc['num1'].value > 1")))
                .addSort("num1", SortOrder.ASC)
                .addScriptField("sNum1", "doc['num1'].value")
                .execute().actionGet();

        assertThat(response.hits().totalHits(), equalTo(2l));
        assertThat(response.hits().getAt(0).id(), equalTo("2"));
        assertThat((Double) response.hits().getAt(0).fields().get("sNum1").values().get(0), equalTo(2.0));
        assertThat(response.hits().getAt(1).id(), equalTo("3"));
        assertThat((Double) response.hits().getAt(1).fields().get("sNum1").values().get(0), equalTo(3.0));

        logger.info("running doc['num1'].value > param1");
        response = client.prepareSearch()
                .setQuery(filteredQuery(matchAllQuery(), scriptFilter("doc['num1'].value > param1").addParam("param1", 2)))
                .addSort("num1", SortOrder.ASC)
                .addScriptField("sNum1", "doc['num1'].value")
                .execute().actionGet();

        assertThat(response.hits().totalHits(), equalTo(1l));
        assertThat(response.hits().getAt(0).id(), equalTo("3"));
        assertThat((Double) response.hits().getAt(0).fields().get("sNum1").values().get(0), equalTo(3.0));

        logger.info("running doc['num1'].value > param1");
        response = client.prepareSearch()
                .setQuery(filteredQuery(matchAllQuery(), scriptFilter("doc['num1'].value > param1").addParam("param1", -1)))
                .addSort("num1", SortOrder.ASC)
                .addScriptField("sNum1", "doc['num1'].value")
                .execute().actionGet();

        assertThat(response.hits().totalHits(), equalTo(3l));
        assertThat(response.hits().getAt(0).id(), equalTo("1"));
        assertThat((Double) response.hits().getAt(0).fields().get("sNum1").values().get(0), equalTo(1.0));
        assertThat(response.hits().getAt(1).id(), equalTo("2"));
        assertThat((Double) response.hits().getAt(1).fields().get("sNum1").values().get(0), equalTo(2.0));
        assertThat(response.hits().getAt(2).id(), equalTo("3"));
        assertThat((Double) response.hits().getAt(2).fields().get("sNum1").values().get(0), equalTo(3.0));
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>AADC: C:/Development/3510_AADC_ADTF/trunk/src/adtfBase/AADC_ADTF_BaseFilters/src/calibration/AADC_SignalCalibrationExt/SensorCalibration.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AADC

Main Page

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

 All Classes Namespaces Files Functions Variables Enumerations

SensorCalibration.h

    1

   24 #ifndef _SENSORCALIBRATION_H_

   25 #define _SENSORCALIBRATION_H_

   26

   27 #include "stdafx.h"

   28

   29 #define OID_ADTF_SENSOR_CALIBRATION "adtf.aadc.sensorCalibration"

   30

   34 class SensorCalibration : public adtf::cFilter

   35 {

   36     ADTF_DECLARE_FILTER_VERSION(OID_ADTF_SENSOR_CALIBRATION, "AADC Calibration Filter Extended", OBJCAT_DataFilter, "Sensor Calibration Filter Extended", 1, 0, 0, "Beta Version");

   37

   38         cInputPin m_oInput;             //input pin for the raw value

   39         cOutputPin m_oOutput;           //output pin for the calibrated value

   40

   41     public:

   42         SensorCalibration(const tChar* __info);

   43         virtual ~SensorCalibration();

   44

   45     protected: // overwrites cFilter

   46         tResult Init(tInitStage eStage, __exception = NULL);

   47         tResult Start(__exception = NULL);

   48         tResult Stop(__exception = NULL);

   49         tResult Shutdown(tInitStage eStage, __exception = NULL);

   50

   51         tResult OnPinEvent(IPin* pSource, tInt nEventCode, tInt nParam1, tInt nParam2, IMediaSample* pMediaSample);

   52

   53     private:

   55         tResult CreateInputPins(__exception = NULL);

   57         tResult CreateOutputPins(__exception = NULL);

   59         tResult LoadConfigurationData();

   61         tResult CheckConfigurationData();

   62

   66         tFloat32 getLinearInterpolatedValue(tFloat32 inputValue);

   67

   71         tFloat32 getCubicSplineInterpolatedValue(tFloat32 inputValue);

   72

   74         cFilename m_fileConfig;

   76         vector<tFloat32> m_yValues;

   78         vector<tFloat32> m_xValues;

   80         Cubic *m_cubicInterpolation;

   81

   83         tBool m_bDebugModeEnabled;

   84

   86         cObjectPtr<IMediaTypeDescription> m_pCoderDescSignal;

   87

   88 };

   89

   90

   91

   92 //*************************************************************************************************

   93

   94 #endif // _SENSORCALIBRATION_H_

   95

SensorCalibration

Definition: SensorCalibration.h:34

Cubic

Interpolates a given set of points using cubic spline fitting.

Definition: cCubic.h:24

SensorCalibration::SensorCalibration

SensorCalibration(const tChar *__info)

Definition: SensorCalibration.cpp:27

src

adtfBase

AADC_ADTF_BaseFilters

src

calibration

AADC_SignalCalibrationExt

SensorCalibration.h

Generated on Tue Sep 16 2014 14:13:25 for AADC by

     1.8.8


text:
isExistApp=`ps -eaf |grep cp-users-service |grep -v grep| awk '{ print $2; }'`
if [[ -n $isExistApp ]]; then
    service cp-users-service stop
fi

service cp-users-service start


text:
<?php
namespace Grav\Plugin;

use Grav\Common\Plugin;
use Grav\Common\Page\Page;
use Grav\Common\Page\Pages;
use Grav\Common\Grav;
use Grav\Common\Uri;
use Grav\Common\Twig;
use Grav\Plugin\Form;
use RocketTheme\Toolbox\Event\Event;
use RocketTheme\Toolbox\File\File;
use Symfony\Component\Yaml\Yaml;

class FormPlugin extends Plugin
{

    /**
     * @var bool
     */
    protected $active = false;

    /**
     * @var Form
     */
    protected $form;

    /**
     * @return array
     */
    public static function getSubscribedEvents()
    {
        return [
            'onPageInitialized' => ['onPageInitialized', 0],
            'onTwigTemplatePaths' => ['onTwigTemplatePaths', 0],
            'onTwigSiteVariables' => ['onTwigSiteVariables', 0],
            'onFormProcessed' => ['onFormProcessed', 0]
        ];
    }

    /**
     * Initialize form if the page has one. Also catches form processing if user posts the form.
     */
    public function onPageInitialized()
    {
        /** @var Page $page */
        $page = $this->grav['page'];
        if (!$page) {
            return;
        }

        $header = $page->header();
        if (isset($header->form) && is_array($header->form)) {
            $this->active = true;

            // Create form.
            require_once __DIR__ . '/classes/form.php';
            $this->form = new Form($page);

            // Handle posting if needed.
            if (!empty($_POST)) {
                $this->form->post();
            }
        }
    }

        /**
     * Add current directory to twig lookup paths.
     */
    public function onTwigTemplatePaths()
    {
        $this->grav['twig']->twig_paths[] = __DIR__ . '/templates';
    }

    /**
     * Make form accessible from twig.
     */
    public function onTwigSiteVariables()
    {
        if (!$this->active) {
            return;
        }

        $this->grav['twig']->twig_vars['form'] = $this->form;
    }

    /**
     * Handle form processing instructions.
     *
     * @param Event $event
     */
    public function onFormProcessed(Event $event)
    {
        $form = $event['form'];
        $action = $event['action'];
        $params = $event['params'];

        if (!$this->active) {
            return;
        }

        if (!$this->validate($form)) {
            /** @var Language $l */
            $l = $this->grav['language'];
            $this->form->message = $l->translate('FORM_PLUGIN.NOT_VALIDATED');
            $uri = $this->grav['uri'];
            $route = $uri->route();

            /** @var Twig $twig */
            $twig = $this->grav['twig'];
            $twig->twig_vars['form'] = $form;

            /** @var Pages $pages */
            $pages = $this->grav['pages'];
            $page = $pages->dispatch($route, true);
            unset($this->grav['page']);
            $this->grav['page'] = $page;

            return;
        }

        $this->process($form);

        switch ($action) {
            case 'captcha':
                // Validate the captcha
                $query = http_build_query([
                    'secret' => $params['recatpcha_secret'],
                    'response' => $this->form->value('g-recaptcha-response')
                ]);
                $url = 'https://www.google.com/recaptcha/api/siteverify?'.$query;
                $response = json_decode(file_get_contents($url), true);

                if (!isset($response['success']) || $response['success'] !== true) {
                    throw new \RuntimeException('Error validating the Captcha');
                }
                break;
            case 'message':
                $this->form->message = (string) $params;
                break;
            case 'redirect':
                $this->grav->redirect((string) $params);
                break;
            case 'reset':
                if (in_array($params, array(true, 1, '1', 'yes', 'on', 'true'), true)) {
                    $this->form->reset();
                }
                break;
            case 'display':
                $route = (string) $params;
                if (!$route || $route[0] != '/') {
                    /** @var Uri $uri */
                    $uri = $this->grav['uri'];
                    $route = $uri->route() . ($route ? '/' . $route : '');
                }

                /** @var Twig $twig */
                $twig = $this->grav['twig'];
                $twig->twig_vars['form'] = $form;

                /** @var Pages $pages */
                $pages = $this->grav['pages'];
                $page = $pages->dispatch($route, true);
                unset($this->grav['page']);
                $this->grav['page'] = $page;
                break;
            case 'save':
                $prefix = !empty($params['fileprefix']) ? $params['fileprefix'] : '';
                $format = !empty($params['dateformat']) ? $params['dateformat'] : 'Ymd-His-u';
                $ext = !empty($params['extension']) ? '.' . trim($params['extension'], '.') : '.txt';
                $filename = !empty($params['filename']) ? $params['filename'] : '';
                $operation = !empty($params['operation']) ? $params['operation'] : 'create';

                if (!$filename) {
                    $filename = $prefix . $this->udate($format) . $ext;
                }

                /** @var Twig $twig */
                $twig = $this->grav['twig'];
                $vars = array(
                    'form' => $this->form
                );

                $fullFileName = DATA_DIR . $this->form->name . '/' . $filename;

                $file = File::instance($fullFileName);

                if ($operation == 'create') {
                    $body = $twig->processString(
                        !empty($params['body']) ? $params['body'] : '{% include "forms/data.txt.twig" %}',
                        $vars
                    );
                    $file->save($body);
                } elseif ($operation == 'add') {
                    $vars = $vars['form']->value();

                    foreach ($form->fields as $field) {
                        if (isset($field['process']) && isset($field['process']['ignore']) && $field['process']['ignore']) {
                            unset($vars[$field['name']]);
                        }
                    }

                    if (file_exists($fullFileName)) {
                        $data = Yaml::parse($file->content());
                        if (count($data) > 0) {
                            array_unshift($data, $vars);
                        } else {
                            $data[] = $vars;
                        }
                    } else {
                        $data[] = $vars;
                    }

                    $file->save(Yaml::dump($data));
                }
                break;
        }
    }

    /**
     * Validate a form
     *
     * @param Form $form
     * @return bool
     */
    protected function validate($form) {
        foreach ($form->fields as $field) {
            if (isset($field['validate']) && isset($field['validate']['required']) && $field['validate']['required']) {
                if (!$form->value($field['name'])) {
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * Process a form
     *
     * Currently available processing tasks:
     *
     * - fillWithCurrentDateTime
     *
     * @param Form $form
     * @return bool
     */
    protected function process($form) {
        foreach ($form->fields as $field) {
            if (isset($field['process'])) {
                if (isset($field['process']['fillWithCurrentDateTime']) && $field['process']['fillWithCurrentDateTime']) {
                    $form->setValue($field['name'], gmdate('D, d M Y H:i:s', time()));
                }
            }
        }
    }

    /**
     * Create unix timestamp for storing the data into the filesystem.
     *
     * @param string $format
     * @param int $utimestamp
     * @return string
     */
    private function udate($format = 'u', $utimestamp = null)
    {
        if (is_null($utimestamp)) {
            $utimestamp = microtime(true);
        }

        $timestamp = floor($utimestamp);
        $milliseconds = round(($utimestamp - $timestamp) * 1000000);

        return date(preg_replace('`(?<!\\\\)u`', \sprintf('%06d', $milliseconds), $format), $timestamp);
    }
}


text:
from __future__ import unicode_literals

from django.db import models

# Create your models here.
from Ventanilla.models import CatalogoTipoAlumno
from Ventanilla.models import CatalogoTipoDocumento
from Ventanilla.models import CatalogoEstadoSolicitud
from Ventanilla.models import TablaAlumno
from Ventanilla.models import TablaSolicitud


text: history.pushState({ the: 'state' }, '/home', { the: 'query value' });


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('wedding', '0002_invitation_last_viewed'),
    ]

    operations = [
        migrations.AddField(
            model_name='invitation',
            name='check_spelling',
            field=models.BooleanField(default=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='invitation',
            name='mail_invitation',
            field=models.BooleanField(default=False),
            preserve_default=True,
        ),
    ]


text:
jCarouselLite
=============

A fork of Ganeshji Marwaha's jCarouselLite.


text:
define(['ash', 'game/constants/WorldConstants', 'worldcreator/WorldCreatorConstants', 'worldcreator/WorldCreatorLogger', 'game/vos/ResourcesVO', 'game/vos/EnvironmentalHazardsVO'],
function (Ash, WorldConstants, WorldCreatorConstants, WorldCreatorLogger, ResourcesVO, EnvironmentalHazardsVO) {

	var SectorVO = Ash.Class.extend({

		constructor: function (position, isCampableLevel, notCampableReason) {
			this.id = Math.floor(Math.random() * 100000);
			this.position = position;
			this.level = position.level;
			this.campableLevel = isCampableLevel;
			this.notCampableReason = notCampableReason;

			this.isCamp = false;
			this.isPassageUp = false;
			this.isPassageDown = false;

			this.requiredResources = new ResourcesVO();
			this.criticalPaths = [];
			this.criticalPathTypes = [];
			this.criticalPathIndices = [];
			this.locales = [];
			this.movementBlockers = {};
			this.passageUpType = null;
			this.passageDownType = null;
			this.sunlit = false;
			this.hazards = new EnvironmentalHazardsVO();
			this.hasSpring = false;
			this.hasTradeConnectorSpot = false;
			this.scavengeDifficulty = 5;
			this.resourcesScavengable = new ResourcesVO();
			this.resourcesCollectable = new ResourcesVO();
			this.itemsScavengeable = [];
			this.numLocaleEnemies = {};
			this.possibleEnemies = [];
			this.stashes = [];
			this.waymarks = [];

			this.distanceToCamp = -1;
		},

		isOnCriticalPath: function (type) {
			return this.criticalPathTypes.indexOf(type) >= 0;
		},

		isOnEarlyCriticalPath: function () {
			if (this.criticalPathTypes.indexOf(WorldCreatorConstants.CRITICAL_PATH_TYPE_CAMP_TO_POI_1) >= 0) return true;
			if (this.criticalPathTypes.indexOf(WorldCreatorConstants.CRITICAL_PATH_TYPE_PASSAGE_TO_CAMP) >= 0) return true;
			if (this.criticalPathTypes.indexOf(WorldCreatorConstants.CRITICAL_PATH_TYPE_PASSAGE_TO_PASSAGE) >= 0) return true;
			return false;
		},

		isOnPassageCriticalPath: function () {
			if (this.criticalPathTypes.indexOf(WorldCreatorConstants.CRITICAL_PATH_TYPE_PASSAGE_TO_CAMP) >= 0) return true;
			if (this.criticalPathTypes.indexOf(WorldCreatorConstants.CRITICAL_PATH_TYPE_CAMP_TO_PASSAGE) >= 0) return true;
			if (this.criticalPathTypes.indexOf(WorldCreatorConstants.CRITICAL_PATH_TYPE_PASSAGE_TO_PASSAGE) >= 0) return true;
			return false;
		},

		updateCriticalPath: function () {
			this.criticalPath = "-";
			for (let i = 0; i < this.criticalPathTypes.length; i++) {
				if (this.getCriticalPathPriority(this.criticalPathTypes[i] < this.getCriticalPathPriority(this.criticalPath))) {
					var split = this.criticalPathTypes[i].split("_");
					this.criticalPath = split[split.length - 1][0];
				}
			}
		},

		addToCriticalPath: function (path) {
			if (this.criticalPaths.indexOf(path) >= 0) return;
			let index = path.length;
			this.criticalPaths.push(path);
			this.criticalPathTypes.push(path.type);
			this.criticalPathIndices.push(index);
			path.length++;
			this.updateCriticalPath();
		},

		addBlocker: function (direction, blockerType, canOverride) {
			var existingType = this.movementBlockers[direction];
			if (existingType === blockerType) return;
			if (existingType) {
				WorldCreatorLogger.w("movement blocker already exists:" + this.movementBlockers[direction] + " (trying to add: " + blockerType + ")");
				return;
			}
			this.movementBlockers[direction] = blockerType;
		},

		getBlockerByDirection: function (direction) {
			return this.movementBlockers[direction];
		},

		hasWater: function () {
			return this.hasSpring || this.resourcesScavengable.getResource(resourceNames.water) > 0 || this.resourcesCollectable.getResource(resourceNames.water) > 0;
		},

		getCriticalPathPriority: function (pathType) {
			if (!pathType) return 99;
			switch (pathType) {
				case this.CRITICAL_PATH_TYPE_CAMP_TO_POI_1: return 3;
				case this.CRITICAL_PATH_TYPE_CAMP_TO_POI_2: return 4;
				case this.CRITICAL_PATH_TYPE_CAMP_TO_PASSAGE: return 1;
				case this.CRITICAL_PATH_TYPE_PASSAGE_TO_PASSAGE: return 10;
				default: return 50;
			}
		},

		getZoneC: function () {
			switch (this.zone) {
				case WorldConstants.ZONE_ENTRANCE:
					return "e";
				case WorldConstants.ZONE_PASSAGE_TO_CAMP:
					return "p";
				case WorldConstants.ZONE_POI_1:
					return "1";
				case WorldConstants.ZONE_POI_2:
					return "2";
				case WorldConstants.ZONE_CAMP_TO_PASSAGE:
					return "b";
				case WorldConstants.ZONE_EXTRA_CAMPABLE:
					return "x";
				case WorldConstants.ZONE_POI_TEMP:
					return "t";
				case WorldConstants.ZONE_PASSAGE_TO_PASSAGE:
					return "i";
				case WorldConstants.ZONE_EXTRA_UNCAMPABLE:
					return "x";
				default:
					WorldCreatorLogger.w("no debug char defined for zone " + this.zone);
					return WorldCreatorConstants.getZoneOrdinal(this.zone);
			}
		},

		getCriticalPathC: function () {
			for (let i = 0; i < WorldCreatorConstants.CRITICAL_PATHS_BY_ORDER.length; i++) {
				var path = WorldCreatorConstants.CRITICAL_PATHS_BY_ORDER[i];
				if (this.isOnCriticalPath(path)) return i;
			}
			return -1;
		},

		toString: function () {
			return "s-" + this.position;
		},

	});

	return SectorVO;
});


text:
package com.neo.repository;

import com.neo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {

    User findById(long id);

    Long deleteById(Long id);
}


text:
namespace peloton {

namespace expression {
class CaseExpression;
}  // namespace expression

namespace codegen {

/// A translator for CASE expressions.
class CaseTranslator : public ExpressionTranslator {
 public:
  CaseTranslator(const expression::CaseExpression &expression,
                 CompilationContext &context);

  codegen::Value DeriveValue(CodeGen &codegen,
                             RowBatch::Row &row) const override;
};

}  // namespace codegen
}  // namespace peloton


text:
external help file: HostsFile-help.xml
Module Name: HostsFile
online version: https://automatedlab.org/en/latest/HostsFile/en-us/Remove-HostEntry
schema: 2.0.0
---

# Remove-HostEntry

## SYNOPSIS
Remove a host entry

## SYNTAX

### ByIpAddress
```
Remove-HostEntry -IpAddress <IPAddress> -Section <String> [<CommonParameters>]
```

### ByHostName
```
Remove-HostEntry -HostName <Object> -Section <String> [<CommonParameters>]
```

### ByHostEntry
```
Remove-HostEntry -InputObject <Object> -Section <String> [<CommonParameters>]
```

## DESCRIPTION
Remove a host entry

## EXAMPLES

### Example 1
```powershell
PS C:\> Get-HostEntry -Ip 8.8.8.8 | Remove-HostEntry
```

Gets a host entry and uses the bound parameter InputObject to remove the entry

## PARAMETERS

### -HostName
The host name to remove

```yaml
Type: Object
Parameter Sets: ByHostName
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -InputObject
The host file entry to remove

```yaml
Type: Object
Parameter Sets: ByHostEntry
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -IpAddress
The IP address to remove

```yaml
Type: IPAddress
Parameter Sets: ByIpAddress
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Section
The section to remove in

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### None

## OUTPUTS

### System.Object
## NOTES

## RELATED LINKS


text:
package org.apache.accumulo.server;

public enum TabletLevel {
  ROOT, META, NORMAL

}


text:
FROM centos

MAINTAINER Yifan Gao <docker@yfgao.com>

ENV ASSETS_DIR="/opt/smartentry/HEAD"

COPY smartentry.sh /sbin/smartentry.sh

ENTRYPOINT ["/sbin/smartentry.sh"]

CMD ["run"]


text:
@implementation DataBase

+ (DataBase *)shareInstance {

    static DataBase * instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[DataBase alloc]init];
    });
    return instance;
}

+ (NSString *)cacheWithClass:(Class)cls {
    return [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", NSStringFromClass([cls class])]];
}

+ (void)cache:(Class)cls data:(NSDictionary *)data {
    [data writeToFile:[DataBase cacheWithClass:cls] atomically:YES];
}

+ (void)requestDataWithClass:(Class)cls finishedCallBack:(void(^)(NSDictionary * response))finishedCallBack {
    finishedCallBack([NSDictionary dictionaryWithContentsOfFile:[DataBase cacheWithClass:cls]]);
}

@end


text:
This SDK has now been deprecated.

For the latest JavaScript SDK (send only), please visit [developers.chirp.io/docs/getting-started/js](https://developers.chirp.io/docs/getting-started/js)

If you also want to decode in the browser, use the WebAssembly SDK [developers.chirp.io/docs/getting-started/wasm](https://developers.chirp.io/docs/getting-started/wasm)


text:
@implementation SADataObject

@synthesize imageName = _imageName;
@synthesize title     = _title;

- (NSString *)description
{
    NSString *desc = [NSString stringWithFormat:@"Data Object:[Image name:%@, Title:%@]", self.imageName, self.title];

    return desc;
}

@end


text:
'use strict';

// Declare app level module which depends on filters, and services
angular.module('myApp',['myApp.controllers', 'myApp.services'])
  .config([function() {
  }]);


text:
package com.vsked.pattern2;

public class Sample1Factory {

	public static Human createHuman(Class<?> c){
		Human man =null;
		try{
			man=(Human)Class.forName(c.getName()).newInstance();
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("create exception");
		}
		return man;
	}

}


text:
This is not an introduction to Python.
For that, see the [Python tutorial](https://docs.python.org/2/tutorial/) or the [Python module index](https://docs.python.org/3/py-modindex.html).
Instead, this lists some tips and pointers that will prove useful when working on your language.

### Lists

Lists will comprise our ASTs, so you'll need lists pretty early on. The [tutorial page on lists](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists) should prove useful.

### Dictionaries

We'll be using [dictionaries](https://docs.python.org/2/library/stdtypes.html#typesmapping) when representing the program environments.

- Remember that dicts are mutable in Python. Use the [`copy`](https://docs.python.org/2/library/stdtypes.html#dict.copy) function when a copy is needed.
- To update a dictionary with values from another, use [`update`](https://docs.python.org/2/library/stdtypes.html#set.update).
- You will find yourself needing to make a dictionary from a list of keys and a list of values. To do so, combine the [`dict`](https://docs.python.org/2/library/functions.html#func-dict) and [`zip`](https://docs.python.org/2/library/functions.html#zip) functions like this:

    ```python
    >>> dict(zip(["foo", "bar"], [1, 2]))
    {'foo': 1, 'bar': 2}
    ```

Read more about dicts in the [documentation](https://docs.python.org/2/tutorial/datastructures.html#dictionaries).

### Strings

- Strings works in many ways like lists. Thus, you can substring using indices:

    ```python
    >>> "hello world"[6:]
    'world'
    ```

- Remove unwanted whitespace using [`str.strip()`](https://docs.python.org/2/library/stdtypes.html#str.strip).

- It is also useful to know about how to do [string interpolation](https://docs.python.org/2/library/stdtypes.html#string-formatting-operations) in Python.

    ```python
    >>> "Hey, %s language!" % "cool"
    'Hey, cool language!'
    >>> "%d bottles of %s on the wall" % (99, "beer")
    '99 bottles of beer on the wall'
    >>> "%(num)s bottles of %(what)s on the %(where)s, %(num)d bottles of %(what)s" \
    ...      % {"num": 99, "what": "beer", "where": "wall"}
    '99 bottles of beer on the wall, 99 bottles of beer'
    ```

### Classes

When defining a class, all methods take a special argument `self` as the first argument. The `__init__` method works as constructor for the class.

```python
class Knight:

    def __init__(self, sound):
        self.sound = sound

    def speak(self):
        print self.sound
```

You don't provide the `self` when creating instances or calling methods:

```python
>>> knight = Knight("ni")
>>> knight.speak()
ni
```

### Default argument values

One thing it is easy to be bitten by is the way Python handles default function argument values. These are members of the function itself, and not "reset" every time the function is called.

```python
>>> def function(data=[]):
...     data.append(1)
...     return data
...
>>> function()
[1]
>>> function()
[1, 1]
>>> function()
[1, 1, 1]
```

Beware this when you implement the `Environment` class.


text:
import pymongo

from pymongo import MongoClient

# connect to database
connection = MongoClient('localhost', 27017)

db = connection.test

# handle to names collection
names = db.names

item = names.find_one()

print(item['name'])


text:
<?php

namespace App\Entities\Base;

use Doctrine\ORM\Mapping as ORM;

/**
 * App\Entities\Base\SoftwareInformation
 *
 * @ORM\MappedSuperclass
 * @ORM\Table(name="`software_information`")
 */
class SoftwareInformation extends AbstractEntity
{
    /** Table name constant */
    const TABLE_NAME = 'software_information';

    /** Column name constants */
    const NAME       = 'name';
    const VERSION    = 'version';
    const VENDOR     = 'vendor';

    /**
     * @ORM\Id
     * @ORM\Column(name="`id`", type="integer", options={"unsigned":true})
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(name="`name`", type="string", length=255)
     */
    protected $name;

    /**
     * @ORM\Column(name="`version`", type="string", length=100, nullable=true)
     */
    protected $version;

    /**
     * @ORM\Column(name="`vendor`", type="string", length=100, nullable=true)
     */
    protected $vendor;

    /**
     * @ORM\Column(name="`created_at`", type="datetime")
     */
    protected $created_at;

    /**
     * @ORM\Column(name="`updated_at`", type="datetime")
     */
    protected $updated_at;

    public function __construct()
    {
    }

    /**
     * Set the value of id.
     *
     * @param integer $id
     * @return \App\Entities\Base\SoftwareInformation
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * Get the value of id.
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set the value of name.
     *
     * @param string $name
     * @return \App\Entities\Base\SoftwareInformation
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get the value of name.
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set the value of version.
     *
     * @param string $version
     * @return \App\Entities\Base\SoftwareInformation
     */
    public function setVersion($version)
    {
        $this->version = $version;

        return $this;
    }

    /**
     * Get the value of version.
     *
     * @return string
     */
    public function getVersion()
    {
        return $this->version;
    }

    /**
     * Set the value of vendor.
     *
     * @param string $vendor
     * @return \App\Entities\Base\SoftwareInformation
     */
    public function setVendor($vendor)
    {
        $this->vendor = $vendor;

        return $this;
    }

    /**
     * Get the value of vendor.
     *
     * @return string
     */
    public function getVendor()
    {
        return $this->vendor;
    }

    /**
     * Set the value of created_at.
     *
     * @param \DateTime $created_at
     * @return \App\Entities\Base\SoftwareInformation
     */
    public function setCreatedAt($created_at)
    {
        $this->created_at = $created_at;

        return $this;
    }

    /**
     * Get the value of created_at.
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->created_at;
    }

    /**
     * Set the value of updated_at.
     *
     * @param \DateTime $updated_at
     * @return \App\Entities\Base\SoftwareInformation
     */
    public function setUpdatedAt($updated_at)
    {
        $this->updated_at = $updated_at;

        return $this;
    }

    /**
     * Get the value of updated_at.
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updated_at;
    }

    /**
     * Get the display name for the entity
     *
     * @param bool $plural
     * @return string
     */
    public function getDisplayName(bool $plural = false): string
    {
        return 'Software';
    }

    public function __sleep()
    {
        return array('id', 'name', 'version', 'vendor', 'created_at', 'updated_at');
    }
}


text:
require 'spec_helper'

describe RuboCop::Cop::Style::RescueEnsureAlignment do
  subject(:cop) { described_class.new }

  shared_examples 'common behavior' do |keyword|
    context 'bad alignment' do
      it 'registers an offense when used with begin' do
        inspect_source(cop, ['begin',
                             '  something',
                             "    #{keyword}",
                             '    error',
                             'end'])
        expect(cop.messages).to eq(["`#{keyword}` at 3, 4 is not aligned with" \
                                    ' `end` at 5, 0.'])
      end

      it 'registers an offense when used with def' do
        inspect_source(cop, ['def test',
                             '  something',
                             "    #{keyword}",
                             '    error',
                             'end'])
        expect(cop.messages).to eq(["`#{keyword}` at 3, 4 is not aligned with" \
                                    ' `end` at 5, 0.'])
      end

      it 'registers an offense when used with defs' do
        inspect_source(cop, ['def Test.test',
                             '  something',
                             "    #{keyword}",
                             '    error',
                             'end'])
        expect(cop.messages).to eq(["`#{keyword}` at 3, 4 is not aligned with" \
                                    ' `end` at 5, 0.'])
      end

      it 'auto-corrects' do
        corrected = autocorrect_source(cop, ['begin',
                                             '  something',
                                             "    #{keyword}",
                                             '    error',
                                             'end'])
        expect(corrected).to eq ['begin',
                                 '  something',
                                 keyword,
                                 '    error',
                                 'end'].join("\n")
      end
    end

    it 'accepts correct alignment' do
      inspect_source(cop, ['begin',
                           '  something',
                           keyword,
                           '    error',
                           'end'])
      expect(cop.messages).to be_empty
    end
  end

  context 'rescue' do
    it_behaves_like 'common behavior', 'rescue'

    it 'accepts the modifier form' do
      inspect_source(cop, 'test rescue nil')
      expect(cop.messages).to be_empty
    end
  end

  context 'ensure' do
    it_behaves_like 'common behavior', 'ensure'
  end

  describe 'excluded file' do
    let(:config) do
      RuboCop::Config.new('Style/RescueEnsureAlignment' =>
                          { 'Enabled' => true,
                            'Exclude' => ['**/**'] })
    end

    subject(:cop) { described_class.new(config) }

    it 'processes excluded files with issue' do
      inspect_source_file(cop, ['begin',
                                '  foo',
                                'rescue',
                                '  bar',
                                'end'])

      expect(cop.messages).to be_empty
    end
  end
end