text:
class Prison::FeedbacksController < ApplicationController
  def new
    @feedback = FeedbackSubmission.new(email_address: current_user&.email)
  end

  def create
    @feedback = FeedbackSubmission.new(feedback_params)
    if @feedback.save
      ZendeskTicketsJob.perform_later(@feedback)
      redirect_to prison_inbox_path,
                  notice: t('feedback_submitted', scope: %i[prison flash])
    else
      render :new
    end
  end

private

  def feedback_params
    params.
      require(:feedback_submission).
      permit(:referrer, :body, :email_address, :user_agent, :prison_id).
      merge(submitted_by_staff: true)
  end
end


text:
package org.apache.eagle.log.entity.filter;

import org.apache.eagle.log.entity.meta.EntityDefinition;
import org.apache.eagle.log.entity.meta.EntityDefinitionManager;
import org.apache.eagle.log.entity.test.TestLogAPIEntity;
import org.apache.eagle.query.parser.EagleQueryParseException;
import org.apache.eagle.query.parser.EagleQueryParser;
import org.apache.eagle.query.parser.ORExpression;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.RowFilter;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestHBaseFilterBuilder {
    private static final Logger LOG = LoggerFactory.getLogger(TestHBaseFilterBuilder.class);
    private EntityDefinition ed;

    private Filter buildFilter(String query) throws EagleQueryParseException {
        ORExpression expression = new EagleQueryParser(query).parse();
        HBaseFilterBuilder builder = new HBaseFilterBuilder(ed, expression);
        Filter filterList = builder.buildFilters();
        LOG.info("\n" + expression + " \n=> " + filterList);
        return filterList;
    }

    @Before
    public void setUp() {
        try {
            ed = EntityDefinitionManager.getEntityDefinitionByEntityClass(TestLogAPIEntity.class);
            if (ed == null) {
                EntityDefinitionManager.registerEntity(TestLogAPIEntity.class);
                ed = EntityDefinitionManager.getEntityDefinitionByEntityClass(TestLogAPIEntity.class);
            }
        } catch (InstantiationException e) {
            Assert.fail(e.getMessage());
        } catch (IllegalAccessException e) {
            Assert.fail(e.getMessage());
        }
    }

    /**
     * Should success without exception
     */
    @Test
    public void testQueryParseAndBuildFilterSuccess() {
        String[] queries = new String[] {
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID = \"job_1234\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID = \"PigLatin: \\\"quoted_pig_job_name_value\\\"\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID in (\"job_1234\",\"job_4567\")",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID in (1234,\"job_4567\")",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID in (1234,\"sample job name: \\\"quoted_job_name_value\\\"\")",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID CONTAINS \"job_1234\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID CONTAINS job_1234",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID NOT CONTAINS \"job_456\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID is \"job_789\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID is not \"job_789\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID is null",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID is not null",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID is NULL",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID is not NULL",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID = NULL",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID != null",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID =~ \".*job_1234.*\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID !=~ \".*job_1234.*\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID !=~ \"\\\\|_\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field1 = 1 ",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field1 = 1 and @field3 = 100000",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field1 = 1 and @field5 = 1.56",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field1 = 1 and @field5 > 1.56",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field1 = 1 and @field5 >= 1.56",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field1 = 1 and @field5 < 1.56",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field1 = 1 and @field5 <= 1.56",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and ( @field3 = 100000 or @field3 < 100000)\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and ( @field3 = 100000 or @field3 in (\"100000\",\"1\"))\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and ( @field3 = 100000 or @field3 in (\"100000\",\"1\"))\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and ( @field3 = 100000 or @field7 in (\"\\\"value1-part1,value1-part2\\\"\",\"value2\"))\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and ( @field3 = 100000 or @field3 not in (\"100000\",\"1\"))\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and ( @field3 = 100000 or @field3 NOT IN (\"100000\",\"1\"))\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and ( @field3 = 100000 or @field7 NOT IN (\"\\\"value1-part1,value1-part2\\\"\",\"value2\"))\"",
                                         // expression filter
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and EXP{field3/field7 - field2} > 12",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field5 > EXP{field3/field7 - field2}",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and EXP{field3/field7 - field2} > EXP{field1 * field2}",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and EXP{field3/field7 - field2} > EXP{field1 * field2}",
        };
        for (String query : queries) {
            try {
                Filter filter = buildFilter(query);
                Assert.assertNotNull(filter);
            } catch (EagleQueryParseException e) {
                Assert.fail(e.getMessage());
            } catch (Exception ex) {
                Assert.fail(ex.getMessage());
            }
        }
    }

    /**
     * Should throw exception
     */
    @Test
    public void testNegativeQueryParseSuccessfullyButBuildFilterFailed() {
        String[] queries = new String[] {
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @tag < \"job_1234\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @tag <= \"job_1234\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @tag >= \"job_1234\"",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field1 < null",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field1 <= null",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field1 > NULL",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field1 >= NULL",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field1 =~ NULL",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field1 !=~ NULL",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field1 contains NULL",
                                         "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field1 not contains NULL"
        };
        for (String query : queries) {
            try {
                @SuppressWarnings("unused")
                Filter filter = buildFilter(query);
                Assert.fail("Should throw exception: " + query);
            } catch (IllegalArgumentException e) {
                LOG.info("Expect exception: " + e.getMessage());
            } catch (EagleQueryParseException e) {
                Assert.fail("Should parse successfully: " + query);
            }
        }
    }

    @Test
    public void testParsedFilter() {
        String q1 = "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field3 = 100000";
        try {
            FilterList filterList = (FilterList)buildFilter(q1);
            Assert.assertEquals(FilterList.Operator.MUST_PASS_ONE, filterList.getOperator());
            Assert.assertEquals(1, filterList.getFilters().size());
            Assert.assertEquals(2, ((FilterList)filterList.getFilters().get(0)).getFilters().size());
        } catch (EagleQueryParseException e) {
            Assert.fail(e.getMessage());
        }

        String q2 = "@cluster = \"cluster1\" and @datacenter = \"dc1\" and ( @field3 = 100000 or @field3 < 100000)";
        try {
            FilterList filterList = (FilterList)buildFilter(q2);
            Assert.assertEquals(FilterList.Operator.MUST_PASS_ONE, filterList.getOperator());
            Assert.assertEquals(2, filterList.getFilters().size());
            Assert.assertEquals(2, ((FilterList)filterList.getFilters().get(0)).getFilters().size());
        } catch (EagleQueryParseException e) {
            Assert.fail(e.getMessage());
        }

        // Test parse success but bad type of value
        String q3 = "@cluster = \"cluster1\" and @datacenter = \"dc1\" and ( @field3 = 100000 or @field3 < \"bad_int_100000\")";
        boolean q3Ex = false;
        try {
            Assert.assertNull(buildFilter(q3));
        } catch (EagleQueryParseException e) {
            Assert.fail(e.getMessage());
        } catch (IllegalArgumentException e) {
            LOG.debug("Expect: ", e);
            Assert.assertTrue(e.getCause() instanceof NumberFormatException);
            q3Ex = true;
        }
        Assert.assertTrue(q3Ex);
    }

    @Test
    public void testWithUnescapedString() {
        ///////////////////////////////////
        // Tag filter with IN or EQUAL
        // Should use RowKeyFilter only
        ///////////////////////////////////
        String query = "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID = \"job.1234\"";
        try {
            FilterList filter = (FilterList)buildFilter(query);
            Assert.assertEquals(RowFilter.class,
                                ((FilterList)filter.getFilters().get(0)).getFilters().get(0).getClass());
            Assert.assertFalse("Should use rowkey filter only", filter.toString().matches(".*job.1234.*"));
        } catch (EagleQueryParseException e) {
            Assert.fail(e.getMessage());
        } catch (Exception ex) {
            Assert.fail(ex.getMessage());
        }

        query = "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID in (\"job_1234\")";
        try {
            FilterList filter = (FilterList)buildFilter(query);
            Assert.assertEquals(RowFilter.class,
                                ((FilterList)filter.getFilters().get(0)).getFilters().get(0).getClass());
            Assert.assertFalse("Should use rowkey filter only", filter.toString().matches(".*job_1234.*"));
        } catch (EagleQueryParseException e) {
            Assert.fail(e.getMessage());
        } catch (Exception ex) {
            Assert.fail(ex.getMessage());
        }

        query = "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID in (\"job.1234\")";
        try {
            FilterList filter = (FilterList)buildFilter(query);
            Assert.assertEquals(RowFilter.class,
                                ((FilterList)filter.getFilters().get(0)).getFilters().get(0).getClass());
            Assert.assertFalse("Should use rowkey filter only", filter.toString().matches(".*job.*1234.*"));
        } catch (EagleQueryParseException e) {
            Assert.fail(e.getMessage());
        } catch (Exception ex) {
            Assert.fail(ex.getMessage());
        }

        ///////////////////////////////
        // Tag with other operators
        ///////////////////////////////
        query = "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID =~ \"job_1234\"";

        try {
            FilterList filter = (FilterList)buildFilter(query);
            Assert.assertEquals(RowFilter.class,
                                ((FilterList)filter.getFilters().get(0)).getFilters().get(0).getClass());
            Assert.assertTrue(filter.toString().matches(".*job_1234.*"));
        } catch (EagleQueryParseException e) {
            Assert.fail(e.getMessage());
        } catch (Exception ex) {
            Assert.fail(ex.getMessage());
        }

        query = "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @jobID =~ \"job.1234\"";

        try {
            FilterList filter = (FilterList)buildFilter(query);
            Assert.assertEquals(RowFilter.class,
                                ((FilterList)filter.getFilters().get(0)).getFilters().get(0).getClass());
            Assert.assertTrue(filter.toString().matches(".*job.1234.*"));
        } catch (EagleQueryParseException e) {
            Assert.fail(e.getMessage());
        } catch (Exception ex) {
            Assert.fail(ex.getMessage());
        }

        ///////////////////////////////
        // Tag with IN
        // Should escape regexp chars
        ///////////////////////////////
        query = "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field7 = \"job_1234\"";

        try {
            FilterList filter = (FilterList)buildFilter(query);
            Assert.assertEquals(RowFilter.class,
                                ((FilterList)filter.getFilters().get(0)).getFilters().get(0).getClass());
            Assert.assertTrue(filter.toString().matches(".*job_1234.*"));
        } catch (EagleQueryParseException e) {
            Assert.fail(e.getMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
            Assert.fail(ex.getMessage());
        }

        query = "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field7 in (\"job.1234\",\"others\")";

        try {
            FilterList filter = (FilterList)buildFilter(query);
            Assert.assertEquals(RowFilter.class,
                                ((FilterList)filter.getFilters().get(0)).getFilters().get(0).getClass());
            Assert.assertTrue(filter.toString().matches(".*job\\.1234.*"));
        } catch (EagleQueryParseException e) {
            Assert.fail(e.getMessage());
        } catch (Exception ex) {
            Assert.fail(ex.getMessage());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System.Web.Mvc;
using AlloySample.Models.Pages;
using AlloySample.Models.ViewModels;
using EPiServer.Web;
using EPiServer.Web.Mvc;

namespace AlloySample.Controllers
{
    public class StartPageController : PageControllerBase<StartPage>
    {
        public ActionResult Index(StartPage currentPage)
        {
            var model = PageViewModel.Create(currentPage);

            if (SiteDefinition.Current.StartPage.CompareToIgnoreWorkID(currentPage.ContentLink)) // Check if it is the StartPage or just a page of the StartPage type.
            {
                //Connect the view models logotype property to the start page's to make it editable
                var editHints = ViewData.GetEditHints<PageViewModel<StartPage>, StartPage>();
                editHints.AddConnection(m => m.Layout.Logotype, p => p.SiteLogotype);
                editHints.AddConnection(m => m.Layout.ProductPages, p => p.ProductPageLinks);
                editHints.AddConnection(m => m.Layout.CompanyInformationPages, p => p.CompanyInformationPageLinks);
                editHints.AddConnection(m => m.Layout.NewsPages, p => p.NewsPageLinks);
                editHints.AddConnection(m => m.Layout.CustomerZonePages, p => p.CustomerZonePageLinks);
            }

            return View(model);
        }

    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class io.permazen.kv.KVDatabaseException (Permazen 4.1.6 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
io.permazen.kv.KVDatabaseException

Packages that use KVDatabaseException

Package
Description

io.permazen.kv

byte[] array key/value store API and related utility classes.

io.permazen.kv.mvcc

Utility classes for MVCC type operations using a KVStore.

Uses of KVDatabaseException in io.permazen.kv

Subclasses of KVDatabaseException in io.permazen.kv

Modifier and Type
Class and Description

class
KVTransactionException

Thrown when an operation on a KVTransaction fails.

class
RetryTransactionException

Exception thrown when an attempt to access a KVTransaction results
 in a conflict or other condition requiring that the transaction be retried.

class
StaleTransactionException

Thrown when an operation is attempted on a KVTransaction that is no longer usable.

class
TransactionTimeoutException

Thrown when a KVTransaction is kept open for too long.

Uses of KVDatabaseException in io.permazen.kv.mvcc

Subclasses of KVDatabaseException in io.permazen.kv.mvcc

Modifier and Type
Class and Description

class
TransactionConflictException

Exception thrown when a transaction fails because of an MVCC conflict.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2020. All rights reserved.


text:
module SolidUseCase
  module Either
    class ErrorStruct < OpenStruct
      def ==(error_type_symbol)
        self[:type] == error_type_symbol
      end
    end
  end
end


text:
#ifndef B2_BROAD_PHASE_H
#define B2_BROAD_PHASE_H

#include "Common/b2Settings.h"
#include "Collision/b2Collision.h"
#include "Collision/b2DynamicTree.h"
#include <algorithm>

struct b2Pair
{
	int32 proxyIdA;
	int32 proxyIdB;
};

/// The broad-phase is used for computing pairs and performing volume queries and ray casts.
/// This broad-phase does not persist pairs. Instead, this reports potentially new pairs.
/// It is up to the client to consume the new pairs and to track subsequent overlap.
class b2BroadPhase
{
public:

	enum
	{
		e_nullProxy = -1
	};

	b2BroadPhase();
	~b2BroadPhase();

	/// Create a proxy with an initial AABB. Pairs are not reported until
	/// UpdatePairs is called.
	int32 CreateProxy(const b2AABB& aabb, void* userData);

	/// Destroy a proxy. It is up to the client to remove any pairs.
	void DestroyProxy(int32 proxyId);

	/// Call MoveProxy as many times as you like, then when you are done
	/// call UpdatePairs to finalized the proxy pairs (for your time step).
	void MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement);

	/// Call to trigger a re-processing of it's pairs on the next call to UpdatePairs.
	void TouchProxy(int32 proxyId);

	/// Get the fat AABB for a proxy.
	const b2AABB& GetFatAABB(int32 proxyId) const;

	/// Get user data from a proxy. Returns NULL if the id is invalid.
	void* GetUserData(int32 proxyId) const;

	/// Test overlap of fat AABBs.
	bool TestOverlap(int32 proxyIdA, int32 proxyIdB) const;

	/// Get the number of proxies.
	int32 GetProxyCount() const;

	/// Update the pairs. This results in pair callbacks. This can only add pairs.
	template <typename T>
	void UpdatePairs(T* callback);

	/// Query an AABB for overlapping proxies. The callback class
	/// is called for each proxy that overlaps the supplied AABB.
	template <typename T>
	void Query(T* callback, const b2AABB& aabb) const;

	/// Ray-cast against the proxies in the tree. This relies on the callback
	/// to perform a exact ray-cast in the case were the proxy contains a shape.
	/// The callback also performs the any collision filtering. This has performance
	/// roughly equal to k * log(n), where k is the number of collisions and n is the
	/// number of proxies in the tree.
	/// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
	/// @param callback a callback class that is called for each proxy that is hit by the ray.
	template <typename T>
	void RayCast(T* callback, const b2RayCastInput& input) const;

	/// Get the height of the embedded tree.
	int32 GetTreeHeight() const;

	/// Get the balance of the embedded tree.
	int32 GetTreeBalance() const;

	/// Get the quality metric of the embedded tree.
	float32 GetTreeQuality() const;

	/// Shift the world origin. Useful for large worlds.
	/// The shift formula is: position -= newOrigin
	/// @param newOrigin the new origin with respect to the old origin
	void ShiftOrigin(const b2Vec2& newOrigin);

private:

	friend class b2DynamicTree;

	void BufferMove(int32 proxyId);
	void UnBufferMove(int32 proxyId);

	bool QueryCallback(int32 proxyId);

	b2DynamicTree m_tree;

	int32 m_proxyCount;

	int32* m_moveBuffer;
	int32 m_moveCapacity;
	int32 m_moveCount;

	b2Pair* m_pairBuffer;
	int32 m_pairCapacity;
	int32 m_pairCount;

	int32 m_queryProxyId;
};

/// This is used to sort pairs.
inline bool b2PairLessThan(const b2Pair& pair1, const b2Pair& pair2)
{
	if (pair1.proxyIdA < pair2.proxyIdA)
	{
		return true;
	}

	if (pair1.proxyIdA == pair2.proxyIdA)
	{
		return pair1.proxyIdB < pair2.proxyIdB;
	}

	return false;
}

inline void* b2BroadPhase::GetUserData(int32 proxyId) const
{
	return m_tree.GetUserData(proxyId);
}

inline bool b2BroadPhase::TestOverlap(int32 proxyIdA, int32 proxyIdB) const
{
	const b2AABB& aabbA = m_tree.GetFatAABB(proxyIdA);
	const b2AABB& aabbB = m_tree.GetFatAABB(proxyIdB);
	return b2TestOverlap(aabbA, aabbB);
}

inline const b2AABB& b2BroadPhase::GetFatAABB(int32 proxyId) const
{
	return m_tree.GetFatAABB(proxyId);
}

inline int32 b2BroadPhase::GetProxyCount() const
{
	return m_proxyCount;
}

inline int32 b2BroadPhase::GetTreeHeight() const
{
	return m_tree.GetHeight();
}

inline int32 b2BroadPhase::GetTreeBalance() const
{
	return m_tree.GetMaxBalance();
}

inline float32 b2BroadPhase::GetTreeQuality() const
{
	return m_tree.GetAreaRatio();
}

template <typename T>
void b2BroadPhase::UpdatePairs(T* callback)
{
	// Reset pair buffer
	m_pairCount = 0;

	// Perform tree queries for all moving proxies.
	for (int32 i = 0; i < m_moveCount; ++i)
	{
		m_queryProxyId = m_moveBuffer[i];
		if (m_queryProxyId == e_nullProxy)
		{
			continue;
		}

		// We have to query the tree with the fat AABB so that
		// we don't fail to create a pair that may touch later.
		const b2AABB& fatAABB = m_tree.GetFatAABB(m_queryProxyId);

		// Query tree, create pairs and add them pair buffer.
		m_tree.Query(this, fatAABB);
	}

	// Reset move buffer
	m_moveCount = 0;

	// Sort the pair buffer to expose duplicates.
	std::sort(m_pairBuffer, m_pairBuffer + m_pairCount, b2PairLessThan);

	// Send the pairs back to the client.
	int32 i = 0;
	while (i < m_pairCount)
	{
		b2Pair* primaryPair = m_pairBuffer + i;
		void* userDataA = m_tree.GetUserData(primaryPair->proxyIdA);
		void* userDataB = m_tree.GetUserData(primaryPair->proxyIdB);

		callback->AddPair(userDataA, userDataB);
		++i;

		// Skip any duplicate pairs.
		while (i < m_pairCount)
		{
			b2Pair* pair = m_pairBuffer + i;
			if (pair->proxyIdA != primaryPair->proxyIdA || pair->proxyIdB != primaryPair->proxyIdB)
			{
				break;
			}
			++i;
		}
	}

	// Try to keep the tree balanced.
	//m_tree.Rebalance(4);
}

template <typename T>
inline void b2BroadPhase::Query(T* callback, const b2AABB& aabb) const
{
	m_tree.Query(callback, aabb);
}

template <typename T>
inline void b2BroadPhase::RayCast(T* callback, const b2RayCastInput& input) const
{
	m_tree.RayCast(callback, input);
}

inline void b2BroadPhase::ShiftOrigin(const b2Vec2& newOrigin)
{
	m_tree.ShiftOrigin(newOrigin);
}

#endif


text:
SYNONYM

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

#### Published in
Fl. carniol. (Wien), Edn 2 2: 445 (1772)

#### Original name
Agaricus inversus Scop., 1772

### Remarks
null


text:
package ru.stesting.jtraining.addressbook.tests;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stesting.jtraining.addressbook.model.ContactData;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * Created by DBorisov on 28.05.2016.
 */
public class ContactDetalisTests extends TestBase {

  @BeforeMethod
  public  void ensurePreconditions() {
    app.goTo().homePage();
    if (app.contact().all().size() == 0) {
      app.contact().createContactWithTestData();
    }
  }

  @Test
  public void testContactDetails() {
    ContactData contact = app.contact().all().iterator().next();
    ContactData contactInfoFromEditForm = app.contact().infoFromEditForm(contact);
    String contactInfoFromDetailsFormAsString = app.contact().infoFromDetailsFormAsString(contact);

    assertThat(contactInfoFromEditForm.asString(), equalTo(truncateGroups(contactInfoFromDetailsFormAsString)));
  }

  private String truncateGroups(String contactInfoAsString) {
    if (contactInfoAsString.indexOf("\n\nMember of:") > 0)  {
      return contactInfoAsString.substring(0, contactInfoAsString.indexOf("\n\nMember of:"));
    }
   return contactInfoAsString;
  }
}


text:
import mock
from oslo_db import exception as db_exc

from neutron.api.rpc.handlers import dhcp_rpc
from neutron.common import constants
from neutron.common import exceptions as n_exc
from neutron.tests import base

class TestDhcpRpcCallback(base.BaseTestCase):

    def setUp(self):
        super(TestDhcpRpcCallback, self).setUp()
        self.plugin_p = mock.patch('neutron.manager.NeutronManager.get_plugin')
        get_plugin = self.plugin_p.start()
        self.plugin = mock.MagicMock()
        get_plugin.return_value = self.plugin
        self.callbacks = dhcp_rpc.DhcpRpcCallback()
        self.log_p = mock.patch('neutron.api.rpc.handlers.dhcp_rpc.LOG')
        self.log = self.log_p.start()

    def test_get_active_networks(self):
        plugin_retval = [dict(id='a'), dict(id='b')]
        self.plugin.get_networks.return_value = plugin_retval

        networks = self.callbacks.get_active_networks(mock.Mock(), host='host')

        self.assertEqual(networks, ['a', 'b'])
        self.plugin.assert_has_calls(
            [mock.call.get_networks(mock.ANY,
                                    filters=dict(admin_state_up=[True]))])

        self.assertEqual(len(self.log.mock_calls), 1)

    def test_group_by_network_id(self):
        port1 = {'network_id': 'a'}
        port2 = {'network_id': 'b'}
        port3 = {'network_id': 'a'}
        grouped_ports = self.callbacks._group_by_network_id(
                                                        [port1, port2, port3])
        expected = {'a': [port1, port3], 'b': [port2]}
        self.assertEqual(expected, grouped_ports)

    def test_get_active_networks_info(self):
        plugin_retval = [{'id': 'a'}, {'id': 'b'}]
        self.plugin.get_networks.return_value = plugin_retval
        port = {'network_id': 'a'}
        subnet = {'network_id': 'b'}
        self.plugin.get_ports.return_value = [port]
        self.plugin.get_subnets.return_value = [subnet]
        networks = self.callbacks.get_active_networks_info(mock.Mock(),
                                                           host='host')
        expected = [{'id': 'a', 'subnets': [], 'ports': [port]},
                    {'id': 'b', 'subnets': [subnet], 'ports': []}]
        self.assertEqual(expected, networks)

    def _test__port_action_with_failures(self, exc=None, action=None):
        port = {
            'network_id': 'foo_network_id',
            'device_owner': constants.DEVICE_OWNER_DHCP,
            'fixed_ips': [{'subnet_id': 'foo_subnet_id'}]
        }
        self.plugin.create_port.side_effect = exc
        self.assertIsNone(self.callbacks._port_action(self.plugin,
                                                      mock.Mock(),
                                                      {'port': port},
                                                      action))

    def _test__port_action_good_action(self, action, port, expected_call):
        self.callbacks._port_action(self.plugin, mock.Mock(),
                                    port, action)
        self.plugin.assert_has_calls([expected_call])

    def test_port_action_create_port(self):
        self._test__port_action_good_action(
            'create_port', mock.Mock(),
            mock.call.create_port(mock.ANY, mock.ANY))

    def test_port_action_update_port(self):
        fake_port = {'id': 'foo_port_id', 'port': mock.Mock()}
        self._test__port_action_good_action(
            'update_port', fake_port,
            mock.call.update_port(mock.ANY, 'foo_port_id', mock.ANY))

    def test__port_action_bad_action(self):
        self.assertRaises(
            n_exc.Invalid,
            self._test__port_action_with_failures,
            exc=None,
            action='foo_action')

    def test_create_port_catch_network_not_found(self):
        self._test__port_action_with_failures(
            exc=n_exc.NetworkNotFound(net_id='foo_network_id'),
            action='create_port')

    def test_create_port_catch_subnet_not_found(self):
        self._test__port_action_with_failures(
            exc=n_exc.SubnetNotFound(subnet_id='foo_subnet_id'),
            action='create_port')

    def test_create_port_catch_db_error(self):
        self._test__port_action_with_failures(exc=db_exc.DBError(),
                                              action='create_port')

    def test_create_port_catch_ip_generation_failure_reraise(self):
        self.assertRaises(
            n_exc.IpAddressGenerationFailure,
            self._test__port_action_with_failures,
            exc=n_exc.IpAddressGenerationFailure(net_id='foo_network_id'),
            action='create_port')

    def test_create_port_catch_and_handle_ip_generation_failure(self):
        self.plugin.get_subnet.side_effect = (
            n_exc.SubnetNotFound(subnet_id='foo_subnet_id'))
        self._test__port_action_with_failures(
            exc=n_exc.IpAddressGenerationFailure(net_id='foo_network_id'),
            action='create_port')

    def test_get_network_info_return_none_on_not_found(self):
        self.plugin.get_network.side_effect = n_exc.NetworkNotFound(net_id='a')
        retval = self.callbacks.get_network_info(mock.Mock(), network_id='a')
        self.assertIsNone(retval)

    def test_get_network_info(self):
        network_retval = dict(id='a')

        subnet_retval = mock.Mock()
        port_retval = mock.Mock()

        self.plugin.get_network.return_value = network_retval
        self.plugin.get_subnets.return_value = subnet_retval
        self.plugin.get_ports.return_value = port_retval

        retval = self.callbacks.get_network_info(mock.Mock(), network_id='a')
        self.assertEqual(retval, network_retval)
        self.assertEqual(retval['subnets'], subnet_retval)
        self.assertEqual(retval['ports'], port_retval)

    def _test_get_dhcp_port_helper(self, port_retval, other_expectations=[],
                                   update_port=None, create_port=None):
        subnets_retval = [dict(id='a', enable_dhcp=True),
                          dict(id='b', enable_dhcp=False)]

        self.plugin.get_subnets.return_value = subnets_retval
        if port_retval:
            self.plugin.get_ports.return_value = [port_retval]
        else:
            self.plugin.get_ports.return_value = []
        if isinstance(update_port, n_exc.NotFound):
            self.plugin.update_port.side_effect = update_port
        else:
            self.plugin.update_port.return_value = update_port
        self.plugin.create_port.return_value = create_port

        retval = self.callbacks.get_dhcp_port(mock.Mock(),
                                              network_id='netid',
                                              device_id='devid',
                                              host='host')

        expected = [mock.call.get_subnets(mock.ANY,
                                          filters=dict(network_id=['netid'])),
                    mock.call.get_ports(mock.ANY,
                                        filters=dict(network_id=['netid'],
                                                     device_id=['devid']))]

        expected.extend(other_expectations)
        self.plugin.assert_has_calls(expected)
        return retval

    def test_update_dhcp_port_verify_port_action_port_dict(self):
        port = {'port': {'network_id': 'foo_network_id',
                         'device_owner': constants.DEVICE_OWNER_DHCP,
                         'fixed_ips': [{'subnet_id': 'foo_subnet_id'}]}
                }
        expected_port = {'port': {'network_id': 'foo_network_id',
                                  'device_owner': constants.DEVICE_OWNER_DHCP,
                                  'binding:host_id': 'foo_host',
                                  'fixed_ips': [{'subnet_id': 'foo_subnet_id'}]
                                  },
                         'id': 'foo_port_id'
                         }

        def _fake_port_action(plugin, context, port, action):
            self.assertEqual(expected_port, port)

        self.callbacks._port_action = _fake_port_action
        self.callbacks.update_dhcp_port(mock.Mock(),
                                        host='foo_host',
                                        port_id='foo_port_id',
                                        port=port)

    def test_update_dhcp_port(self):
        port = {'port': {'network_id': 'foo_network_id',
                         'device_owner': constants.DEVICE_OWNER_DHCP,
                         'fixed_ips': [{'subnet_id': 'foo_subnet_id'}]}
                }
        expected_port = {'port': {'network_id': 'foo_network_id',
                                  'device_owner': constants.DEVICE_OWNER_DHCP,
                                  'binding:host_id': 'foo_host',
                                  'fixed_ips': [{'subnet_id': 'foo_subnet_id'}]
                                  },
                         'id': 'foo_port_id'
                         }
        self.callbacks.update_dhcp_port(mock.Mock(),
                                        host='foo_host',
                                        port_id='foo_port_id',
                                        port=port)
        self.plugin.assert_has_calls([
            mock.call.update_port(mock.ANY, 'foo_port_id', expected_port)])

    def test_get_dhcp_port_existing(self):
        port_retval = dict(id='port_id', fixed_ips=[dict(subnet_id='a')])
        expectations = [
            mock.call.update_port(mock.ANY, 'port_id', dict(port=port_retval))]

        self._test_get_dhcp_port_helper(port_retval, expectations,
                                        update_port=port_retval)
        self.assertEqual(len(self.log.mock_calls), 1)

    def _test_get_dhcp_port_create_new(self, update_port=None):
        self.plugin.get_network.return_value = dict(tenant_id='tenantid')
        create_spec = dict(tenant_id='tenantid', device_id='devid',
                           network_id='netid', name='',
                           admin_state_up=True,
                           device_owner=constants.DEVICE_OWNER_DHCP,
                           mac_address=mock.ANY)
        create_retval = create_spec.copy()
        create_retval['id'] = 'port_id'
        create_retval['fixed_ips'] = [dict(subnet_id='a', enable_dhcp=True)]

        create_spec['fixed_ips'] = [dict(subnet_id='a')]

        expectations = [
            mock.call.get_network(mock.ANY, 'netid'),
            mock.call.create_port(mock.ANY, dict(port=create_spec))]

        retval = self._test_get_dhcp_port_helper(None, expectations,
                                                 update_port=update_port,
                                                 create_port=create_retval)
        self.assertEqual(create_retval, retval)
        self.assertEqual(len(self.log.mock_calls), 2)

    def test_get_dhcp_port_create_new(self):
        self._test_get_dhcp_port_create_new()

    def test_get_dhcp_port_create_new_with_failure_on_port_update(self):
        self._test_get_dhcp_port_create_new(
            update_port=n_exc.PortNotFound(port_id='foo'))

    def test_release_dhcp_port(self):
        port_retval = dict(id='port_id', fixed_ips=[dict(subnet_id='a')])
        self.plugin.get_ports.return_value = [port_retval]

        self.callbacks.release_dhcp_port(mock.ANY, network_id='netid',
                                         device_id='devid')

        self.plugin.assert_has_calls([
            mock.call.delete_ports_by_device_id(mock.ANY, 'devid', 'netid')])

    def test_release_port_fixed_ip(self):
        port_retval = dict(id='port_id', fixed_ips=[dict(subnet_id='a')])
        port_update = dict(id='port_id', fixed_ips=[])
        self.plugin.get_ports.return_value = [port_retval]

        self.callbacks.release_port_fixed_ip(mock.ANY, network_id='netid',
                                             device_id='devid', subnet_id='a')

        self.plugin.assert_has_calls([
            mock.call.get_ports(mock.ANY, filters=dict(network_id=['netid'],
                                                       device_id=['devid'])),
            mock.call.update_port(mock.ANY, 'port_id',
                                  dict(port=port_update))])


text:
using UnityEngine;

public class UnityPlanet : MonoBehaviour
{

	private bool destroyed;

	public Vector3 Position
	{
		get { return gameObject.transform.position; }
		set { gameObject.transform.position = value; }
	}

	public Quaternion Rotation
	{
		get { return gameObject.transform.rotation; }
		set { gameObject.transform.rotation = value; }
	}

	public bool Destroyed
	{
		get { return destroyed; }
		set
		{
			destroyed = value;
			if (destroyed)
				GameObject.Destroy(gameObject);
		}
	}

	public static UnityPlanet Instantiate(Vector3 pos, float mass)
	{
		int asteroidVariant = Random.Range (1,6);
		var planet = GameObject.Instantiate(Resources.Load("Asteroid" + asteroidVariant.ToString()), pos, Quaternion.identity) as GameObject;
		planet.transform.rigidbody.mass = mass;
		var scale = planet.transform.localScale;
		var scaleFactor = mass / 10000.0f;
		planet.transform.localScale = new Vector3(scale.x + scaleFactor, scale.y + scaleFactor, scale.z + scaleFactor);
		return planet.GetComponent<UnityPlanet>();
	}
}


text:
class Test : boost::noncopyable
{
 public:
  Test()
  {
    printf("tid=%d, constructing %p\n", muduo::CurrentThread::tid(), this);
  }

  ~Test()
  {
    printf("tid=%d, destructing %p %s\n", muduo::CurrentThread::tid(), this, name_.c_str());
  }

  const std::string& name() const { return name_; }
  void setName(const std::string& n) { name_ = n; }

 private:
  std::string name_;
};

void threadFunc()
{
  printf("tid=%d, %p name=%s\n",
         muduo::CurrentThread::tid(),
         &muduo::Singleton<Test>::instance(),
         muduo::Singleton<Test>::instance().name().c_str());
  muduo::Singleton<Test>::instance().setName("only one, changed");
}

int main()
{
  muduo::Singleton<Test>::instance().setName("only one");
  muduo::Thread t1(threadFunc);
  t1.start();
  t1.join();
  printf("tid=%d, %p name=%s\n",
         muduo::CurrentThread::tid(),
         &muduo::Singleton<Test>::instance(),
         muduo::Singleton<Test>::instance().name().c_str());
}


text:
package io.undertow.servlet.test.security.form;

import static org.junit.Assert.assertEquals;

import io.undertow.security.api.AuthenticationMode;
import io.undertow.server.handlers.PathHandler;
import io.undertow.servlet.api.AuthMethodConfig;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;
import io.undertow.servlet.api.LoginConfig;
import io.undertow.servlet.api.ServletContainer;
import io.undertow.servlet.api.ServletInfo;
import io.undertow.servlet.api.ServletSecurityInfo;
import io.undertow.servlet.test.SimpleServletTestCase;
import io.undertow.servlet.test.security.SendUsernameServlet;
import io.undertow.servlet.test.security.constraint.ServletIdentityManager;
import io.undertow.servlet.test.util.TestClassIntrospector;
import io.undertow.testutils.DefaultServer;
import io.undertow.testutils.HttpClientUtils;
import io.undertow.testutils.TestHttpClient;
import io.undertow.util.StatusCodes;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 * @author Mark Banierink
 */
@RunWith(DefaultServer.class)
public class ServletFormAuthDefaultPageTestCase {

    public static final String HELLO_WORLD = "Hello World";
    private static final String DEFAULT_PAGE = "/main.html";

    @BeforeClass
    public static void setup() throws ServletException {
        final PathHandler path = new PathHandler();

        final ServletContainer container = ServletContainer.Factory.newInstance();

        ServletInfo s = new ServletInfo("servlet", SendUsernameServlet.class)
                .setServletSecurityInfo(new ServletSecurityInfo()
                        .addRoleAllowed("role1"))
                .addMapping("/secured/*");

        ServletInfo echo = new ServletInfo("echo", EchoServlet.class)
                .setServletSecurityInfo(new ServletSecurityInfo()
                        .addRoleAllowed("role1"))
                .addMapping("/secured/echo");

        ServletInfo echoParam = new ServletInfo("echoParam", RequestParamEchoServlet.class)
                .setServletSecurityInfo(new ServletSecurityInfo()
                        .addRoleAllowed("role1"))
                .addMapping("/secured/echoParam");

        ServletInfo s1 = new ServletInfo("loginPage", FormLoginServlet.class)
                .setServletSecurityInfo(new ServletSecurityInfo()
                        .addRoleAllowed("group1"))
                .addMapping("/FormLoginServlet");

        ServletIdentityManager identityManager = new ServletIdentityManager();
        identityManager.addUser("user1", "password1", "role1");

        Map<String, String> props = new HashMap<>();
        props.put("default_page", "/main.html");
        props.put("override_initial", "true");
        AuthMethodConfig authMethodConfig = new AuthMethodConfig("FORM", props);

        LoginConfig loginConfig = new LoginConfig("Test Realm", "/FormLoginServlet", "/error.html").addFirstAuthMethod(authMethodConfig);

        DeploymentInfo builder = new DeploymentInfo()
                .setClassLoader(SimpleServletTestCase.class.getClassLoader())
                .setContextPath("/servletContext")
                .setClassIntrospecter(TestClassIntrospector.INSTANCE)
                .setDeploymentName("servletContext.war")
                .setAuthenticationMode(AuthenticationMode.CONSTRAINT_DRIVEN)
                .setIdentityManager(identityManager)
                .setLoginConfig(loginConfig)
                .addServlets(s, s1, echo,echoParam);

        DeploymentManager manager = container.addDeployment(builder);
        manager.deploy();
        path.addPrefixPath(builder.getContextPath(), manager.start());

        DefaultServer.setRootHandler(path);
    }

    @Test
    public void testServletFormAuth() throws IOException {
        TestHttpClient client = new TestHttpClient();
        client.setRedirectStrategy(new DefaultRedirectStrategy() {
            @Override
            public boolean isRedirected(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException {
                if (response.getStatusLine().getStatusCode() == StatusCodes.FOUND) {
                    return true;
                }
                if (request.getRequestLine().getUri().equals(DEFAULT_PAGE)) {
                    response.setStatusCode(StatusCodes.OK);
                    // Skip redirecting, because the resource isn't available in this test
                    return false;
                }
                return super.isRedirected(request, response, context);
            }
        });
        try {
            final String uri = DefaultServer.getDefaultServerURL() + "/servletContext/secured/test";
            HttpGet get = new HttpGet(uri);
            HttpResponse result = client.execute(get);
            assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            String response = HttpClientUtils.readResponse(result);
            Assert.assertTrue(response.startsWith("j_security_check"));

            BasicNameValuePair[] pairs = new BasicNameValuePair[]{new BasicNameValuePair("j_username", "user1"), new BasicNameValuePair("j_password", "password1")};
            final List<NameValuePair> data = new ArrayList<>();
            data.addAll(Arrays.asList(pairs));
            HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/servletContext/j_security_check;jsessionid=dsjahfklsahdfjklsa");

            post.setEntity(new UrlEncodedFormEntity(data));

            result = client.execute(post);
            assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

            response = HttpClientUtils.readResponse(result);
            Assert.assertEquals("", response);
        } finally {
            client.getConnectionManager().shutdown();
        }
    }

    @Test
    public void testServletFormAuthWithSavedPostBody() throws IOException {
        TestHttpClient client = new TestHttpClient();
        client.setRedirectStrategy(new DefaultRedirectStrategy() {
            @Override
            public boolean isRedirected(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException {
                if (response.getStatusLine().getStatusCode() == StatusCodes.FOUND) {
                    return true;
                }
                if (request.getRequestLine().getUri().equals(DEFAULT_PAGE)) {
                    response.setStatusCode(StatusCodes.OK);
                    // Skip redirecting, because the resource isn't available in this test
                    return false;
                }
                return super.isRedirected(request, response, context);
            }
        });
        try {
            final String uri = DefaultServer.getDefaultServerURL() + "/servletContext/secured/echo";
            HttpPost post = new HttpPost(uri);
            post.setEntity(new StringEntity("String Entity"));
            HttpResponse result = client.execute(post);
            assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            String response = HttpClientUtils.readResponse(result);
            Assert.assertTrue(response.startsWith("j_security_check"));

            BasicNameValuePair[] pairs = new BasicNameValuePair[]{new BasicNameValuePair("j_username", "user1"), new BasicNameValuePair("j_password", "password1")};
            final List<NameValuePair> data = new ArrayList<>();
            data.addAll(Arrays.asList(pairs));
            post = new HttpPost(DefaultServer.getDefaultServerURL() + "/servletContext/j_security_check");

            post.setEntity(new UrlEncodedFormEntity(data));

            result = client.execute(post);
            assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

            response = HttpClientUtils.readResponse(result);
            Assert.assertEquals("", response);
        } finally {
            client.getConnectionManager().shutdown();
        }
    }

    @Test
    public void testServletFormAuthWithoutSavedPostBody() throws IOException {
        TestHttpClient client = new TestHttpClient();
        client.setRedirectStrategy(new DefaultRedirectStrategy() {
            @Override
            public boolean isRedirected(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException {
                if (response.getStatusLine().getStatusCode() == StatusCodes.FOUND) {
                    return true;
                }
                if (request.getRequestLine().getUri().equals(DEFAULT_PAGE)) {
                    response.setStatusCode(StatusCodes.OK);
                    // Skip redirecting, because the resource isn't available in this test
                    return false;
                }
                // force the test to fail
                response.setStatusCode(StatusCodes.EXPECTATION_FAILED);
                return super.isRedirected(request, response, context);
            }
        });
        try {
            BasicNameValuePair[] pairs = new BasicNameValuePair[]{new BasicNameValuePair("j_username", "user1"), new BasicNameValuePair("j_password", "password1")};
            final List<NameValuePair> data = new ArrayList<>();
            data.addAll(Arrays.asList(pairs));
            HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/servletContext/j_security_check");

            post.setEntity(new UrlEncodedFormEntity(data));

            HttpResponse result = client.execute(post);
            assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

            String response = HttpClientUtils.readResponse(result);
            Assert.assertEquals("", response);
        } finally {
            client.getConnectionManager().shutdown();
        }
    }
}


text:
require 'opennebula/pool_element'

module OpenNebula
    class Group < PoolElement
        #######################################################################
        # Constants and Class Methods
        #######################################################################

        GROUP_METHODS = {
            :info           => "group.info",
            :allocate       => "group.allocate",
            :update         => "group.update",
            :delete         => "group.delete",
            :quota          => "group.quota",
            :add_provider   => "group.addprovider",
            :del_provider   => "group.delprovider"
        }

        # Flag for requesting connected user's group info
        SELF = -1

        # Default resource ACL's for group users (create)
        GROUP_DEFAULT_ACLS = "VM+IMAGE+TEMPLATE+DOCUMENT"
        ALL_CLUSTERS_IN_ZONE = 10

        # The default view for group and group admins, must be defined in
        # sunstone_views.yaml
        GROUP_ADMIN_SUNSTONE_VIEWS = "vdcadmin"

        # Creates a Group description with just its identifier
        # this method should be used to create plain Group objects.
        # +id+ the id of the user
        #
        # Example:
        #   group = Group.new(Group.build_xml(3),rpc_client)
        #
        def Group.build_xml(pe_id=nil)
            if pe_id
                group_xml = "<GROUP><ID>#{pe_id}</ID></GROUP>"
            else
                group_xml = "<GROUP></GROUP>"
            end

            XMLElement.build_xml(group_xml,'GROUP')
        end

        # Class constructor
        def initialize(xml, client)
            super(xml,client)
        end

        #######################################################################
        # XML-RPC Methods for the Group Object
        #######################################################################

        # Retrieves the information of the given Group.
        def info()
            super(GROUP_METHODS[:info], 'GROUP')
        end

        alias_method :info!, :info

        # Creates a group based in a group definition hash
        #   group_hash[:name] the group name
        #   group_hash[:group_admin] the admin user definition hash, see def
        #   create_admin_user function description for details.
        #   group_hash[:resource_providers]
        #   group_hash[:resource_providers][:zone_id]
        #   group_hash[:resource_providers][:cluster_id]
        #   group_hash[:views] Array of sunstone view names, to be stored
        #       in SUNSTONE_VIEWS
        #   group_hash[:default_view] Default sunstone view name, to be stored
        #       in DEFAULT_VIEW
        #
        def create(group_hash)
            # Check arguments
            if !group_hash[:name]
                return OpenNebula::Error.new("Group name not defined")
            end

            if group_hash[:group_admin]
                if group_hash[:group_admin][:name] && !group_hash[:group_admin][:password]
                    error_msg = "Admin user password not defined"
                    return OpenNebula::Error.new(error_msg)
                end
            end

            # Allocate group
            rc = self.allocate(group_hash[:name])
            return rc if OpenNebula.is_error?(rc)

            # Handle resource providers
            group_hash[:resource_providers].each { |rp|
                next if rp[:zone_id].nil? && rp[:cluster_id].nil?

                if rp[:cluster_id].class == String && rp[:cluster_id] == "ALL"
                    add_provider(rp[:zone_id],ALL_CLUSTERS_IN_ZONE)
                else
                    add_provider(rp[:zone_id],rp[:cluster_id])
                end
            } if !group_hash[:resource_providers].nil?

            # Set group ACLs to create resources
            rc, msg = create_default_acls(group_hash[:resources])

            if OpenNebula.is_error?(rc)
                self.delete
                error_msg =  "Error creating group ACL's: #{rc.message}"
                return OpenNebula::Error.new(error_msg)
            end

            # Set group ACLs to share resources
            if group_hash[:shared_resources]
                acls = Array.new
                acls << "@#{self.id} #{group_hash[:shared_resources]}/@#{self.id} USE"

                rc, msg = create_group_acls(acls)

                if OpenNebula.is_error?(rc)
                    self.delete
                    error_msg =  "Error creating group ACL's: #{rc.message}"
                    return OpenNebula::Error.new(error_msg)
                end
            end

            # Create associated group admin if needed
            rc = create_admin_user(group_hash)

            if OpenNebula.is_error?(rc)
                self.delete
                error_msg =  "Error creating admin user: #{rc.message}"
                return OpenNebula::Error.new(error_msg)
            end

            str = ""
            update = false

            # Add Sunstone views for the group
            if group_hash[:views]
                str += "SUNSTONE_VIEWS=\"#{group_hash[:views].join(",")}\"\n"
                update = true
            end

            # Add Sunstone views for the group
            if group_hash[:default_view]
                str += "DEFAULT_VIEW=\"#{group_hash[:default_view]}\"\n"
                update = true
            end

            if update
                self.update(str, true)
            end

            return 0
        end

        # Allocates a new Group in OpenNebula
        #
        # +groupname+ A string containing the name of the Group.
        def allocate(groupname)
            super(GROUP_METHODS[:allocate], groupname)
        end

        # Replaces the template contents
        #
        # @param new_template [String] New template contents
        # @param append [true, false] True to append new attributes instead of
        #   replace the whole template
        #
        # @return [nil, OpenNebula::Error] nil in case of success, Error
        #   otherwise
        def update(new_template=nil, append=false)
            super(GROUP_METHODS[:update], new_template, append ? 1 : 0)
        end

        # Deletes the Group
        def delete()
            super(GROUP_METHODS[:delete])
        end

        # Sets the group quota limits
        # @param quota [String] a template (XML or txt) with the new quota limits
        #
        # @return [nil, OpenNebula::Error] nil in case of success, Error
        #   otherwise
        def set_quota(quota)
            return Error.new('ID not defined') if !@pe_id

            rc = @client.call(GROUP_METHODS[:quota],@pe_id, quota)
            rc = nil if !OpenNebula.is_error?(rc)

            return rc
        end

        # Adds a resource provider to this group
        # @param zone_id [Integer] Zone ID
        # @param cluster_id [Integer] Cluster ID
        #
        # @return [nil, OpenNebula::Error] nil in case of success, Error
        #   otherwise
        def add_provider(zone_id, cluster_id)
            return call(GROUP_METHODS[:add_provider], @pe_id, zone_id.to_i, cluster_id.to_i)
        end

        # Deletes a resource provider from this group
        # @param zone_id [Integer] Zone ID
        # @param cluster_id [Integer] Cluster ID
        #
        # @return [nil, OpenNebula::Error] nil in case of success, Error
        #   otherwise
        def del_provider(zone_id, cluster_id)
            return call(GROUP_METHODS[:del_provider], @pe_id, zone_id.to_i, cluster_id.to_i)
        end

        # ---------------------------------------------------------------------
        # Helpers to get information
        # ---------------------------------------------------------------------

        # Returns whether or not the user with id 'uid' is part of this group
        def contains(uid)
            #This doesn't work in ruby 1.8.5
            #return self["USERS/ID[.=#{uid}]"] != nil

            id_array = retrieve_elements('USERS/ID')
            return id_array != nil && id_array.include?(uid.to_s)
        end

        # Returns an array with the numeric user ids
        def user_ids
            array = Array.new

            self.each("USERS/ID") do |id|
                array << id.text.to_i
            end

            return array
        end

        private
        #######################################################################
        #######################################################################
        # Creates an acl array of acl strings. Returns true or error and
        # a qrray with the new acl ids
        def create_group_acls(acls)
            acls_ids = Array.new

            acls.each{|rule|

                acl = OpenNebula::Acl.new(OpenNebula::Acl.build_xml,@client)

                rule_ast = "#{rule} *" #Add all zone id's

                parsed_acl = OpenNebula::Acl.parse_rule(rule_ast)

                return parsed_acl, [] if OpenNebula.is_error?(parsed_acl)

                rc  = acl.allocate(*parsed_acl)

                return rc, "" if OpenNebula.is_error?(rc)

                acls_ids << acl.id
            }

            return true, acls_ids
        end

        def create_default_acls(resources=nil)
            resources = GROUP_DEFAULT_ACLS if !resources

            acls = Array.new
            acls << "@#{self.id} #{resources}/* CREATE"

            create_group_acls(acls)
        end

        # Creates a group admin and user based on the group definition hash
        # @param gdef [Hash] keys are ruby sumbols
        #     gdef[:group_admin] the group admin hash
        #     gdef[:group_admin][:name] username for group admin
        #     gdef[:group_admin][:password] password for group admin
        #     gdef[:group_admin][:auth_driver] auth driver for group admin
        #     gdef[:group_admin][:resources] resources that group admin manage
        #     gdef[:group_admin][:manage_resources] whether group admin manages
        #                                           group users
        #     gdef[:resources] resources that group users manage
        #
        # @return [nil, OpenNebula::Error] nil in case of success, Error
        def create_admin_user(gdef)

            return nil if gdef[:group_admin].nil? || gdef[:group_admin][:name].nil?

            # Create group admin
            uadmin  = gdef[:group_admin][:name]
            upasswd = gdef[:group_admin][:password]
            udriver = gdef[:group_admin][:auth_driver]

            if !uadmin.nil? && !upasswd.nil?

                group_admin = OpenNebula::User.new(OpenNebula::User.build_xml,
                                                   @client)

                if udriver
                    rc = group_admin.allocate(uadmin, upasswd, udriver)
                else
                    rc = group_admin.allocate(uadmin, upasswd)
                end

                if OpenNebula.is_error?(rc)
                    return rc
                end
            end

            # Set admin user groups to self
            rc = group_admin.chgrp(self.id)

            if OpenNebula.is_error?(rc)
                group_admin.delete
                return rc
            end

            # Set the default admin view to vdcadmin
            group_admin.update("DEFAULT_VIEW=#{GROUP_ADMIN_SUNSTONE_VIEWS}", true)

            #Create admin group acls
            acls = Array.new

            acls_str = (gdef[:group_admin][:resources] || \
                        gdef[:resources] || GROUP_DEFAULT_ACLS)

            manage_users = gdef[:group_admin][:manage_users] || "YES"

            if manage_users.upcase == "YES"
                acls << "##{group_admin.id} USER/@#{self.id} CREATE+USE+MANAGE+ADMIN"
            end

            acls << "##{group_admin.id} #{acls_str}/@#{self.id} " +
                    "CREATE+USE+MANAGE"

            rc, tmp = create_group_acls(acls)

            if OpenNebula.is_error?(rc)
                group_admin.delete
                return rc
            end

            #Set Sunstone Views for the group
            gtmpl =  "GROUP_ADMINS=#{gdef[:group_admin][:name]}\n"
            gtmpl << "GROUP_ADMIN_VIEWS=#{GROUP_ADMIN_SUNSTONE_VIEWS}\n"

            self.update(gtmpl, true)

            return nil
        end
    end
end


text:
package org.apache.geronimo.deployment.tools;

import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.io.InputStream;
import javax.enterprise.deploy.shared.ModuleType;
import javax.enterprise.deploy.model.DDBeanRoot;

import org.apache.geronimo.deployment.tools.loader.ClientDeployable;
import org.apache.geronimo.kernel.osgi.MockBundle;
import org.osgi.framework.Bundle;
import junit.framework.TestCase;

/**
 *
 *
 * @version $Rev$ $Date$
 */
public class ClientDeployableTest extends TestCase {
    private ClassLoader classLoader;

    public void testLoadClient() throws Exception {
        URL resource = classLoader.getResource("deployables/app-client1.jar");
        ClassLoader cl = new URLClassLoader(new URL[] {resource});
        Bundle bundle = new MockBundle(cl, resource.toString(), 0L);
        ClientDeployable deployable = new ClientDeployable(bundle);
        assertEquals(ModuleType.CAR, deployable.getType());
        Set entrySet = new HashSet(Collections.list(deployable.entries()));
        Set resultSet = new HashSet();
        resultSet.add("META-INF/");
        resultSet.add("META-INF/MANIFEST.MF");
        resultSet.add("META-INF/application-client.xml");
        resultSet.add("Main.java");
        resultSet.add("Main.class");
        //TODO implement getEntryPaths, reenable this check
//        assertEquals(resultSet, entrySet);
        InputStream entry = deployable.getEntry("META-INF/application-client.xml");
        assertNotNull(entry);
        entry.close();
        Class main = deployable.getClassFromScope("Main");
        assertEquals("Main", main.getName());

        DDBeanRoot root = deployable.getDDBeanRoot();
        assertNotNull(root);
        assertEquals(ModuleType.CAR, root.getType());
        assertEquals(deployable, root.getDeployableObject());
    }

    protected void setUp() throws Exception {
        classLoader = Thread.currentThread().getContextClassLoader();
    }
}


text:
require 'test/unit'
require 'tempfile'

class TestAutoload < Test::Unit::TestCase
  def test_autoload_so
    # Date is always available, unless excluded intentionally.
    assert_in_out_err([], <<-INPUT, [], [])
    autoload :Date, "date"
    begin Date; rescue LoadError; end
    INPUT
  end

  def test_non_realpath_in_loadpath
    require 'tmpdir'
    tmpdir = Dir.mktmpdir('autoload')
    tmpdirs = [tmpdir]
    tmpdirs.unshift(tmpdir + '/foo')
    Dir.mkdir(tmpdirs[0])
    tmpfiles = [tmpdir + '/foo.rb', tmpdir + '/foo/bar.rb']
    open(tmpfiles[0] , 'w') do |f|
      f.puts <<-INPUT
$:.unshift(File.expand_path('..', __FILE__)+'/./foo')
module Foo
  autoload :Bar, 'bar'
end
p Foo::Bar
      INPUT
    end
    open(tmpfiles[1], 'w') do |f|
      f.puts 'class Foo::Bar; end'
    end
    assert_in_out_err([tmpfiles[0]], "", ["Foo::Bar"], [])
  ensure
    File.unlink(*tmpfiles) rescue nil if tmpfiles
    tmpdirs.each {|dir| Dir.rmdir(dir)}
  end

  def test_autoload_p
    bug4565 = '[ruby-core:35679]'

    require 'tmpdir'
    Dir.mktmpdir('autoload') {|tmpdir|
      tmpfile = tmpdir + '/foo.rb'
      tmpfile2 = tmpdir + '/bar.rb'
      a = Module.new do
        autoload :X, tmpfile
        autoload :Y, tmpfile2
      end
      b = Module.new do
        include a
      end
      assert_equal(true, a.const_defined?(:X))
      assert_equal(true, b.const_defined?(:X))
      assert_equal(tmpfile, a.autoload?(:X), bug4565)
      assert_equal(tmpfile, b.autoload?(:X), bug4565)
      assert_equal(tmpfile, a.autoload?(:X, false))
      assert_equal(tmpfile, a.autoload?(:X, nil))
      assert_nil(b.autoload?(:X, false))
      assert_nil(b.autoload?(:X, nil))
      assert_equal(true, a.const_defined?("Y"))
      assert_equal(true, b.const_defined?("Y"))
      assert_equal(tmpfile2, a.autoload?("Y"))
      assert_equal(tmpfile2, b.autoload?("Y"))
    }
  end

  def test_autoload_with_unqualified_file_name # [ruby-core:69206]
    lp = $LOAD_PATH.dup
    lf = $LOADED_FEATURES.dup

    Dir.mktmpdir('autoload') { |tmpdir|
      $LOAD_PATH << tmpdir

      Dir.chdir(tmpdir) do
        eval <<-END
          class ::Object
            module A
              autoload :C, 'test-ruby-core-69206'
            end
          end
        END

        File.write("test-ruby-core-69206.rb", 'module A; class C; end; end')
        assert_kind_of Class, ::A::C
      end
    }
  ensure
    $LOAD_PATH.replace lp
    $LOADED_FEATURES.replace lf
    Object.send(:remove_const, :A) if Object.const_defined?(:A)
  end

  def test_require_explicit
    Tempfile.create(['autoload', '.rb']) {|file|
      file.puts 'class Object; AutoloadTest = 1; end'
      file.close
      add_autoload(file.path)
      begin
        assert_nothing_raised do
          assert(require file.path)
          assert_equal(1, ::AutoloadTest)
        end
      ensure
        remove_autoload_constant
      end
    }
  end

  def test_threaded_accessing_constant
    # Suppress "warning: loading in progress, circular require considered harmful"
    EnvUtil.default_warning {
      Tempfile.create(['autoload', '.rb']) {|file|
        file.puts 'sleep 0.5; class AutoloadTest; X = 1; end'
        file.close
        add_autoload(file.path)
        begin
          assert_nothing_raised do
            t1 = Thread.new { ::AutoloadTest::X }
            t2 = Thread.new { ::AutoloadTest::X }
            [t1, t2].each(&:join)
          end
        ensure
          remove_autoload_constant
        end
      }
    }
  end

  def test_threaded_accessing_inner_constant
    # Suppress "warning: loading in progress, circular require considered harmful"
    EnvUtil.default_warning {
      Tempfile.create(['autoload', '.rb']) {|file|
        file.puts 'class AutoloadTest; sleep 0.5; X = 1; end'
        file.close
        add_autoload(file.path)
        begin
          assert_nothing_raised do
            t1 = Thread.new { ::AutoloadTest::X }
            t2 = Thread.new { ::AutoloadTest::X }
            [t1, t2].each(&:join)
          end
        ensure
          remove_autoload_constant
        end
      }
    }
  end

  def test_nameerror_when_autoload_did_not_define_the_constant
    Tempfile.create(['autoload', '.rb']) {|file|
      file.puts ''
      file.close
      add_autoload(file.path)
      begin
        assert_raise(NameError) do
          AutoloadTest
        end
      ensure
        remove_autoload_constant
      end
    }
  end

  def test_override_autoload
    Tempfile.create(['autoload', '.rb']) {|file|
      file.puts ''
      file.close
      add_autoload(file.path)
      begin
        eval %q(class AutoloadTest; end)
        assert_equal(Class, AutoloadTest.class)
      ensure
        remove_autoload_constant
      end
    }
  end

  def test_override_while_autoloading
    Tempfile.create(['autoload', '.rb']) {|file|
      file.puts 'class AutoloadTest; sleep 0.5; end'
      file.close
      add_autoload(file.path)
      begin
        # while autoloading...
        t = Thread.new { AutoloadTest }
        sleep 0.1
        # override it
        EnvUtil.suppress_warning {
          eval %q(AutoloadTest = 1)
        }
        t.join
        assert_equal(1, AutoloadTest)
      ensure
        remove_autoload_constant
      end
    }
  end

  def ruby_impl_require
    Kernel.module_eval do
      alias old_require require
    end
    called_with = []
    Kernel.send :define_method, :require do |path|
      called_with << path
      old_require path
    end
    yield called_with
  ensure
    Kernel.module_eval do
      undef require
      alias require old_require
      undef old_require
    end
  end

  def test_require_implemented_in_ruby_is_called
    ruby_impl_require do |called_with|
      Tempfile.create(['autoload', '.rb']) {|file|
        file.puts 'class AutoloadTest; end'
        file.close
        add_autoload(file.path)
        begin
          assert(Object::AutoloadTest)
        ensure
          remove_autoload_constant
        end
        assert_equal [file.path], called_with
      }
    end
  end

  def test_autoload_while_autoloading
    ruby_impl_require do |called_with|
      Tempfile.create(%w(a .rb)) do |a|
        Tempfile.create(%w(b .rb)) do |b|
          a.puts "require '#{b.path}'; class AutoloadTest; end"
          b.puts "class AutoloadTest; module B; end; end"
          [a, b].each(&:flush)
          add_autoload(a.path)
          begin
            assert(Object::AutoloadTest)
          ensure
            remove_autoload_constant
          end
          assert_equal [a.path, b.path], called_with
        end
      end
    end
  end

  def test_bug_13526
    script = File.join(__dir__, 'bug-13526.rb')
    assert_ruby_status([script], '', '[ruby-core:81016] [Bug #13526]')
  end

  def test_autoload_private_constant
    Dir.mktmpdir('autoload') do |tmpdir|
      File.write(tmpdir+"/test-bug-14469.rb", "#{<<~"begin;"}\n#{<<~'end;'}")
      begin;
        class AutoloadTest
          ZZZ = :ZZZ
          private_constant :ZZZ
        end
      end;
      assert_separately(%W[-I #{tmpdir}], "#{<<-"begin;"}\n#{<<-'end;'}")
      bug = '[ruby-core:85516] [Bug #14469]'
      begin;
        class AutoloadTest
          autoload :ZZZ, "test-bug-14469.rb"
        end
        assert_raise(NameError, bug) {AutoloadTest::ZZZ}
      end;
    end
  end

  def test_autoload_deprecate_constant
    Dir.mktmpdir('autoload') do |tmpdir|
      File.write(tmpdir+"/test-bug-14469.rb", "#{<<~"begin;"}\n#{<<~'end;'}")
      begin;
        class AutoloadTest
          ZZZ = :ZZZ
          deprecate_constant :ZZZ
        end
      end;
      assert_separately(%W[-I #{tmpdir}], "#{<<-"begin;"}\n#{<<-'end;'}")
      bug = '[ruby-core:85516] [Bug #14469]'
      begin;
        class AutoloadTest
          autoload :ZZZ, "test-bug-14469.rb"
        end
        assert_warning(/ZZZ is deprecated/, bug) {AutoloadTest::ZZZ}
      end;
    end
  end

  def test_autoload_private_constant_before_autoload
    Dir.mktmpdir('autoload') do |tmpdir|
      File.write(tmpdir+"/test-bug-11055.rb", "#{<<~"begin;"}\n#{<<~'end;'}")
      begin;
        class AutoloadTest
          ZZZ = :ZZZ
        end
      end;
      assert_separately(%W[-I #{tmpdir}], "#{<<-"begin;"}\n#{<<-'end;'}")
      bug = '[Bug #11055]'
      begin;
        class AutoloadTest
          autoload :ZZZ, "test-bug-11055.rb"
          private_constant :ZZZ
          ZZZ
        end
        assert_raise(NameError, bug) {AutoloadTest::ZZZ}
      end;
      assert_separately(%W[-I #{tmpdir}], "#{<<-"begin;"}\n#{<<-'end;'}")
      bug = '[Bug #11055]'
      begin;
        class AutoloadTest
          autoload :ZZZ, "test-bug-11055.rb"
          private_constant :ZZZ
        end
        assert_raise(NameError, bug) {AutoloadTest::ZZZ}
      end;
    end
  end

  def test_autoload_deprecate_constant_before_autoload
    Dir.mktmpdir('autoload') do |tmpdir|
      File.write(tmpdir+"/test-bug-11055.rb", "#{<<~"begin;"}\n#{<<~'end;'}")
      begin;
        class AutoloadTest
          ZZZ = :ZZZ
        end
      end;
      assert_separately(%W[-I #{tmpdir}], "#{<<-"begin;"}\n#{<<-'end;'}")
      bug = '[Bug #11055]'
      begin;
        class AutoloadTest
          autoload :ZZZ, "test-bug-11055.rb"
          deprecate_constant :ZZZ
        end
        assert_warning(/ZZZ is deprecated/, bug) {class AutoloadTest; ZZZ; end}
        assert_warning(/ZZZ is deprecated/, bug) {AutoloadTest::ZZZ}
      end;
      assert_separately(%W[-I #{tmpdir}], "#{<<-"begin;"}\n#{<<-'end;'}")
      bug = '[Bug #11055]'
      begin;
        class AutoloadTest
          autoload :ZZZ, "test-bug-11055.rb"
          deprecate_constant :ZZZ
        end
        assert_warning(/ZZZ is deprecated/, bug) {AutoloadTest::ZZZ}
      end;
    end
  end

  def test_autoload_fork
    EnvUtil.default_warning do
      Tempfile.create(['autoload', '.rb']) {|file|
        file.puts 'sleep 0.3; class AutoloadTest; end'
        file.close
        add_autoload(file.path)
        begin
          thrs = []
          3.times do
            thrs << Thread.new { AutoloadTest && nil }
            thrs << Thread.new { fork { AutoloadTest } }
          end
          thrs.each(&:join)
          thrs.each do |th|
            pid = th.value or next
            _, status = Process.waitpid2(pid)
            assert_predicate status, :success?
          end
        ensure
          remove_autoload_constant
          assert_nil $!, '[ruby-core:86410] [Bug #14634]'
        end
      }
    end
  end if Process.respond_to?(:fork)

  def test_autoload_same_file
    Dir.mktmpdir('autoload') do |tmpdir|
      File.write("#{tmpdir}/test-bug-14742.rb", "#{<<~'begin;'}\n#{<<~'end;'}")
      begin;
        module Foo; end
        module Bar; end
      end;
      3.times do # timing-dependent, needs a few times to hit [Bug #14742]
        assert_separately(%W[-I #{tmpdir}], "#{<<-'begin;'}\n#{<<-'end;'}")
        begin;
          autoload :Foo, 'test-bug-14742'
          autoload :Bar, 'test-bug-14742'
          t1 = Thread.new do Foo end
          t2 = Thread.new do Bar end
          t1.join
          t2.join
          bug = '[ruby-core:86935] [Bug #14742]'
          assert_instance_of Module, t1.value, bug
          assert_instance_of Module, t2.value, bug
        end;
      end
    end
  end

  def test_autoload_same_file_with_raise
    Dir.mktmpdir('autoload') do |tmpdir|
      File.write("#{tmpdir}/test-bug-16177.rb", "#{<<~'begin;'}\n#{<<~'end;'}")
      begin;
        raise '[ruby-core:95055] [Bug #16177]'
      end;
      assert_raise(RuntimeError, '[ruby-core:95055] [Bug #16177]') do
        assert_separately(%W[-I #{tmpdir}], "#{<<-'begin;'}\n#{<<-'end;'}")
        begin;
          autoload :Foo, 'test-bug-16177'
          autoload :Bar, 'test-bug-16177'
          t1 = Thread.new do Foo end
          t2 = Thread.new do Bar end
          t1.join
          t2.join
        end;
      end
    end
  end

  def test_no_leak
    assert_no_memory_leak([], '', <<~'end;', 'many autoloads', timeout: 60)
      200000.times do |i|
        m = Module.new
        m.instance_eval do
          autoload :Foo, 'x'
          autoload :Bar, i.to_s
        end
      end
    end;
  end

  def add_autoload(path)
    (@autoload_paths ||= []) << path
    ::Object.class_eval {autoload(:AutoloadTest, path)}
  end

  def remove_autoload_constant
    $".replace($" - @autoload_paths)
    ::Object.class_eval {remove_const(:AutoloadTest)}
  end
end


text:
var redis = require('redis');
var Lab = require('lab');
var describe = Lab.experiment;
var it = Lab.test;
var expect = Lab.expect;
var before = Lab.before;
var after = Lab.after;
var redisTypes = require('../index')({
  redisClient: require('redis').createClient()
});
var RedisKey = redisTypes.Key;
var createCount = require('callback-count');

describe('instanciating the model', function () {
  it('should throw an error if no redis client is provided', function (done) {
    var errorCaught = false;
    try {
      var t = require('../index')();
    } catch (err) {
      errorCaught = true;
      expect(err).to.be.okay;
    }
    expect(errorCaught).to.equal(true);
    done()
  });
});

describe('create RedisKey', function() {
  it('should require a key', function(done) {
    try {
      new RedisKey();
    }
    catch (err) {
      expect(err).to.be.instanceof(Error);
      expect(err.message).to.equal('key is required');
      done();
    }
  });
});

describe('RedisKey DEL', function() {
  before(function (done) {
    this.key = 'key';
    this.redis = redis.createClient();
    this.redis.set(this.key, 'value', done);
  });
  after(function (done) {
    this.redis.flushall(done);
    delete this.key;
    delete this.redis;
  });
  it('should delete a redis key', function (done) {
    var redis = this.redis;
    var key = this.key;
    var redisKey = new RedisKey(key);
    redisKey.del(function (err) {
      expect(err).to.not.exist;
      redis.exists(key, function (err, exists) {
        expect(err).to.not.exist;
        expect(exists).to.equal(0);
        done();
      });
    });
  });
});

describe('RedisKey DUMP', function() {
  before(function (done) {
    this.key = 'key';
    this.redis = redis.createClient();
    this.redis.set(this.key, 'value', done);
  });
  after(function (done) {
    this.redis.flushall(done);
    delete this.key;
    delete this.redis;
  });
  it('should return the serialized value of a key', function (done) {
    var redis = this.redis;
    var key = this.key;
    var redisKey = new RedisKey(key);
    redisKey.dump(function (err, val1) {
      expect(err).to.not.exist;
      redis.dump(key, function (err, val2) {
        expect(err).to.not.exist;
        expect(val1).to.equal(val2);
        done();
      });
    });
  });
});

describe('RedisKey EXISTS', function() {
  before(function (done) {
    this.key = 'key';
    this.redis = redis.createClient();
    this.redis.set(this.key, 'value', done);
  });
  after(function (done) {
    this.redis.flushall(done);
    delete this.key;
    delete this.redis;
  });
  it('should return existance for a key', function (done) {
    var redis = this.redis;
    var key = this.key;
    var redisKey = new RedisKey(key);
    redisKey.exists(function (err, val1) {
      expect(err).to.not.exist;
      redis.exists(key, function (err, val2) {
        expect(err).to.not.exist;
        expect(val1).to.equal(val2);
        done();
      });
    });
  });
});

describe('RedisKey EXPIRE', function() {
  before(function (done) {
    this.key = 'key';
    this.redis = redis.createClient();
    this.redis.set(this.key, 'value', done);
  });
  after(function (done) {
    this.redis.flushall(done);
    delete this.key;
    delete this.redis;
  });
  it('should set the ttl for a key', {timeout:3000}, function (done) {
    var redis = this.redis;
    var key = this.key;
    var redisKey = new RedisKey(key);
    redisKey.expire(1, function (err) {
      expect(err).to.not.exist;
      redis.ttl(key, function (err, ttl) {
        expect(err).to.not.exist;
        expect(ttl).to.be.above(-1);
        done();
      });
    });
  });
});

describe('RedisKey EXPIREAT', function() {
  before(function (done) {
    this.key = 'key';
    this.redis = redis.createClient();
    this.redis.set(this.key, 'value', done);
  });
  after(function (done) {
    this.redis.flushall(done);
    delete this.key;
    delete this.redis;
  });
  it('should set the ttl (by date) for a key', function (done) {
    var redis = this.redis;
    var key = this.key;
    var redisKey = new RedisKey(key);
    var unixDate = Math.round(Date.now()/1000)+1;
    redisKey.expireat(unixDate, function (err) {
      expect(err).to.not.exist;
      redis.ttl(key, function (err, ttl) {
        expect(err).to.not.exist;
        expect(ttl).to.be.above(-1);
        done();
      });
    });
  });
});

describe('RedisKey GET', function() {
  before(function (done) {
    this.key = 'key';
    this.redis = redis.createClient();
    done();
  });
  after(function (done) {
    this.redis.flushall(done);
    delete this.key;
    delete this.redis;
  });
  it('should get a redis key', function (done) {
    var key = this.key;
    var redisKey = new RedisKey(key);
    var value = 'someAwesomeValue';
    redisKey.set(value, function (err) {
      expect(err).to.not.exist;
      redisKey.get(function (err, setValue) {
        expect(err).to.not.exist;
        expect(setValue).to.equal(value);
        done();
      });
    });
  });
});

// describe('RedisKey MOVE', function() {
//   before(function (done) {
//     this.key = 'key';
//     this.val = 'value';
//     this.redis = redis.createClient();
//     this.redis2 = redis.createClient(6380);
//     this.redis.set(this.key, this.val, done);
//   });
//   after(function (done) {
//     this.redis.flushall(done);
//     delete this.key;
//     delete this.redis;
//     delete this.redis2;
//     delete this.newKey;
//     delete this.val;
//   });
//   it('should move a key to a new key', function (done) {
//     var redis = this.redis;
//     var key = this.key;
//     var newKey = this.newKey;
//     var redisKey = new RedisKey(key);
//     redisKey.move('127.0.0.1:6380', function (err) {
//       expect(err).to.not.exist;
//       var count = createCount(2, done);
//       redis2.exists(key, function (err, exists) {
//         if (err) return count.next(err);
//         expect(exists).to.equal(0);
//         count.next();
//       });
//       redis.get(key, function (err, val) {
//         if (err) return count.next(err);
//         expect(val).to.equal(this.val);
//         count.next();
//       });
//     });
//   });
// });

describe('RedisKey PERSIST', function() {
  before(function (done) {
    this.key = 'key';
    this.redis = redis.createClient();
    this.redis.set(this.key, 'value', done);
  });
  after(function (done) {
    this.redis.flushall(done);
    delete this.key;
    delete this.redis;
  });
  it('should return the serialized value of a key', function (done) {
    var redis = this.redis;
    var key = this.key;
    var redisKey = new RedisKey(key);
    var expireTime = 100;
    redisKey.pexpire(100, function (err) {
      expect(err).to.not.exist;
      redisKey.persist(function (err) {
        expect(err).to.not.exist;
        redis.pttl(key, function (err, exists) {
          expect(err).to.not.exist;
          expect(exists).to.equal(-1);
          done();
        });
      });
    });
  });
});

describe('RedisKey PEXPIRE', function() {
  before(function (done) {
    this.key = 'key';
    this.redis = redis.createClient();
    this.redis.set(this.key, 'value', done);
  });
  after(function (done) {
    this.redis.flushall(done);
    delete this.key;
    delete this.redis;
  });
  it('should set the ttl for a key', {timeout:3000}, function (done) {
    var redis = this.redis;
    var key = this.key;
    var redisKey = new RedisKey(key);
    redisKey.pexpire(1000, function (err) {
      expect(err).to.not.exist;
      redis.pttl(key, function (err, ttl) {
        expect(err).to.not.exist;
        expect(ttl).to.be.above(-1);
        done();
      });
    });
  });
});

describe('RedisKey EXPIREAT', function() {
  before(function (done) {
    this.key = 'key';
    this.redis = redis.createClient();
    this.redis.set(this.key, 'value', done);
  });
  after(function (done) {
    this.redis.flushall(done);
    delete this.key;
    delete this.redis;
  });
  it('should set the ttl (by date) for a key', function (done) {
    var redis = this.redis;
    var key = this.key;
    var redisKey = new RedisKey(key);
    var unixDate = Date.now() + 1*1000;
    redisKey.pexpireat(unixDate, function (err) {
      expect(err).to.not.exist;
      redis.pttl(key, function (err, ttl) {
        expect(err).to.not.exist;
        expect(ttl).to.be.above(-1);
        done();
      });
    });
  });
});

describe('RedisKey PTTL', function() {
  before(function (done) {
    this.key = 'key';
    this.redis = redis.createClient();
    this.redis.set(this.key, 'value', done);
  });
  after(function (done) {
    this.redis.flushall(done);
    delete this.key;
    delete this.redis;
  });
  it('should set the ttl (by date) for a key', function (done) {
    var redis = this.redis;
    var key = this.key;
    var redisKey = new RedisKey(key);
    redisKey.pexpire(1000, function (err) {
      expect(err).to.not.exist;
      redisKey.pttl(function (err, ttl) {
        expect(err).to.not.exist;
        expect(ttl).to.be.above(-1);
        done();
      });
    });
  });
});

describe('RedisKey RENAME', function() {
  before(function (done) {
    this.key = 'key';
    this.val = 'value';
    this.newKey = 'newkey';
    this.redis = redis.createClient();
    this.redis.set(this.key, this.val, done);
  });
  after(function (done) {
    this.redis.flushall(done);
    delete this.key;
    delete this.redis;
    delete this.newKey;
    delete this.val;
  });
  it('should rename a key to a new key', function (done) {
    var redis = this.redis;
    var key = this.key;
    var newKey = this.newKey;
    var val = this.val;
    var redisKey = new RedisKey(key);
    redisKey.rename(newKey, function (err) {
      expect(err).to.not.exist;
      var count = createCount(2, done);
      redis.exists(key, function (err, exists) {
        expect(err).to.not.exist;
        expect(exists).to.equal(0);
        count.next();
      });
      redis.get(newKey, function (err, currentVal) {
        expect(err).to.not.exist;
        expect(currentVal).to.equal(val);
        count.next();
      });
    });
  });
});

describe('RedisKey RENAMENX', function() {
  before(function (done) {
    this.key = 'key';
    this.val = 'value';
    this.newKey = 'newkey';
    this.collisionKey = 'collisionkey';
    this.redis = redis.createClient();
    this.redis.set(this.key, this.val, done);
  });
  after(function (done) {
    this.redis.flushall(done);
    delete this.key;
    delete this.redis;
    delete this.newKey;
    delete this.collisionKey;
    delete this.val;
  });
  it('should rename a key to a new key if new key dne', function (done) {
    var redis = this.redis;
    var key = this.key;
    var newKey = this.newKey;
    var val = this.val;
    var redisKey = new RedisKey(key);
    redisKey.rename(newKey, function (err) {
      expect(err).to.not.exist;
      var count = createCount(2, done);
      redis.exists(key, function (err, exists) {
        expect(err).to.not.exist;
        expect(exists).to.equal(0);
        count.next();
      });
      redis.get(newKey, function (err, currentVal) {
        expect(err).to.not.exist;
        expect(currentVal).to.equal(val);
        count.next();
      });
    });
  });
  it('should error if a key is renamed to a new key that already exists', function (done) {
    var redis = this.redis;
    var key = this.key;
    var newKey = this.collisionkey;
    var val = this.val;
    var redisKey = new RedisKey(key);
    redisKey.rename(newKey, function (err) {
      expect(err).to.exist;
      done();
    });
  });
});

describe('RedisKey RESTORE', function() {
  before(function (done) {
    var self = this;
    this.key = 'key';
    this.val = 'value';
    this.redis = redis.createClient();
    this.redis.set(this.key, this.val, function (err) {
      if (err) return done(err);
      self.redis.dump(self.key, function (err, dump) {
        if (err) return done(err);
        self.dump = dump;
        self.redis.del(self.key, function (err) {
          if (err) return done(err);
          done();
        });
      });
    });
  });
  after(function (done) {
    this.redis.flushall(done);
    delete this.key;
    delete this.redis;
    delete this.dump;
    delete this.val;
  });
  it('should return the serialized value of a key', function (done) {
    var self = this;
    var redisKey = new RedisKey(this.key);
    redisKey.restore(0, self.dump, function (err, val1) {
      // BUG with node_redis restore doesnt work
      // expect(err).to.not.exist;
      // redis.get(self.key, function (err, val) {
      //   expect(err).to.not.exist;
      //   expect(val).to.equal(self.val);
      //   done();
      // });
      done();
    });
  });
});

describe('RedisKey SET', function() {
  before(function (done) {
    this.key = 'key';
    this.redis = redis.createClient();
    done();
  });
  after(function (done) {
    this.redis.flushall(done);
    delete this.key;
    delete this.redis;
  });
  it('should create a redis key', function (done) {
    var redis = this.redis;
    var key = this.key;
    var redisKey = new RedisKey(key);
    var value = 'someAwesomeValue';
    redisKey.set(value, function (err) {
      expect(err).to.not.exist;
      redis.get(key, function (err, setValue) {
        expect(err).to.not.exist;
        expect(setValue).to.equal(value);
        done();
      });
    });
  });
});

describe('RedisKey SORT', function() {
  before(function (done) {
    this.key = 'key';
    this.redis = redis.createClient();
    var count = createCount(done);
    this.redis.rpush(this.key, 1, count.inc().next);
    this.redis.rpush(this.key, 2, count.inc().next);
    this.redis.rpush(this.key, 3, count.inc().next);
  });
  after(function (done) {
    this.redis.flushall(done);
    delete this.key;
    delete this.redis;
  });
  it('should return the serialized value of a key', function (done) {
    var redis = this.redis;
    var key = this.key;
    var redisKey = new RedisKey(key);
    redisKey.sort('DESC', function (err) {
      expect(err).to.not.exist;
      redis.lrange(key, 0, -1, function (err, vals) {
        expect(err).to.not.exist;
        expect(vals[0]).to.equal('1');
        expect(vals[1]).to.equal('2');
        expect(vals[2]).to.equal('3');
        done();
      });
    });
  });
});

describe('RedisKey TTL', function() {
  before(function (done) {
    this.key = 'key';
    this.redis = redis.createClient();
    var count = createCount(done);
    this.redis.set(this.key, 'val', count.inc().next);
    this.redis.expire(this.key, 1, count.inc().next);
  });
  after(function (done) {
    this.redis.flushall(done);
    delete this.key;
    delete this.redis;
  });
  it('should return the serialized value of a key', function (done) {
    var redis = this.redis;
    var key = this.key;
    var redisKey = new RedisKey(key);
    redisKey.ttl(function (err, ttl) {
      expect(err).to.not.exist;
      expect(ttl).to.be.above(-1);
      done();
    });
  });
});

describe('RedisKey TYPE', function() {
  before(function (done) {
    this.key = 'key';
    this.redis = redis.createClient();
    var count = createCount(done);
    this.redis.set(this.key, 'val', count.inc().next);
  });
  after(function (done) {
    this.redis.flushall(done);
    delete this.key;
    delete this.redis;
  });
  it('should return the serialized value of a key', function (done) {
    var redis = this.redis;
    var key = this.key;
    var redisKey = new RedisKey(key);
    redisKey.type(function (err, type) {
      expect(err).to.not.exist;
      expect(type).to.equal('string');
      done();
    });
  });
});


text:
package nl.rivm.cib.epidemes.geodb.jdbc;

import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.spatial.dialect.postgis.PostgisDialect;
import org.hibernate.type.StandardBasicTypes;

/**
 * {@link PostgisDialectExtended} follows example from
 * https://gist.github.com/geobabbler/bdc405c5d25ba2b45d81
 *
 * @version $Id$
 * @author Rick van Krevelen
 */
public class PostgisDialectExtended extends PostgisDialect
{
	/** the serialVersionUID */
	private static final long serialVersionUID = 1L;

	public PostgisDialectExtended()
	{
		super();
		registerFunction( "Transform", new StandardSQLFunction( "ST_Transform",
				StandardBasicTypes.STRING ) );
		registerFunction( "AsGeoJson", new StandardSQLFunction( "ST_AsGeoJson",
				StandardBasicTypes.STRING ) );
		registerFunction( "AsGml", new StandardSQLFunction( "ST_AsGml",
				StandardBasicTypes.STRING ) );
		registerFunction( "AsKml", new StandardSQLFunction( "ST_AsKml",
				StandardBasicTypes.STRING ) );
		registerFunction( "Srid", new StandardSQLFunction( "ST_Srid",
				StandardBasicTypes.INTEGER ) );
	}
}