text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>DbEnv::set_memory_init()</title>
    <link rel="stylesheet" href="apiReference.css" type="text/css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
    <link rel="start" href="index.html" title="Berkeley DB C++ API Reference" />
    <link rel="up" href="env.html" title="Chapter 5.  The DbEnv Handle" />
    <link rel="prev" href="envset_isalive.html" title="DbEnv::set_isalive()" />
    <link rel="next" href="envset_memory_max.html" title="DbEnv::set_memory_max()" />

Library Version 11.2.5.3

          DbEnv::set_memory_init()

          Prev
          Chapter 5.
                The DbEnv Handle

           Next

DbEnv::set_memory_init()

#include <db_cxx.h>

int
DbEnv::set_memory_init(DB_MEM_CONFIG type, u_int32_t count);

        This method sets the number of objects to allocate and initialize
        for a specified structure when an environment is created.  Doing
        this helps avoid memory contention after startup.  Using this
        method is optional; failure to use this method causes BDB to
        allocate a minimal number of structures that will grow dynamically.
        These structures are all allocated from the main environment
        region.  The amount of memory in this region can be set via the
	    DbEnv::set_memory_max()
        method.  If this method is not called then memory will be limited
        to the initial settings or by the (deprecated) set maximum
        interfaces.

         The database environment's initialization  may also be configured
         using the environment's DB_CONFIG file.  The syntax of the entry
         in that file is a single line with the string "set_memory_init",
         one or more whitespace characters, followed by the struct
         specification, more white space and the count to be allocated.
         Because the DB_CONFIG file is read when the database environment
         is opened, it will silently overrule configuration done before
         that time.

         The DbEnv::set_memory_init() method must
         be called prior to opening the database environment. It may be
         called as often as needed to set the different configurations.

Parameters

type

                The type parameter must be
                set to one of the following:

                        DB_MEM_LOCK

                        Initialize locks.  A thread uses this structure
                        to lock a page (or record for the QUEUE access
                        method) and hold it to the end of a transactions.

                        DB_MEM_LOCKOBJECT

                        Initialize lock objects.  For each page (or record) which
                        is locked in the system, a lock object will be allocated.

                        DB_MEM_LOCKER

                        Initialize lockers. Each thread which is active in a
                        transactional environment will use a locker structure
                        either for each transaction which is active, or for each
                        non-transactional cursor that is active.

                          DB_MEM_LOGID

                        Initialize the log fileid structures.  For each database handle
                        which is opened for writing in a transactional environment,
                        a log fileid structure is used.

                          DB_MEM_TRANSACTION

                        Initialize transaction structures.  Each active
                        transaction uses a transaction structure until it
                        either commits or aborts.

Note

                            Currently transaction structures are not
                            preallocated. This setting will be used to
                            preallocate memory and objects related to
                            transactions such as locker structures and
                            mutexes.

                          DB_MEM_THREAD

                        Initialize thread identification structures.  If thread
                        tracking is enabled then each active thread will use a
                        structure.  Note that since a thread does not signal the
                        BDB library that it will no longer be making calls, unused
                        structures may accumulate until a cleanup is triggered either
                        using a high water mark or by running
                        DbEnv::failchk().

count

                The count parameter
                sets the number of specified objects to initialize.

                The count specified for
                locks and lock objects should be at least 5 times the
                number of lock table partitions. You can examine the
                current number of lock table partitions configured for your
                environment using the
                DbEnv::get_lk_partitions()
                method.

Errors

                 The DbEnv::set_memory_init()

                method may fail and throw a DbException
                exception, encapsulating one of the following non-zero errors, or return one
                of the following non-zero errors:

EINVAL

                If the method was called after DbEnv::open()
                was called; or if an invalid flag value or parameter was specified.

Class

            DbEnv

See Also

             Database Environments and Related Methods

          Prev

            Up

           Next

          DbEnv::set_isalive()

            Home

           DbEnv::set_memory_max()


text:
title: "EMCF Family Forum"
venue: Riverside Centre
address: Riverside Court, Pride Park, Derby
postcode: 'DE24 8HY'
allday: false
description:
    Further information about the upcoming changes to EMCF
when: 2018-05-08
starttime: 1930
finishtime: 2130
category:
    Family forum
layout: event
---

redpajama_set_name: RedPajamaGithub


text:
package com.ibm.jaggr.core.impl.layer;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import com.ibm.jaggr.core.BadRequestException;
import com.ibm.jaggr.core.IAggregator;
import com.ibm.jaggr.core.cache.ICacheManager;
import com.ibm.jaggr.core.config.IConfig;
import com.ibm.jaggr.core.deps.ModuleDepInfo;
import com.ibm.jaggr.core.deps.ModuleDeps;
import com.ibm.jaggr.core.impl.config.ConfigImpl;
import com.ibm.jaggr.core.impl.layer.ModuleList.ModuleListEntry;
import com.ibm.jaggr.core.impl.transport.AbstractHttpTransport;
import com.ibm.jaggr.core.module.IModule;
import com.ibm.jaggr.core.module.ModuleSpecifier;
import com.ibm.jaggr.core.readers.ModuleBuildReader;
import com.ibm.jaggr.core.resource.IResource;
import com.ibm.jaggr.core.test.MockRequestedModuleNames;
import com.ibm.jaggr.core.test.TestUtils;
import com.ibm.jaggr.core.test.TestUtils.Ref;
import com.ibm.jaggr.core.transport.IHttpTransport;
import com.ibm.jaggr.core.util.BooleanTerm;
import com.ibm.jaggr.core.util.DependencyList;
import com.ibm.jaggr.core.util.Features;

import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

import javax.servlet.http.HttpServletRequest;

public class LayerImpl_getModulesTest {

	private IAggregator mockAggregator;
	private HttpServletRequest mockRequest;
	private Map<String, Object> requestAttributes;
	private Map<String, String[]> requestParams;
	private Features features;

	@Before
	public void setUp() throws Exception {
		requestAttributes = new HashMap<String, Object>();
		requestParams = new HashMap<String, String[]>();
		features = new Features();
		mockAggregator = TestUtils.createMockAggregator();
		mockRequest = TestUtils.createMockRequest(mockAggregator, requestAttributes, requestParams, null, null);
		EasyMock.replay(mockAggregator, mockRequest);
		requestAttributes.put(IHttpTransport.FEATUREMAP_REQATTRNAME, features);
	}

	@Test(expected=BadRequestException.class)
	public void testGetModules_nullRequestedModules() throws Exception {
		LayerImpl layer = new TestLayerImpl();
		layer.getModules(mockRequest);
	}

	@Test(expected=BadRequestException.class)
	public void testGetModules_emptyRequestedModules() throws Exception {
		// Empty requested modules
		LayerImpl layer = new TestLayerImpl();
		MockRequestedModuleNames names = new MockRequestedModuleNames();
		mockRequest.setAttribute(AbstractHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, names);
		layer.getModules(mockRequest);
	}

	@Test
	public void testGetModules_moduleListOnly() throws Exception {
		LayerImpl layer = new TestLayerImpl();
		MockRequestedModuleNames names = new MockRequestedModuleNames();
		names.setModules(Arrays.asList(new String[]{"module/a", "module/b"}));
		mockRequest.setAttribute(AbstractHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, names);
		ModuleList modules = layer.getModules(mockRequest);
		assertTrue(modules.getDependentFeatures().isEmpty());
		assertSame(modules, requestAttributes.get(LayerImpl.MODULE_FILES_PROPNAME));
		List<IModule> expected = makeModuleList("module/a", "module/b");
		assertEquals(expected, modules.getModules());
		for (ModuleListEntry entry : modules) {
			assertEquals(ModuleSpecifier.MODULES, entry.getSource());
		}
	}

	@Test
	public void testGetModules_moduleListWithScript() throws Exception {
		LayerImpl layer = new TestLayerImpl();
		MockRequestedModuleNames names = new MockRequestedModuleNames();
		names.setModules(Arrays.asList(new String[]{"module/a", "module/b"}));
		names.setScripts(Arrays.asList(new String[]{"script/a"}));
		mockRequest.setAttribute(AbstractHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, names);
		ModuleList modules = layer.getModules(mockRequest);
		assertTrue(modules.getDependentFeatures().isEmpty());
		assertSame(modules, requestAttributes.get(LayerImpl.MODULE_FILES_PROPNAME));
		List<IModule> expected = makeModuleList("module/a", "module/b","script/a");
		assertEquals(expected, modules.getModules());
		for (ModuleListEntry entry : modules) {
			if ("script/a".equals(entry.getModule().getModuleName())) {
				assertEquals(ModuleSpecifier.SCRIPTS, entry.getSource());
			} else {
				assertEquals(ModuleSpecifier.MODULES, entry.getSource());
			}
		}
	}

	@Test
	public void testGetModules_moduleList_with_serverExpandLayers() throws Exception {
		LayerImpl layer = EasyMock.createMockBuilder(TestLayerImpl.class)
			.addMockedMethod("newDependencyList", String.class, Iterable.class, IAggregator.class, Features.class, boolean.class, boolean.class, boolean.class)
			.createMock();
		MockRequestedModuleNames names = new MockRequestedModuleNames();
		names.setModules(Arrays.asList(new String[]{"module/a"}));
		mockRequest.setAttribute(AbstractHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, names);
		mockRequest.setAttribute(IHttpTransport.SERVEREXPANDLAYERS_REQATTRNAME, true);
		ModuleDeps depsExplicitDeps = new ModuleDeps();
		ModuleDeps depsExpandedDeps = new ModuleDeps();
		depsExplicitDeps.add("module/a", new ModuleDepInfo());
		depsExpandedDeps.add("dep/moduledep", new ModuleDepInfo());
		DependencyList depsDependencies = new DependencyList(depsExplicitDeps, depsExpandedDeps, new HashSet<String>(Arrays.asList("feature")));
		EasyMock.expect(layer.newDependencyList(
				EasyMock.eq(LayerImpl.DEPSOURCE_MODULEDEPS),
				EasyMock.eq(Arrays.asList(new String[]{"module/a"})),
				EasyMock.eq(mockAggregator),
				EasyMock.eq(features),
				EasyMock.eq(true),
				EasyMock.eq(false),
				EasyMock.eq(false)))
			.andReturn(depsDependencies).once();
		EasyMock.replay(layer);
		ModuleList modules = layer.getModules(mockRequest);
		EasyMock.verify(layer);
		assertEquals(new HashSet<String>(Arrays.asList("feature")), modules.getDependentFeatures());
		assertSame(modules, requestAttributes.get(LayerImpl.MODULE_FILES_PROPNAME));
		List<IModule> expected = makeModuleList("module/a", "dep/moduledep");
		assertEquals(expected, modules.getModules());
		for (ModuleListEntry entry : modules) {
			String moduleName = entry.getModule().getModuleName();
			if ("module/a".equals(moduleName)) {
				assertEquals(ModuleSpecifier.MODULES, entry.getSource());
			} else if ("dep/moduledep".equals(moduleName)) {
				assertEquals(ModuleSpecifier.LAYER, entry.getSource());
			} else {
				fail("unexpected entry " + moduleName);
			}
		}
	}

	@Test
	public void testGetModules_deps() throws Exception {
		LayerImpl layer = EasyMock.createMockBuilder(TestLayerImpl.class)
				.addMockedMethod("newDependencyList", String.class, Iterable.class, IAggregator.class, Features.class, boolean.class, boolean.class, boolean.class)
				.createMock();
		MockRequestedModuleNames names = new MockRequestedModuleNames();
		mockRequest.setAttribute(AbstractHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, names);
		names.setDeps(Arrays.asList(new String[]{"dep/a"}));
		ModuleDeps depsExplicitDeps = new ModuleDeps();
		ModuleDeps depsExpandedDeps = new ModuleDeps();
		depsExplicitDeps.add("dep/a", new ModuleDepInfo());
		depsExpandedDeps.add("dep/adep", new ModuleDepInfo());
		DependencyList depsDependencies = new DependencyList(depsExplicitDeps, depsExpandedDeps, new HashSet<String>(Arrays.asList("feature")));
		EasyMock.expect(layer.newDependencyList(
				EasyMock.eq(LayerImpl.DEPSOURCE_REQDEPS),
				EasyMock.eq(Arrays.asList(new String[]{"dep/a"})),
				EasyMock.eq(mockAggregator),
				EasyMock.eq(features),
				EasyMock.eq(true),
				EasyMock.eq(false),
				EasyMock.eq(false)))
			.andReturn(depsDependencies).once();
		EasyMock.replay(layer);

		ModuleList modules = layer.getModules(mockRequest);
		EasyMock.verify(layer);
		List<IModule> expected = makeModuleList("dep/a", "dep/adep");
		assertSame(modules, requestAttributes.get(LayerImpl.MODULE_FILES_PROPNAME));
		assertNull(requestAttributes.get(LayerImpl.EXPANDEDDEPS_PROPNAME));
		assertEquals(expected, modules.getModules());
		assertEquals(new HashSet<String>(Arrays.asList("dep/a")), modules.getRequiredModules());
		assertEquals(new HashSet<String>(Arrays.asList("feature")), modules.getDependentFeatures());
		assertEquals(ModuleSpecifier.LAYER, modules.get(0).getSource());
		assertEquals(ModuleSpecifier.LAYER, modules.get(1).getSource());
	}

	@Test
	public void testGetModules_depsAndPreloads() throws Exception {
		LayerImpl layer = EasyMock.createMockBuilder(TestLayerImpl.class)
				.addMockedMethod("newDependencyList", String.class, Iterable.class, IAggregator.class, Features.class, boolean.class, boolean.class, boolean.class)
				.createMock();
		MockRequestedModuleNames names = new MockRequestedModuleNames();
		mockRequest.setAttribute(AbstractHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, names);
		names.setDeps(Arrays.asList("dep/a"));
		names.setPreloads(Arrays.asList("preload/a"));

		ModuleDeps depsExplicitDeps = new ModuleDeps();
		ModuleDeps depsExpandedDeps = new ModuleDeps();
		depsExplicitDeps.add("dep/a", new ModuleDepInfo());
		depsExpandedDeps.add("dep/adep", new ModuleDepInfo());
		ModuleDeps preloadsExplicitDeps = new ModuleDeps();
		ModuleDeps preloadsExpandedDeps = new ModuleDeps();
		preloadsExplicitDeps.add("preload/a", new ModuleDepInfo());
		preloadsExpandedDeps.add("preload/adep", new ModuleDepInfo());
		DependencyList depsDependencies = new DependencyList(depsExplicitDeps, depsExpandedDeps, new HashSet<String>(Arrays.asList("feature1")));
		DependencyList preloadsDependencies = new DependencyList(preloadsExplicitDeps, preloadsExpandedDeps, new HashSet<String>(Arrays.asList("feature2")));

		EasyMock.expect(layer.newDependencyList(
				EasyMock.eq(LayerImpl.DEPSOURCE_REQDEPS),
				EasyMock.eq(Arrays.asList("dep/a")),
				EasyMock.eq(mockAggregator),
				EasyMock.eq(features),
				EasyMock.eq(true),
				EasyMock.eq(false),
				EasyMock.eq(false)))
			.andReturn(depsDependencies).once();

		EasyMock.expect(layer.newDependencyList(
				EasyMock.eq(LayerImpl.DEPSOURCE_REQPRELOADS),
				EasyMock.eq(Arrays.asList("preload/a")),
				EasyMock.eq(mockAggregator),
				EasyMock.eq(features),
				EasyMock.eq(true),
				EasyMock.eq(false),
				EasyMock.eq(false)))
			.andReturn(preloadsDependencies).once();
		EasyMock.replay(layer);

		ModuleList modules = layer.getModules(mockRequest);
		EasyMock.verify(layer);
		List<IModule> expected = makeModuleList("dep/a", "dep/adep", "preload/a", "preload/adep");
		assertEquals(expected, modules.getModules());
		assertSame(modules, requestAttributes.get(LayerImpl.MODULE_FILES_PROPNAME));
		assertNull(requestAttributes.get(LayerImpl.EXPANDEDDEPS_PROPNAME));
		assertEquals(new HashSet<String>(Arrays.asList("dep/a")), modules.getRequiredModules());
		assertEquals(new HashSet<String>(Arrays.asList("feature1", "feature2")), modules.getDependentFeatures());
		assertEquals(ModuleSpecifier.LAYER, modules.get(0).getSource());
		assertEquals(ModuleSpecifier.LAYER, modules.get(1).getSource());
		assertEquals(ModuleSpecifier.LAYER, modules.get(2).getSource());
		assertEquals(ModuleSpecifier.LAYER, modules.get(3).getSource());
	}

	@Test
	public void testGetModules_pluginDelegators() throws Exception {

		Ref<IConfig> configRef = new Ref<IConfig>(null);
		File tmpdir = new File(System.getProperty("user.dir"));
		mockAggregator = TestUtils.createMockAggregator(configRef, tmpdir);
		EasyMock.replay(mockAggregator);
		configRef.set(new ConfigImpl(mockAggregator, tmpdir.toURI(), "{textPluginDelegators:['js/css', 'dojo/text'], jsPluginDelegators:['dojo/i18n']}", true));
		mockRequest.setAttribute(IAggregator.AGGREGATOR_REQATTRNAME, mockAggregator);

		LayerImpl layer = EasyMock.createMockBuilder(TestLayerImpl.class)
				.addMockedMethod("newDependencyList", String.class, Iterable.class, IAggregator.class, Features.class, boolean.class, boolean.class, boolean.class)
				.createMock();
		MockRequestedModuleNames names = new MockRequestedModuleNames();
		mockRequest.setAttribute(AbstractHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, names);
		names.setDeps(Arrays.asList("dep/a"));
		names.setPreloads(Arrays.asList("preload/a"));

		ModuleDeps depsExplicitDeps = new ModuleDeps();
		ModuleDeps depsExpandedDeps = new ModuleDeps();
		depsExplicitDeps.add("dep/a", new ModuleDepInfo());
		depsExpandedDeps.add("dojo/text!dep/adep", new ModuleDepInfo());
		depsExpandedDeps.add("foo!dep/bdep", new ModuleDepInfo());
		ModuleDeps preloadsExplicitDeps = new ModuleDeps();
		ModuleDeps preloadsExpandedDeps = new ModuleDeps();
		preloadsExplicitDeps.add("preload/a", new ModuleDepInfo());
		preloadsExpandedDeps.add("js/css!preload/adep", new ModuleDepInfo());
		preloadsExpandedDeps.add("dojo/i18n!preload/nls/adep", new ModuleDepInfo());
		DependencyList depsDependencies = new DependencyList(depsExplicitDeps, depsExpandedDeps, new HashSet<String>(Arrays.asList("feature1")));
		DependencyList preloadsDependencies = new DependencyList(preloadsExplicitDeps, preloadsExpandedDeps, new HashSet<String>(Arrays.asList("feature2")));

		EasyMock.expect(layer.newDependencyList(
				EasyMock.eq(LayerImpl.DEPSOURCE_REQDEPS),
				EasyMock.eq(Arrays.asList("dep/a")),
				EasyMock.isA(IAggregator.class),
				EasyMock.eq(features),
				EasyMock.eq(true),
				EasyMock.eq(false),
				EasyMock.eq(false)))
			.andReturn(depsDependencies).once();

		EasyMock.expect(layer.newDependencyList(
				EasyMock.eq(LayerImpl.DEPSOURCE_REQPRELOADS),
				EasyMock.eq(Arrays.asList("preload/a")),
				EasyMock.isA(IAggregator.class),
				EasyMock.eq(features),
				EasyMock.eq(true),
				EasyMock.eq(false),
				EasyMock.eq(false)))
			.andReturn(preloadsDependencies).once();
		EasyMock.replay(layer);

		ModuleList modules = layer.getModules(mockRequest);
		EasyMock.verify(layer);
		List<IModule> expected = makeModuleList("dep/a", "combo/text!dep/adep", "preload/a", "combo/text!preload/adep", "preload/nls/adep");
		assertEquals(expected, modules.getModules());
		assertSame(modules, requestAttributes.get(LayerImpl.MODULE_FILES_PROPNAME));
		assertNull(requestAttributes.get(LayerImpl.EXPANDEDDEPS_PROPNAME));
		assertEquals(new HashSet<String>(Arrays.asList("dep/a")), modules.getRequiredModules());
		assertEquals(new HashSet<String>(Arrays.asList("feature1", "feature2")), modules.getDependentFeatures());
		assertEquals(ModuleSpecifier.LAYER, modules.get(0).getSource());
		assertEquals(ModuleSpecifier.LAYER, modules.get(1).getSource());
		assertEquals(ModuleSpecifier.LAYER, modules.get(2).getSource());
		assertEquals(ModuleSpecifier.LAYER, modules.get(3).getSource());
	}

	@Test
	public void testGetModules_depsAndPreloadsWithReqExpLogging() throws Exception {
		LayerImpl layer = EasyMock.createMockBuilder(TestLayerImpl.class)
				.addMockedMethod("newDependencyList", String.class, Iterable.class, IAggregator.class, Features.class, boolean.class, boolean.class, boolean.class)
				.createMock();
		MockRequestedModuleNames names = new MockRequestedModuleNames();
		mockRequest.setAttribute(AbstractHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, names);
		mockRequest.setAttribute(AbstractHttpTransport.ASSERTNONLS_REQATTRNAME, true);
		names.setDeps(Arrays.asList("dep/a"));
		names.setPreloads(Arrays.asList("preload/a"));

		ModuleDeps depsExplicitDeps = new ModuleDeps();
		ModuleDeps depsExpandedDeps = new ModuleDeps();
		depsExplicitDeps.add("dep/a", new ModuleDepInfo());
		depsExpandedDeps.add("dep/adep", new ModuleDepInfo());
		ModuleDeps preloadsExplicitDeps = new ModuleDeps();
		ModuleDeps preloadsExpandedDeps = new ModuleDeps();
		preloadsExplicitDeps.add("preload/a", new ModuleDepInfo());
		preloadsExpandedDeps.add("preload/adep", new ModuleDepInfo());
		DependencyList depsDependencies = new DependencyList(depsExplicitDeps, depsExpandedDeps, new HashSet<String>(Arrays.asList("feature1")));
		DependencyList preloadsDependencies = new DependencyList(preloadsExplicitDeps, preloadsExpandedDeps, new HashSet<String>(Arrays.asList("feature2")));

		EasyMock.expect(layer.newDependencyList(
				EasyMock.eq(LayerImpl.DEPSOURCE_REQDEPS),
				EasyMock.eq(Arrays.asList("dep/a")),
				EasyMock.eq(mockAggregator),
				EasyMock.eq(features),
				EasyMock.eq(true),
				EasyMock.eq(true),
				EasyMock.eq(false)))
			.andReturn(depsDependencies).once();

		EasyMock.expect(layer.newDependencyList(
				EasyMock.eq(LayerImpl.DEPSOURCE_REQPRELOADS),
				EasyMock.eq(Arrays.asList("preload/a")),
				EasyMock.eq(mockAggregator),
				EasyMock.eq(features),
				EasyMock.eq(true),
				EasyMock.eq(true),
				EasyMock.eq(false)))
			.andReturn(preloadsDependencies).once();

		EasyMock.replay(layer);
		mockRequest.setAttribute(IHttpTransport.EXPANDREQUIRELISTS_REQATTRNAME, true);
		mockRequest.setAttribute(IHttpTransport.DEPENDENCYEXPANSIONLOGGING_REQATTRNAME, true);
		mockAggregator.getOptions().setOption("developmentMode", "true");

		ModuleList modules = layer.getModules(mockRequest);
		EasyMock.verify(layer);
		List<IModule> expected = makeModuleList("dep/a", "dep/adep", "preload/a", "preload/adep");
		assertEquals(expected, modules.getModules());
		assertSame(modules, requestAttributes.get(LayerImpl.MODULE_FILES_PROPNAME));
		assertEquals(new HashSet<String>(Arrays.asList("dep/a")), modules.getRequiredModules());
		assertEquals(new HashSet<String>(Arrays.asList("feature1", "feature2")), modules.getDependentFeatures());
		assertEquals(ModuleSpecifier.LAYER, modules.get(0).getSource());
		assertEquals(ModuleSpecifier.LAYER, modules.get(1).getSource());
		assertEquals(ModuleSpecifier.LAYER, modules.get(2).getSource());
		assertEquals(ModuleSpecifier.LAYER, modules.get(3).getSource());

		DependencyList bootLayerDeps = (DependencyList)requestAttributes.get(LayerImpl.EXPANDEDDEPS_PROPNAME);
		ModuleDeps expectedExplicitDeps = new ModuleDeps();
		expectedExplicitDeps.add("dep/a", new ModuleDepInfo());
		expectedExplicitDeps.add("preload/a", new ModuleDepInfo());
		assertEquals(expectedExplicitDeps, bootLayerDeps.getExplicitDeps());
		ModuleDeps expectedExpandedDeps = new ModuleDeps();
		expectedExpandedDeps.add("dep/adep", new ModuleDepInfo());
		expectedExpandedDeps.add("preload/adep", new ModuleDepInfo());
		assertEquals(expectedExpandedDeps, bootLayerDeps.getExpandedDeps());
		assertEquals(new HashSet<String>(Arrays.asList("feature1", "feature2")), bootLayerDeps.getDependentFeatures());

	}

	/*
	 * Verify that an exception is thrown if any of the modules that would be returned is
	 * an nls resource
	 */
	@Test (expected=BadRequestException.class)
	public void testGetModules_depsAndPreloadsWithReqExpLogging_failNoNLS() throws Exception {
		LayerImpl layer = EasyMock.createMockBuilder(TestLayerImpl.class)
				.addMockedMethod("newDependencyList", String.class, Iterable.class, IAggregator.class, Features.class, boolean.class, boolean.class, boolean.class)
				.createMock();
		MockRequestedModuleNames names = new MockRequestedModuleNames();
		mockRequest.setAttribute(AbstractHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, names);
		mockRequest.setAttribute(AbstractHttpTransport.ASSERTNONLS_REQATTRNAME, true);
		names.setDeps(Arrays.asList("dep/a"));
		names.setPreloads(Arrays.asList("preload/a"));

		ModuleDeps depsExplicitDeps = new ModuleDeps();
		ModuleDeps depsExpandedDeps = new ModuleDeps();
		depsExplicitDeps.add("dep/a", new ModuleDepInfo());
		depsExpandedDeps.add("dep/adep", new ModuleDepInfo());
		ModuleDeps preloadsExplicitDeps = new ModuleDeps();
		ModuleDeps preloadsExpandedDeps = new ModuleDeps();
		preloadsExplicitDeps.add("preload/a", new ModuleDepInfo());
		preloadsExpandedDeps.add("preload/nls/a", new ModuleDepInfo());
		DependencyList depsDependencies = new DependencyList(depsExplicitDeps, depsExpandedDeps, new HashSet<String>(Arrays.asList("feature1")));
		DependencyList preloadsDependencies = new DependencyList(preloadsExplicitDeps, preloadsExpandedDeps, new HashSet<String>(Arrays.asList("feature2")));

		EasyMock.expect(layer.newDependencyList(
				EasyMock.eq(LayerImpl.DEPSOURCE_REQDEPS),
				EasyMock.eq(Arrays.asList("dep/a")),
				EasyMock.eq(mockAggregator),
				EasyMock.eq(features),
				EasyMock.eq(true),
				EasyMock.eq(false),
				EasyMock.eq(false)))
			.andReturn(depsDependencies).once();

		EasyMock.expect(layer.newDependencyList(
				EasyMock.eq(LayerImpl.DEPSOURCE_REQPRELOADS),
				EasyMock.eq(Arrays.asList("preload/a")),
				EasyMock.eq(mockAggregator),
				EasyMock.eq(features),
				EasyMock.eq(true),
				EasyMock.eq(false),
				EasyMock.eq(false)))
			.andReturn(preloadsDependencies).once();

		EasyMock.replay(layer);
		layer.getModules(mockRequest);
		EasyMock.verify(layer);
	}

	@Test
	public void testGetModules_includeUndefinedFeatureDeps() throws Exception {
		LayerImpl layer = EasyMock.createMockBuilder(TestLayerImpl.class)
				.addMockedMethod("newDependencyList", String.class, Iterable.class, IAggregator.class, Features.class, boolean.class, boolean.class, boolean.class)
				.createMock();
		MockRequestedModuleNames names = new MockRequestedModuleNames();
		mockRequest.setAttribute(AbstractHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, names);
		names.setDeps(Arrays.asList(new String[]{"dep/a"}));
		ModuleDeps depsExplicitDeps = new ModuleDeps();
		ModuleDeps depsExpandedDeps = new ModuleDeps();
		depsExplicitDeps.add("dep/a", new ModuleDepInfo());
		depsExpandedDeps.add("dep/adep", new ModuleDepInfo());
		depsExpandedDeps.add("foo", new ModuleDepInfo("has", new BooleanTerm("feature"), null));
		depsExpandedDeps.add("bar", new ModuleDepInfo("has", new BooleanTerm("!feature"), null));
		DependencyList depsDependencies = new DependencyList(depsExplicitDeps, depsExpandedDeps, new HashSet<String>(Arrays.asList("feature")));
		EasyMock.expect(layer.newDependencyList(
				EasyMock.eq(LayerImpl.DEPSOURCE_REQDEPS),
				EasyMock.eq(Arrays.asList(new String[]{"dep/a"})),
				EasyMock.eq(mockAggregator),
				EasyMock.eq(features),
				EasyMock.eq(true),
				EasyMock.eq(false),
				EasyMock.eq(false)))
			.andReturn(depsDependencies).once();
		EasyMock.replay(layer);

		ModuleList modules = layer.getModules(mockRequest);
		EasyMock.verify(layer);
		List<IModule> expected = makeModuleList("dep/a", "dep/adep");
		assertSame(modules, requestAttributes.get(LayerImpl.MODULE_FILES_PROPNAME));
		assertNull(requestAttributes.get(LayerImpl.EXPANDEDDEPS_PROPNAME));
		assertEquals(expected, modules.getModules());
		assertEquals(new HashSet<String>(Arrays.asList("dep/a")), modules.getRequiredModules());
		assertEquals(new HashSet<String>(Arrays.asList("feature")), modules.getDependentFeatures());
		assertEquals(ModuleSpecifier.LAYER, modules.get(0).getSource());
		assertEquals(ModuleSpecifier.LAYER, modules.get(1).getSource());

		EasyMock.reset(layer);
		EasyMock.expect(layer.newDependencyList(
				EasyMock.eq(LayerImpl.DEPSOURCE_REQDEPS),
				EasyMock.eq(Arrays.asList(new String[]{"dep/a"})),
				EasyMock.eq(mockAggregator),
				EasyMock.eq(features),
				EasyMock.eq(true),
				EasyMock.eq(false),
				EasyMock.eq(false)))
			.andReturn(depsDependencies).once();

		EasyMock.replay(layer);
		mockRequest.removeAttribute(LayerImpl.MODULE_FILES_PROPNAME);
		mockRequest.setAttribute(IHttpTransport.INCLUDEUNDEFINEDFEATUREDEPS_REQATTRNAME, true);
		modules = layer.getModules(mockRequest);
		EasyMock.verify(layer);
		expected = makeModuleList("dep/a", "dep/adep", "foo", "bar");
		assertSame(modules, requestAttributes.get(LayerImpl.MODULE_FILES_PROPNAME));
		assertNull(requestAttributes.get(LayerImpl.EXPANDEDDEPS_PROPNAME));
		assertEquals(expected, modules.getModules());

	}

	@SuppressWarnings("serial")
	public class TestLayerImpl extends LayerImpl {

		public TestLayerImpl() {
			super("test", 1);
		}

		@Override
		protected IModule newModule(HttpServletRequest request, String mid) {
			return new TestModule(mid);
		}
	}

	@SuppressWarnings("serial")
	public class TestModule implements IModule {

		private final String moduleId;

		public TestModule(String moduleId) {
			this.moduleId = moduleId;
		}

		@Override
		public Future<ModuleBuildReader> getBuild(HttpServletRequest request) throws IOException {
			return null;
		}

		@Override
		public void clearCached(ICacheManager mgr) {}

		@Override
		public String getModuleId() {
			return moduleId;
		}

		@Override
		public String getModuleName() {
			int idx = moduleId.indexOf("!");
			return idx == -1 ? moduleId : moduleId.substring(idx+1);
		}

		@Override
		public String getPluginName() {
			int idx = moduleId.indexOf("!");
			return idx == -1 ? moduleId : moduleId.substring(0, idx);
		}

		@Override
		public URI getURI() {
			return URI.create("file:///" + moduleId);
		}

		@Override
		public IResource getResource(IAggregator aggregator) {
			return aggregator.newResource(getURI());
		}

		@Override
		public boolean equals(Object other) {
			if (other == null) return false;
			if (other instanceof TestModule) {
				return moduleId.equals(((TestModule)other).moduleId);
			}
			return false;
		}

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

		@Override
		public String toString() {
			return moduleId;
		}

	}

	public List<IModule> makeModuleList(String... names) {
		ArrayList<IModule> result = new ArrayList<IModule>(names.length);
		for (String name : names) {
			result.add(new TestModule(name));
		}
		return result;
	}

}


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

require_once('../../config.php');
require_once($CFG->libdir . '/adminlib.php');
require_once($CFG->dirroot . '/' . $CFG->admin . '/webservice/forms.php');
require_once($CFG->libdir . '/externallib.php');

$action = optional_param('action', '', PARAM_ALPHANUMEXT);
$tokenid = optional_param('tokenid', '', PARAM_SAFEDIR);
$confirm = optional_param('confirm', 0, PARAM_BOOL);

admin_externalpage_setup('addwebservicetoken');

//Deactivate the second 'Manage token' navigation node, and use the main 'Manage token' navigation node
$node = $PAGE->settingsnav->find('addwebservicetoken', navigation_node::TYPE_SETTING);
$newnode = $PAGE->settingsnav->find('webservicetokens', navigation_node::TYPE_SETTING);
if ($node && $newnode) {
    $node->display = false;
    $newnode->make_active();
}

require_capability('moodle/site:config', context_system::instance());

$tokenlisturl = new moodle_url("/" . $CFG->admin . "/settings.php", array('section' => 'webservicetokens'));

require_once($CFG->dirroot . "/webservice/lib.php");
$webservicemanager = new webservice();

switch ($action) {

    case 'create':
        $mform = new web_service_token_form(null, array('action' => 'create'));
        $data = $mform->get_data();
        if ($mform->is_cancelled()) {
            redirect($tokenlisturl);
        } else if ($data and confirm_sesskey()) {
            ignore_user_abort(true);

            //check the the user is allowed for the service
            $selectedservice = $webservicemanager->get_external_service_by_id($data->service);
            if ($selectedservice->restrictedusers) {
                $restricteduser = $webservicemanager->get_ws_authorised_user($data->service, $data->user);
                if (empty($restricteduser)) {
                    $allowuserurl = new moodle_url('/' . $CFG->admin . '/webservice/service_users.php',
                            array('id' => $selectedservice->id));
                    $allowuserlink = html_writer::tag('a', $selectedservice->name , array('href' => $allowuserurl));
                    $errormsg = $OUTPUT->notification(get_string('usernotallowed', 'webservice', $allowuserlink));
                }
            }

            //check if the user is deleted. unconfirmed, suspended or guest
            $user = $DB->get_record('user', array('id' => $data->user));
            if ($user->id == $CFG->siteguest or $user->deleted or !$user->confirmed or $user->suspended) {
                throw new moodle_exception('forbiddenwsuser', 'webservice');
            }

            //process the creation
            if (empty($errormsg)) {
                //TODO improvement: either move this function from externallib.php to webservice/lib.php
                // either move most of webservicelib.php functions into externallib.php
                // (create externalmanager class) MDL-23523
                external_generate_token(EXTERNAL_TOKEN_PERMANENT, $data->service,
                        $data->user, context_system::instance(),
                        $data->validuntil, $data->iprestriction);
                redirect($tokenlisturl);
            }
        }

        //OUTPUT: create token form
        echo $OUTPUT->header();
        echo $OUTPUT->heading(get_string('createtoken', 'webservice'));
        if (!empty($errormsg)) {
            echo $errormsg;
        }
        $mform->display();
        echo $OUTPUT->footer();
        die;
        break;

    case 'delete':
        $token = $webservicemanager->get_created_by_user_ws_token($USER->id, $tokenid);

        //Delete the token
        if ($confirm and confirm_sesskey()) {
            $webservicemanager->delete_user_ws_token($token->id);
            redirect($tokenlisturl);
        }

        ////OUTPUT: display delete token confirmation box
        echo $OUTPUT->header();
        $renderer = $PAGE->get_renderer('core', 'webservice');
        echo $renderer->admin_delete_token_confirmation($token);
        echo $OUTPUT->footer();
        die;
        break;

    default:
        //wrong url access
        redirect($tokenlisturl);
        break;
}


text:
using System.Collections.Generic;

using Trezorix.RnaRemote.Core.Items;

namespace RceDoorzoeker.Models.Item
{
	public class SkosPropertyListModel
	{
		public IEnumerable<SkosProperty> Labels { get; set; }
		public ResourceValueModel Caption { get; set; }
	}
}


text:
from django.utils.translation import ugettext_lazy as _

from django import forms

from django.contrib.auth.forms import (
    ReadOnlyPasswordHashField, AdminPasswordChangeForm)
from django.contrib.auth.admin import UserAdmin
from django.contrib import admin

from . import models

class UserCreationForm(forms.ModelForm):
    """A form for creating new users. Includes all the required
    fields, plus a repeated password."""
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation',
                                widget=forms.PasswordInput)

    class Meta:
        model = models.User
        fields = ('email', )

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(_("Passwords don't match"))
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

class UserChangeForm(forms.ModelForm):
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = models.User
        fields = ('username', 'email', 'password', 'is_active',
                  'is_staff')

    def clean_password(self):
        # Regardless of what the user provides, return the initial value.
        # This is done here, rather than on the field, because the
        # field does not have access to the initial value
        return self.initial["password"]

class CustomUserAdmin(UserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm
    change_password_form = AdminPasswordChangeForm
    list_display = ('email', 'username', 'is_superuser', 'is_staff')
    list_filter = ('is_staff', )
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                       'groups', 'user_permissions')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )
    filter_horizontal = ('groups', 'user_permissions', )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (
            None, {
                'classes': ('wide',),
                'fields': ('username', 'email', 'password1', 'password2')
            }
        ),
    )
    search_fields = ('username', 'email',)
    ordering = ('username', 'email',)

# Now register the new UserAdmin...
admin.site.register(models.User, CustomUserAdmin)


text:
Posts.allow({
  insert: function (userId, post) {
    return userId && post.owner === userId;
  },
  update: function (userId, post, fields, modifier) {
    return userId === post.owner;
  },
  remove: function (userId, post) {
    return userId === post.owner;
  }
});


text:
{% extends 'layouts/base.html' %}
{% import 'macros/form_macros.html' as f %}

{% block content %}

Reading Terminal Market
Purchasing Platform

Don't have an account?
              Email Us with your name and contact information to start the approval process

            {% set flashes = {
                'error':   get_flashed_messages(category_filter=['form-error']),
                'warning': get_flashed_messages(category_filter=['form-check-email']),
                'info':    get_flashed_messages(category_filter=['form-info']),
                'success': get_flashed_messages(category_filter=['form-success'])
            } %}

            {{ f.begin_form(form, flashes) }}
                {{ f.render_form_field(form.email, extra_classes="custom-login") }}
                {{ f.render_form_field(form.password, extra_classes="custom-login") }}

                {{ f.form_message(flashes['error'], header='Something went wrong.', class='error') }}
                {{ f.form_message(flashes['warning'], header='Check your email.', class='warning') }}
                {{ f.form_message(flashes['info'], header='Information', class='info') }}
                {{ f.form_message(flashes['success'], header='Success!', class='success') }}

                {{ f.render_form_field(form.submit, extra_classes="custom-login") }}
            {{ f.end_form(form) }}

                    {{ f.render_form_field(form.remember_me, extra_classes='login-keep') }}

                    Forgot password?

{% endblock %}


text:
<?php

namespace Racoony\Contracts\Settings;

/**
 * @author paul.schmidt
 */
interface SettingsRepositoryContract
{
    const CLUB_GENERAL = ['club' => 'general'];

    /**
     * @param $context
     *
     * @return mixed
     */
    public function getSettings($context);

    /**
     * @param $context
     * @param array $data
     *
     * @return mixed
     */
    public function storeSettings($context, $data = []);
}


text:
using namespace tdc_algorithms;

const std::vector<std::string> EXCLUDED_TESTS {
    "chain",
};
const std::vector<std::string> ADDITIONAL_TESTS {
    // "chain(chain(chain(chain(easyrle(\"1\"),bwt()),mtf()),easyrle()),encode(huff))",
    // "chain(lz78, lzw)",
    // "chain(lz78, chain(noop, lzw))",
};

TEST(TudocompDriver, roundtrip_matrix) {
    std::cout << "[ Generating list of test cases ]\n";

    std::vector<std::string> test_cases;

    auto test_cases_contains = [](const std::string test_case,
                                  const std::vector<std::string>& vs) {
        return std::any_of(vs.begin(),
                           vs.end(),
                           [&](const std::string& s) {
                            return test_case.find(s) != std::string::npos;
                           });
    };

    // stage 1: automatically generated list of tests
    {
        for (const auto& x : COMPRESSOR_REGISTRY.all_algorithms_with_static("compressor")) {
            test_cases.push_back(x.to_string());
        }
    }
    // stage 2: build-in exclude and additional
    {
        std::vector<std::string> test_cases_filtered;

        for (auto& x : test_cases) {
            if (!test_cases_contains(x, EXCLUDED_TESTS)) {
                test_cases_filtered.push_back(x);
            }
        }

        for (auto& x : ADDITIONAL_TESTS) {
            test_cases_filtered.push_back(x);
        }

        test_cases = test_cases_filtered;
    }

    // stage 3: environment exclude and additional
    {
        auto env_exclude_p = std::getenv("MATRIX_EXCLUDE");
        auto env_additional_p = std::getenv("MATRIX_ADDITIONAL");

        std::string env_exclude = (env_exclude_p != nullptr) ? env_exclude_p : "";
        std::string env_additional = (env_additional_p != nullptr) ? env_additional_p : "";

        std::vector<std::string> excluded_tests = driver_test::parse_scsv(env_exclude);
        std::vector<std::string> additional_tests = driver_test::parse_scsv(env_additional);

        std::vector<std::string> test_cases_filtered;

        for (auto& x : test_cases) {
            if (!test_cases_contains(x, excluded_tests)) {
                test_cases_filtered.push_back(x);
            }
        }

        for (auto& x : additional_tests) {
            test_cases_filtered.push_back(x);
        }

        test_cases = test_cases_filtered;
    }

    // stage 4: pattern filter
    {
        auto env_pattern_p = std::getenv("MATRIX_PATTERN");
        std::string env_pattern = (env_pattern_p != nullptr) ? env_pattern_p : "";

        std::vector<std::string> pattern_tests = driver_test::parse_scsv(env_pattern);

        if (!pattern_tests.empty()) {
            std::vector<std::string> test_cases_filtered;

            for(auto& x : test_cases) {
                if (test_cases_contains(x, pattern_tests)) {
                    test_cases_filtered.push_back(x);
                }
            }

            test_cases = test_cases_filtered;
        }
    }

    // Check if we want the fast, abbreviated matrix test
    auto env_fast_p = std::getenv("FAST_MATRIX");
    bool env_fast = (env_fast_p != nullptr);

    for (auto& e : test_cases) {
        std::cout << "  " << e << "\n";
    }
    std::cout << "[ Start roundtrip tests ]\n";

    bool early_error = std::getenv("MATRIX_EARLY_ERROR") != nullptr;

    std::vector<driver_test::Error> errors;

    bool saw_errors = false;

    for (auto& algo : test_cases) {
        int counter = 0;
        bool abort = false;

        auto run = [&](std::string text) {
            if (abort) {
                return;
            }
            std::stringstream ss;
            ss << std::setw(2) << std::setfill('0') << counter;
            std::string n = "_" + ss.str();
            counter++;

            auto e = driver_test::roundtrip(algo, n, text, true, abort, true);
            if (e.has_error) {
                saw_errors = true;
                if (early_error) {
                    e.print_error();
                } else {
                    errors.push_back(e);
                }
            }
        };

        if (!env_fast) {
            test::roundtrip_batch([&](std::string text) {
                run(text);
            });
        } else {
            std::stringstream ss;
            test::roundtrip_batch([&](std::string text) {
                ss << text;
            });
            run(ss.str());
        }
    }

    for (auto& e : errors) {
        e.print_error();
    }
    if (!errors.empty()) {
        std::cout << "# [TL;DR - this failed] ##############################################\n";
    }
    std::list<std::string> short_errs;
    for (auto& e : errors) {
        short_errs.push_back(e.algo);
    }

    short_errs.unique();

    for (auto& e : short_errs) {
        std::cout << e << "\n";
    }

    ASSERT_FALSE(saw_errors);
}


text:
// +k8s:deepcopy-gen=package,register
// +k8s:conversion-gen=k8s.io/kubernetes/pkg/apis/authorization
// +k8s:openapi-gen=true

// +groupName=authorization.k8s.io
package v1beta1


text:
<?php
/**
 * Created by PhpStorm.
 * User: daedeloth
 * Date: 28/04/14
 * Time: 15:05
 */

namespace Neuron\Filter;

class TemporaryField extends Field
{
	private $value;

	public function __construct ()
	{

	}

	public function setValue ($value)
	{
		$this->value = $value;
	}

	public function getValue ($model)
	{
		return $this->value;
	}
}


text:
Frontend for the [Airhead](https://github.com/turlando/airhead) webradio.

## Build

- Install [Lein](https://leiningen.org/).
- Run: `lein release`

For details look at the [Airhead
readme](https://github.com/turlando/airhead/blob/master/README.md).


text:
package thymeleafexamples.gtvg.business.entities.repositories;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import thymeleafexamples.gtvg.business.entities.Comment;
import thymeleafexamples.gtvg.business.entities.Product;

public class ProductRepository {

    private static final ProductRepository INSTANCE = new ProductRepository();
    private final Map<Integer,Product> productsById;

    public static ProductRepository getInstance() {
        return INSTANCE;
    }

    private ProductRepository() {

        super();

        this.productsById = new LinkedHashMap<Integer, Product>();

        final Product prod1 = new Product();
        prod1.setId(Integer.valueOf(1));
        prod1.setName("Fresh Sweet Basil");
        prod1.setInStock(true);
        prod1.setPrice(new BigDecimal("4.99"));
        this.productsById.put(prod1.getId(), prod1);

        final Product prod2 = new Product();
        prod2.setId(Integer.valueOf(2));
        prod2.setName("Italian Tomato");
        prod2.setInStock(false);
        prod2.setPrice(new BigDecimal("1.25"));
        this.productsById.put(prod2.getId(), prod2);

        final Product prod3 = new Product();
        prod3.setId(Integer.valueOf(3));
        prod3.setName("Yellow Bell Pepper");
        prod3.setInStock(true);
        prod3.setPrice(new BigDecimal("2.50"));
        this.productsById.put(prod3.getId(), prod3);

        final Product prod4 = new Product();
        prod4.setId(Integer.valueOf(4));
        prod4.setName("Old Cheddar");
        prod4.setInStock(true);
        prod4.setPrice(new BigDecimal("18.75"));
        this.productsById.put(prod4.getId(), prod4);

        final Comment comm21 = new Comment();
        comm21.setId(Integer.valueOf(1));
        comm21.setText("I'm so sad this product is no longer available!");
        prod2.getComments().add(comm21);

        final Comment comm22 = new Comment();
        comm22.setId(Integer.valueOf(2));
        comm22.setText("When do you expect to have it back?");
        prod2.getComments().add(comm22);

        final Comment comm41 = new Comment();
        comm41.setId(Integer.valueOf(3));
        comm41.setText("Very tasty! I'd definitely buy it again!");
        prod4.getComments().add(comm41);

    }

    public List<Product> findAll() {
        return new ArrayList<Product>(this.productsById.values());
    }

    public Product findById(final Integer id) {
        return this.productsById.get(id);
    }

}


text:
#ifndef CRIMILD_SIMULATION_CONSOLE_COMMAND_ECHO_
#define CRIMILD_SIMULATION_CONSOLE_COMMAND_ECHO_

#include "../ConsoleCommand.hpp"

namespace crimild {

	class EchoConsoleCommand : public ConsoleCommand {
	public:
		EchoConsoleCommand( void );
		virtual ~EchoConsoleCommand( void );

		virtual void execute( Console *console, ConsoleCommand::ConsoleCommandArgs const &args ) override;
	};

}

#endif