text:
package com.orangerhymelabs.helenus.cassandra.migration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.datastax.driver.core.Session;
import com.orangerhymelabs.helenus.cassandra.meta.AppliedMigration;
import com.orangerhymelabs.helenus.cassandra.meta.CassandraMetadataStrategy;
import com.orangerhymelabs.helenus.cassandra.meta.MetadataStrategy;

/**
 * @author tfredrich
 *
 */
public class Migrator
{
	private static final Logger LOG = LoggerFactory.getLogger(Migrator.class);

	private static final int UNINITIALIZED = -1;

	private MigrationConfiguration configuration;
	private Set<Migration> migrations = new HashSet<Migration>();
	private MetadataStrategy metadata;

	public Migrator()
	{
		super();
		setConfiguration(new MigrationConfiguration());
	}

	public void setConfiguration(MigrationConfiguration configuration)
	{
		this.configuration = configuration;
		this.metadata = new CassandraMetadataStrategy(configuration);
	}

	public MigrationConfiguration getConfiguration()
	{
		return configuration;
	}

	public Migrator register(Migration migration)
	{
		migrations.add(migration);
		return this;
	}

	public Migrator registerAll(Collection<Migration> migrations)
	{
		this.migrations.addAll(migrations);
		return this;
	}

	public void migrate(final Session session)
	throws IOException
	{
		int currentVersion = getCurrentVersion(session);

		if (currentVersion < 0)
		{
			currentVersion = initializeMetadata(session);
		}

		Collection<Migration> scriptMigrations = discoverMigrationScripts();
		List<Migration> allMigrations = new ArrayList<Migration>(migrations.size() + scriptMigrations.size());
		allMigrations.addAll(migrations);
		allMigrations.addAll(scriptMigrations);
		Collections.sort(allMigrations, Collections.reverseOrder());
		int latestVersion = allMigrations.get(allMigrations.size() -1).getVersion();

		if (currentVersion < latestVersion)
		{
			LOG.info(String.format("Database needs migration from current version %d to version %d", currentVersion, latestVersion));
			boolean wasSuccessful = process(session, allMigrations, currentVersion, latestVersion);

			if (!wasSuccessful)
			{
				throw new MigrationException("Migration aborted");
			}

			LOG.info("Database migration completed successfuly.");
		}
	}

	private boolean process(final Session session, final List<Migration> allMigrations, final int from, final int to)
	{
		for (Migration migration : allMigrations)
		{
			if (migration.isApplicable(from, to))
			{
				LOG.info("Migrating database to version " + migration.getVersion());
				long startTimeMillis = System.currentTimeMillis();
				boolean wasSuccessful = migration.migrate(session);
				long executionTime = System.currentTimeMillis() - startTimeMillis;
				metadata.update(session, new AppliedMigration(migration, executionTime, wasSuccessful));

				if (!wasSuccessful)
				{
					return false;
				}
			}
		}

		return true;
	}

	private Collection<Migration> discoverMigrationScripts()
	throws IOException
	{
		return new ClasspathMigrationLoader().load(configuration);
	}

	private int getCurrentVersion(Session session)
	{
		if (!metadata.exists(session))
		{
			return UNINITIALIZED;
		}

		return metadata.getCurrentVersion(session);
	}

	private int initializeMetadata(Session session)
	{
		metadata.initialize(session);
		return 0;
	}
}


text:
'use strict';  // eslint-disable-line

const fs = require('fs');
const yaml = require('js-yaml');
const walker = require('./walker');
const serverless = require('serverless');

module.exports = (log, projectName, stage, source, bundle, region) =>
  walker(source)
    .then((files) => {
      const serverlessConfig = {
        service: projectName,
        provider: {
          name: 'aws',
          runtime: 'nodejs4.3',
          stage,
          region,
          cfLogs: true,
        },
        functions: files
          .filter(f => /atomable.yml/g.test(f))
          .map(f => yaml.load(fs.readFileSync(f)))
          .map((conf) => {
            const functions = {};
            functions[conf.name] = {
              handler: 'handler.handler',
              events: [
                {
                  http: {
                    path: conf.https.path,
                    method: conf.https.method,
                    cors: conf.https.cors ? false : true, // eslint-disable-line
                  },
                },
              ],
            };
            return functions;
          }).reduce((a, b) => Object.assign(a, b), {}),
      };
      fs.writeFileSync(`${bundle}/serverless.yml`, yaml.dump(serverlessConfig));
    }).then(() =>
      serverless(bundle, { region, stage }, 'deploy', log.dim));

redpajama_set_name: RedPajamaGithub


text:
using PatchKit.Unity.Patcher.Cancellation;

namespace PatchKit.Unity.Patcher.AppData.Remote.Downloaders
{
    /// <summary>
    /// Base HTTP downloader.
    /// </summary>
    public interface IBaseHttpDownloader
    {
        event DataAvailableHandler DataAvailable;

        void SetBytesRange(long bytesRangeStart, long bytesRangeEnd = -1L);

        void Download(CancellationToken cancellationToken);
    }
}


text:
Ejemplo de uso de GITHUB App
Este programa genera un numero aleatorio.


text:
package uk.gov.ons.ctp.response.action.config;

import lombok.Data;

/**
 * Config POJO for action plan exec params
 *
 */
@Data
public class DataGrid {
  private String address;
  private String password;
  private Integer listTimeToWaitSeconds;
  private Integer listTimeToLiveSeconds;
  private Integer lockTimeToLiveSeconds;
}


text:
FAQs
====

What version required of Composer?
----------------------------------

See the documentation: [Installation](index.md#installation).

Why this plugin?
----------------

It is certain that each language has its own dependency management system, and that it is highly recommended to use
each package manager. NPM or Yarn works very well when the asset dependencies are managed only in the PHP project,
but when you create PHP libraries that using assets, there is no way to automatically add asset dependencies,
and most importantly, no validation of versions can be done automatically. You must tell the developers
the list of asset dependencies that using by your PHP library, and you must ask him to add manually the asset
dependencies to its asset manager of his project.

However, another solution exist - what many projects propose - you must add the assets in the folder of the
PHP library (like `/assets`, `/Resources/public`). Of course, with this method, the code is duplicated, it
pollutes the source code of the PHP library, no version management/validation is possible, and it is even
less possible, to use correctly all tools such as Babel, Scss, Less, etc ...

Foxy focuses solely on automation of the validation, addition, updating and deleting of the dependencies in
the definition file of the asset package, while restoring the project state, as well as PHP dependencies if
NPM or Yarn terminates with an error.

What is the difference between Foxy and Fxp Composer Asset Plugin?
------------------------------------------------------------------

When [Fxp Composer Asset Plugin](https://github.com/fxpio/composer-asset-plugin) has been created,
it lacked some important functionality to NPM and Bower as a true lock file, the access to
private repositories, the management of organizations (scope), and the assets was limited to a simple
download of the packages. The solution was to use the SAT solver, the VCS Repositories and the
Composer lock file to manage the asset dependencies of the PHP libraries. However, there are 3 major
disadvantages to this approach:

1. The plugin must be installed in global mode
2. Nodejs must be used more and more to compile some libraries
3. The use of VCS Repositories coupled with the SAT Solver architecture of Composer is much less
   efficient than NPM, despite the optimizations of the plugin to avoid the imports

Now, Bower has been depreciated, NPM has a true lock file (since 5.x), as well as the possibility
of using the private repositories, Yarn arrived with his big performances, and more and more javascript
library requires a compilation because they use Babel, Typescript, Sass, Less, etc...

Nodejs filling its gaps, and becoming more and more required, a plugin could finally perform the reverse operation,
retaining the benefits of Fxp Composer Asset Plugin and NPM. So, conversely, Foxy creates package mocks for NPM
in local directory, containing only the `package.json` file from the PHP library, and adding the path of the
mock package to the project's `package.json` file. The entire validation and installation process is left
to NPM or Yarn. However, the plugin manages the fallback if there is an error of the asset manager.

To conclude, given that there is not a backward compatibility, and that it is impossible to have a version
of the plugin installed globally, and another version installed in the project - because Composer will
install the plugin in the project, but will only use the plugin installed globally - the Fxp Composer Asset
Plugin was become Foxy.

How does the plugin work?
-------------------------

Foxy creates the mocks of Composer packages for NPM in local directory, containing only the `package.json`
file from the PHP library, and adding the package path to the `package.json` file of the project.

The name of the Composer package is converted to a format compatible with NPM, using the NPM scope
`@composer-asset` and replacing the separation slash `/` between the vendor and the package name by
2 dashes `--`, giving consequently, the following format `@composer-asset/<php-package-vendor>--<php-package-name>`
(this scope is reserved by Foxy in the registry of NPM and in Github).

NPM will install in the `node_modules/@composer-asset` folder an updated copy of each Composer package mock
that is located by default in the folder `vendor/foxy/composer-asset`.

For more details, the plugin work in this order:

1. Validation of the asset manager installation, then checking of the compatible asset manager version (optional)
2. Saving the status of project
3. Installing/updating of the PHP dependencies by Composer
4. Retrieving the entire list of installed packages
5. Retains only PHP dependencies with the `foxy/foxy` dependency in the `require` or `require-dev` section of
   the `composer.json` file and with the presence of the `package.json` file
6. Checking the lock file of asset manager
7. Comparing the difference between the installed asset dependencies and the new asset dependencies, to determine
   whether the dependency must be installed, updated, or removed
8. Creating, updating, or deleting of the mock asset libraries in local directory, containing only the
   `package.json` file of the PHP library, with a formatted name as:
   `@composer-asset/<php-package-vendor>--<php-package-name>`
9. Adding, updating, or deleting the mock asset library in the `package.json` file of the project
10. Running the install or update command of asset manager
11. Restoring the `package.json` file with the previous dependencies if the asset manager terminates with an error
12. Restoring the `composer.lock` file and all PHP dependencies if the asset manager terminates with an error

Is Foxy useful if my asset dependencies are defined only in my project?
-----------------------------------------------------------------------

Foxy is mainly focused on automating of the asset management of the PHP libraries, avoiding potentially conflicting
manual management.

Given that Foxy makes it possible to ensure that the entire management process is valid whether it is for Composer
and NPM or Yarn, you can use Foxy even if all of your asset dependencies are only defined in the `package.json` file
of your project. However, the value added by Foxy in this configuration will be low, and will be limited to the
management of the fallback of the PHP dependencies if there is an error of the asset manager.

NPM/Yarn does not find the mock of the Composer dependencies
------------------------------------------------------------

The advantage of Foxy, is that it allows you to keep the workflows of each tool. However, Foxy creates PHP
package mocks for NPM, and in this case, Composer must be launched before NPM or Yarn. After, nothing prevents
you to using all available commands of your favorite asset manager.

Why Foxy does nothing with the '--dry-run' option?
--------------------------------------------------

Foxy can work with Composer's `--dry-run` option, but chose to do nothing.  Given that the PHP dependencies
are not installed, updated or deleted, Foxy can not update the `package.json` file, and so, NPM can not
check the new constraints, if any. To sum up, this amounts to running the commands
`composer update --dry-run` followed by `npm update --dry-run`.

However, with the Foxy's fallbacks, this behavior is automatically reproduced, but by downloading the PHP
dependencies, and restoring the `package.json` file, the `composer.lock` file, and all the PHP dependencies
if the asset manager finishes with an error.

How to increase the PHP memory limit?
-------------------------------------

See the official documentation of Composer: [Memory limits errors](https://getcomposer.org/doc/articles/troubleshooting.md#memory-limit-errors).


text:
class TeamsAddLogUrl < ActiveRecord::Migration
  def change
    add_column :teams, :log_url, :string
  end
end


text:
package org.apache.pig.newplan;

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

import org.apache.pig.impl.logicalLayer.FrontendException;
import org.apache.pig.impl.plan.VisitorException;
import org.apache.pig.impl.util.Utils;

/**
 * A walker to walk graphs in dependency order.  It is guaranteed that a node
 * will not be visited until all of its predecessors have been visited.  This
 * is equivalent to doing a topilogical sort on the graph and then visiting
 * the nodes in order.
 */
public class DependencyOrderWalker extends PlanWalker {

    /**
     * @param plan for this walker to traverse.
     */
    public DependencyOrderWalker(OperatorPlan plan) {
        super(plan);
    }

    @Override
    public PlanWalker spawnChildWalker(OperatorPlan plan) {
        return new DependencyOrderWalker(plan);
    }

    /**
     * Begin traversing the graph.
     * @param visitor Visitor this walker is being used by.
     * @throws VisitorException if an error is encountered while walking.
     */
    @Override
    public void walk(PlanVisitor visitor) throws FrontendException {
        // This is highly inefficient, but our graphs are small so it should be okay.
        // The algorithm works by starting at any node in the graph, finding it's
        // predecessors and calling itself for each of those predecessors.  When it
        // finds a node that has no unfinished predecessors it puts that node in the
        // list.  It then unwinds itself putting each of the other nodes in the list.
        // It keeps track of what nodes it's seen as it goes so it doesn't put any
        // nodes in the graph twice.

        List<Operator> fifo = new ArrayList<Operator>();
        Set<Operator> seen = new HashSet<Operator>();
        List<Operator> leaves = plan.getSinks();
        if (leaves == null) return;
        for (Operator op : leaves) {
            doAllPredecessors(op, seen, fifo);
        }

        for (Operator op: fifo) {
            op.accept(visitor);
        }
    }

    protected void doAllPredecessors(Operator node,
                                   Set<Operator> seen,
                                   Collection<Operator> fifo) throws FrontendException {
        if (!seen.contains(node)) {
            // We haven't seen this one before.
            Collection<Operator> preds = Utils.mergeCollection(plan.getPredecessors(node), plan.getSoftLinkPredecessors(node));
            if (preds != null && preds.size() > 0) {
                // Do all our predecessors before ourself
                for (Operator op : preds) {
                    doAllPredecessors(op, seen, fifo);
                }
            }
            // Now do ourself
            seen.add(node);
            fifo.add(node);
        }
    }
}


text:
package com.github.texxel.data;

import org.junit.Test;

import java.util.*;

import static com.github.texxel.AssertHelpers.*;

public class JavaObjectSerializationTests {

    private static class TestClass implements DataSerializable {
        String value;

        @Constructor
        TestClass(DataIn in) {
            value = in.read(String.class, "value");
        }

        public TestClass(String value) {
            this.value = value;
        }

        @Override
        public void bundleInto (DataOut data) {
            data.write("value", value);
        }

        @Override
        public boolean equals (Object o) {
            return o instanceof TestClass && value.equals(((TestClass) o).value);
        }
    }
    private enum TestEnum {
        A, B;
    }

    @Test
    public void testCollectionSerialize() {
        List<TestClass> original = new LinkedList<>();
        original.add(new TestClass("Hello"));
        original.add(new TestClass("Pizza"));

        DataOutRoot out = new DataOutRoot();
        out.write("list", original);
        DataIn in = new DataIn(out.toPrimitiveData());

        LinkedList read = in.read(LinkedList.class, "list");
        assertListEquals(original, read);
    }

    @Test
    public void testClassSerialize() {
        Class clazz = TestClass.class;

        DataOutRoot out = new DataOutRoot();
        out.write("class", clazz);
        DataIn in = new DataIn(out.toPrimitiveData());

        Class classRead = in.read(Class.class, "class");
        assertEquals(clazz, classRead);
    }

    @Test
    public void testObjectArraySerialize() {
        Object[] objects = { "Hello", new TestClass("one") };

        DataOutRoot out = new DataOutRoot();
        out.write("objs", objects);
        DataIn in = new DataIn(out.toPrimitiveData());

        Object[] objsRead = in.read(Object[].class, "objs");
        assertArrayEquals(objects, objsRead);
    }

    @Test
    public void testCircularReferencedObjectArray() {
        Object[] array = new Object[2];
        array[0] = "first";
        array[1] = array;

        DataOutRoot out = new DataOutRoot();
        out.write("objs", array);
        DataIn in = new DataIn(out.toPrimitiveData());

        Object[] objsRead = in.read(Object[].class, "objs");

        assertEquals("first", objsRead[0]);
        assertSame(objsRead, objsRead[1]);
    }

    @Test
    public void testPrimitiveArraySerialization() {
        int[] ints = { 1, 2, 3, 4 };

        DataOutRoot out = new DataOutRoot();
        out.write("ints", ints);

        DataIn in = new DataIn(out.toPrimitiveData());

        int[] read = in.read(int[].class, "ints");

        assertArrayEquals(ints, read);
    }

    @Test
    public void testMultidimensionalArraysAreConverted() {
        int[][] write = {
            { 11, 12, 13 },
            { 21, 22, 23, 24 },
        };

        DataOutRoot out = new DataOutRoot();
        out.write("ints", write);
        DataIn in = new DataIn(out.toPrimitiveData());

        int[][] read = in.read(int[][].class, "ints");

        assertArrayEquals(write, read);
    }

    @Test
    public void testPrimitiveArraysAreCondensed() {
        int[] array = {1, 2, 3};

        DataOutRoot out = new DataOutRoot();
        out.write("array", array);
        PData data = out.toPrimitiveData();

        assertEquals(PData.Type.LONG, data.getSection("array").getType("1"));
    }

    @Test
    public void testMapsReadAndWrite() {
        HashMap<String, String> strs = new HashMap<>();
        strs.put("one", "einse");
        strs.put("two", "drie");
        TreeMap<String, TestClass> objs = new TreeMap<>();
        objs.put("a", new TestClass("A"));
        objs.put("b", new TestClass("B"));

        DataOutRoot out = new DataOutRoot();
        out.write("strings", strs);
        out.write("objs", objs);

        DataIn in = new DataIn(out.toPrimitiveData());

        Map<String, Integer> intsRead = in.read(Map.class, "strings");
        Map<String, Integer> objsRead = in.read(Map.class, "objs");

        assertMapEquals(strs, intsRead);
        assertMapEquals(objs, objsRead);
    }

    @Test
    public void testEnumsReadAndWrite() {
        DataOutRoot out = new DataOutRoot();
        out.write("a", TestEnum.A);
        out.write("b", TestEnum.B);

        DataIn in = new DataIn(out.toPrimitiveData());

        assertEquals(TestEnum.A, in.read(TestEnum.class, "a"));
        assertEquals(TestEnum.B, in.read(Object.class, "b"));
    }

    @Test
    public void testIntegersInCollections() {
        Set<Integer> intsWrite = new HashSet<>();
        intsWrite.add(1);
        intsWrite.add(2);
        intsWrite.add(4);

        DataOutRoot out = new DataOutRoot();
        out.write("ints", intsWrite);

        DataIn in = new DataIn(out.toPrimitiveData());
        Set<Integer> intsRead = in.read(Set.class, "ints");

        assertSetEquals(intsWrite, intsRead);
    }

}


text:
<?php
/**
 * TemplateUpdateSummary
 *
 * PHP version 7.4
 *
 * @category Class
 * @package  DocuSign\eSign
 * @author   Swaagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * DocuSign REST API
 *
 * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
 *
 * OpenAPI spec version: v2.1
 * Contact: devcenter@docusign.com
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 * Swagger Codegen version: 2.4.13-SNAPSHOT
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace DocuSign\eSign\Model;

use \ArrayAccess;
use DocuSign\eSign\ObjectSerializer;

/**
 * TemplateUpdateSummary Class Doc Comment
 *
 * @category    Class
 * @package     DocuSign\eSign
 * @author      Swagger Codegen team
 * @link        https://github.com/swagger-api/swagger-codegen
 */
class TemplateUpdateSummary implements ModelInterface, ArrayAccess
{
    const DISCRIMINATOR = null;

    /**
      * The original name of the model.
      *
      * @var string
      */
    protected static $swaggerModelName = 'templateUpdateSummary';

    /**
      * Array of property to type mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerTypes = [
        'bulk_envelope_status' => '\DocuSign\eSign\Model\BulkEnvelopeStatus',
        'envelope_id' => '?string',
        'error_details' => '\DocuSign\eSign\Model\ErrorDetails',
        'list_custom_field_update_results' => '\DocuSign\eSign\Model\ListCustomField[]',
        'lock_information' => '\DocuSign\eSign\Model\LockInformation',
        'purge_state' => '?string',
        'recipient_update_results' => '\DocuSign\eSign\Model\RecipientUpdateResponse[]',
        'tab_update_results' => '\DocuSign\eSign\Model\Tabs',
        'text_custom_field_update_results' => '\DocuSign\eSign\Model\TextCustomField[]'
    ];

    /**
      * Array of property to format mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerFormats = [
        'bulk_envelope_status' => null,
        'envelope_id' => null,
        'error_details' => null,
        'list_custom_field_update_results' => null,
        'lock_information' => null,
        'purge_state' => null,
        'recipient_update_results' => null,
        'tab_update_results' => null,
        'text_custom_field_update_results' => null
    ];

    /**
     * Array of property to type mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerTypes()
    {
        return self::$swaggerTypes;
    }

    /**
     * Array of property to format mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerFormats()
    {
        return self::$swaggerFormats;
    }

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @var string[]
     */
    protected static $attributeMap = [
        'bulk_envelope_status' => 'bulkEnvelopeStatus',
        'envelope_id' => 'envelopeId',
        'error_details' => 'errorDetails',
        'list_custom_field_update_results' => 'listCustomFieldUpdateResults',
        'lock_information' => 'lockInformation',
        'purge_state' => 'purgeState',
        'recipient_update_results' => 'recipientUpdateResults',
        'tab_update_results' => 'tabUpdateResults',
        'text_custom_field_update_results' => 'textCustomFieldUpdateResults'
    ];

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @var string[]
     */
    protected static $setters = [
        'bulk_envelope_status' => 'setBulkEnvelopeStatus',
        'envelope_id' => 'setEnvelopeId',
        'error_details' => 'setErrorDetails',
        'list_custom_field_update_results' => 'setListCustomFieldUpdateResults',
        'lock_information' => 'setLockInformation',
        'purge_state' => 'setPurgeState',
        'recipient_update_results' => 'setRecipientUpdateResults',
        'tab_update_results' => 'setTabUpdateResults',
        'text_custom_field_update_results' => 'setTextCustomFieldUpdateResults'
    ];

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @var string[]
     */
    protected static $getters = [
        'bulk_envelope_status' => 'getBulkEnvelopeStatus',
        'envelope_id' => 'getEnvelopeId',
        'error_details' => 'getErrorDetails',
        'list_custom_field_update_results' => 'getListCustomFieldUpdateResults',
        'lock_information' => 'getLockInformation',
        'purge_state' => 'getPurgeState',
        'recipient_update_results' => 'getRecipientUpdateResults',
        'tab_update_results' => 'getTabUpdateResults',
        'text_custom_field_update_results' => 'getTextCustomFieldUpdateResults'
    ];

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @return array
     */
    public static function attributeMap()
    {
        return self::$attributeMap;
    }

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @return array
     */
    public static function setters()
    {
        return self::$setters;
    }

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @return array
     */
    public static function getters()
    {
        return self::$getters;
    }

    /**
     * The original name of the model.
     *
     * @return string
     */
    public function getModelName()
    {
        return self::$swaggerModelName;
    }

    /**
     * Associative array for storing property values
     *
     * @var mixed[]
     */
    protected $container = [];

    /**
     * Constructor
     *
     * @param mixed[] $data Associated array of property values
     *                      initializing the model
     */
    public function __construct(array $data = null)
    {
        $this->container['bulk_envelope_status'] = isset($data['bulk_envelope_status']) ? $data['bulk_envelope_status'] : null;
        $this->container['envelope_id'] = isset($data['envelope_id']) ? $data['envelope_id'] : null;
        $this->container['error_details'] = isset($data['error_details']) ? $data['error_details'] : null;
        $this->container['list_custom_field_update_results'] = isset($data['list_custom_field_update_results']) ? $data['list_custom_field_update_results'] : null;
        $this->container['lock_information'] = isset($data['lock_information']) ? $data['lock_information'] : null;
        $this->container['purge_state'] = isset($data['purge_state']) ? $data['purge_state'] : null;
        $this->container['recipient_update_results'] = isset($data['recipient_update_results']) ? $data['recipient_update_results'] : null;
        $this->container['tab_update_results'] = isset($data['tab_update_results']) ? $data['tab_update_results'] : null;
        $this->container['text_custom_field_update_results'] = isset($data['text_custom_field_update_results']) ? $data['text_custom_field_update_results'] : null;
    }

    /**
     * Show all the invalid properties with reasons.
     *
     * @return array invalid properties with reasons
     */
    public function listInvalidProperties()
    {
        $invalidProperties = [];

        return $invalidProperties;
    }

    /**
     * Validate all the properties in the model
     * return true if all passed
     *
     * @return bool True if all properties are valid
     */
    public function valid()
    {
        return count($this->listInvalidProperties()) === 0;
    }

    /**
     * Gets bulk_envelope_status
     *
     * @return \DocuSign\eSign\Model\BulkEnvelopeStatus
     */
    public function getBulkEnvelopeStatus()
    {
        return $this->container['bulk_envelope_status'];
    }

    /**
     * Sets bulk_envelope_status
     *
     * @param \DocuSign\eSign\Model\BulkEnvelopeStatus $bulk_envelope_status bulk_envelope_status
     *
     * @return $this
     */
    public function setBulkEnvelopeStatus($bulk_envelope_status)
    {
        $this->container['bulk_envelope_status'] = $bulk_envelope_status;

        return $this;
    }

    /**
     * Gets envelope_id
     *
     * @return ?string
     */
    public function getEnvelopeId()
    {
        return $this->container['envelope_id'];
    }

    /**
     * Sets envelope_id
     *
     * @param ?string $envelope_id The envelope ID of the envelope status that failed to post.
     *
     * @return $this
     */
    public function setEnvelopeId($envelope_id)
    {
        $this->container['envelope_id'] = $envelope_id;

        return $this;
    }

    /**
     * Gets error_details
     *
     * @return \DocuSign\eSign\Model\ErrorDetails
     */
    public function getErrorDetails()
    {
        return $this->container['error_details'];
    }

    /**
     * Sets error_details
     *
     * @param \DocuSign\eSign\Model\ErrorDetails $error_details error_details
     *
     * @return $this
     */
    public function setErrorDetails($error_details)
    {
        $this->container['error_details'] = $error_details;

        return $this;
    }

    /**
     * Gets list_custom_field_update_results
     *
     * @return \DocuSign\eSign\Model\ListCustomField[]
     */
    public function getListCustomFieldUpdateResults()
    {
        return $this->container['list_custom_field_update_results'];
    }

    /**
     * Sets list_custom_field_update_results
     *
     * @param \DocuSign\eSign\Model\ListCustomField[] $list_custom_field_update_results
     *
     * @return $this
     */
    public function setListCustomFieldUpdateResults($list_custom_field_update_results)
    {
        $this->container['list_custom_field_update_results'] = $list_custom_field_update_results;

        return $this;
    }

    /**
     * Gets lock_information
     *
     * @return \DocuSign\eSign\Model\LockInformation
     */
    public function getLockInformation()
    {
        return $this->container['lock_information'];
    }

    /**
     * Sets lock_information
     *
     * @param \DocuSign\eSign\Model\LockInformation $lock_information lock_information
     *
     * @return $this
     */
    public function setLockInformation($lock_information)
    {
        $this->container['lock_information'] = $lock_information;

        return $this;
    }

    /**
     * Gets purge_state
     *
     * @return ?string
     */
    public function getPurgeState()
    {
        return $this->container['purge_state'];
    }

    /**
     * Sets purge_state
     *
     * @param ?string $purge_state
     *
     * @return $this
     */
    public function setPurgeState($purge_state)
    {
        $this->container['purge_state'] = $purge_state;

        return $this;
    }

    /**
     * Gets recipient_update_results
     *
     * @return \DocuSign\eSign\Model\RecipientUpdateResponse[]
     */
    public function getRecipientUpdateResults()
    {
        return $this->container['recipient_update_results'];
    }

    /**
     * Sets recipient_update_results
     *
     * @param \DocuSign\eSign\Model\RecipientUpdateResponse[] $recipient_update_results
     *
     * @return $this
     */
    public function setRecipientUpdateResults($recipient_update_results)
    {
        $this->container['recipient_update_results'] = $recipient_update_results;

        return $this;
    }

    /**
     * Gets tab_update_results
     *
     * @return \DocuSign\eSign\Model\Tabs
     */
    public function getTabUpdateResults()
    {
        return $this->container['tab_update_results'];
    }

    /**
     * Sets tab_update_results
     *
     * @param \DocuSign\eSign\Model\Tabs $tab_update_results tab_update_results
     *
     * @return $this
     */
    public function setTabUpdateResults($tab_update_results)
    {
        $this->container['tab_update_results'] = $tab_update_results;

        return $this;
    }

    /**
     * Gets text_custom_field_update_results
     *
     * @return \DocuSign\eSign\Model\TextCustomField[]
     */
    public function getTextCustomFieldUpdateResults()
    {
        return $this->container['text_custom_field_update_results'];
    }

    /**
     * Sets text_custom_field_update_results
     *
     * @param \DocuSign\eSign\Model\TextCustomField[] $text_custom_field_update_results
     *
     * @return $this
     */
    public function setTextCustomFieldUpdateResults($text_custom_field_update_results)
    {
        $this->container['text_custom_field_update_results'] = $text_custom_field_update_results;

        return $this;
    }
    /**
     * Returns true if offset exists. False otherwise.
     *
     * @param integer $offset Offset
     *
     * @return boolean
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * Gets offset.
     *
     * @param integer $offset Offset
     *
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }

    /**
     * Sets value based on offset.
     *
     * @param integer $offset Offset
     * @param mixed   $value  Value to be set
     *
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    /**
     * Unsets offset.
     *
     * @param integer $offset Offset
     *
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * Gets the string presentation of the object
     *
     * @return string
     */
    public function __toString()
    {
        if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
            return json_encode(
                ObjectSerializer::sanitizeForSerialization($this),
                JSON_PRETTY_PRINT
            );
        }

        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
    }
}


text:
#include "includes.h"

static
PVDIR_DOMAIN_SID_GEN_STATE
VmDirFindSidGenStateWithDN_inlock(
    PCSTR pszDomainDN
    );

static
DWORD
_VmDirGenerateDomainGuid(
    PSTR    pszGuid, /* optional */
    uuid_t* pDomainGuid
    );

static
DWORD
VmDirGenerateDomainGuidSid_inlock(
    PSTR    pszGuid, /* optional, if given used directly after check to make sure it is unique*/
    PSTR*   ppszDomainSid
    );

static
DWORD
VmDirGenerateObjectRid(
    UCHAR   ServerId,
    PDWORD  pdwRidSequence,
    PDWORD  pdwObjectRid
    );

static
DWORD
_VmDirSynchronizeRidSequence(
    PVDIR_DOMAIN_SID_GEN_STATE  pDomainSidState
    );

/*
 * During backup restore, per domain RID also needs to advance to a safe value to avoid objectsid collision.
 */
DWORD
VmDirAdvanceDomainRID(
    DWORD   dwCnt
    )
{
    DWORD               dwError = 0;
    VDIR_ENTRY_ARRAY    entryArray = {0};
    PVDIR_ATTRIBUTE     pAttr = NULL;
    size_t              iIdx = 0;
    DWORD               dwRidSeq = 0;
    DWORD               dwOrgRidSeq = 0;
    VDIR_BERVALUE       bvRID = VDIR_BERVALUE_INIT;

    if ( dwCnt > 0 )
    {
        dwError = VmDirSimpleEqualFilterInternalSearch(
                        "",
                        LDAP_SCOPE_SUBTREE,
                        ATTR_OBJECT_CLASS,
                        OC_DC_OBJECT,
                        &entryArray);
        BAIL_ON_VMDIR_ERROR(dwError);

        for ( iIdx = 0; iIdx < entryArray.iSize; iIdx++ )
        {
            char buf9[9] = {0};

            pAttr =  VmDirEntryFindAttribute(VDIR_ATTRIBUTE_SEQUENCE_RID, entryArray.pEntry+iIdx );
            if ( pAttr )
            {
                dwOrgRidSeq = VmDirStringToIA( (PCSTR)pAttr->vals[0].lberbv.bv_val );
                dwRidSeq = dwOrgRidSeq + dwCnt;

                if ( dwRidSeq < dwOrgRidSeq )
                {
                    VMDIR_LOG_ERROR( VMDIR_LOG_MASK_ALL, "%s, Domain [%s] RID rollover to value (%u)",
                                     __FUNCTION__, entryArray.pEntry[iIdx].dn.lberbv_val , dwRidSeq );
                    dwError = ERROR_INVALID_STATE;
                    BAIL_ON_VMDIR_ERROR(dwError);
                }

                dwError = VmDirStringNPrintFA( buf9, sizeof(buf9), sizeof(buf9)-1, "%lu", dwRidSeq );
                BAIL_ON_VMDIR_ERROR(dwError);

                bvRID.lberbv_val = buf9;
                bvRID.lberbv_len = VmDirStringLenA(buf9);
                dwError = VmDirInternalEntryAttributeReplace( NULL,
                                                              entryArray.pEntry[iIdx].dn.lberbv_val,
                                                              VDIR_ATTRIBUTE_SEQUENCE_RID,
                                                              &bvRID);
                BAIL_ON_VMDIR_ERROR(dwError);

                VMDIR_LOG_INFO( VMDIR_LOG_MASK_ALL, "%s: Domain [%s] RID advanced from (%u) to (%u)",
                                __FUNCTION__, entryArray.pEntry[iIdx].dn.lberbv_val, dwOrgRidSeq, dwRidSeq );
            }
        }
    }

cleanup:
    VmDirFreeEntryArrayContent(&entryArray);

    return dwError;

error:
    VMDIR_LOG_ERROR( VMDIR_LOG_MASK_ALL, "%s: advance (%u) failed error (%u)", __FUNCTION__, dwCnt, dwError);
    goto cleanup;
}

DWORD
VmDirGenerateObjectSid(
    PVDIR_ENTRY pEntry,
    PSTR *      ppszObjectSid
    )
{
    DWORD                       dwError = 0;
    BOOLEAN                     bInLock = FALSE;
    // Do not free ref
    PVDIR_DOMAIN_SID_GEN_STATE  pSidGenState = NULL;
//#ifndef _WIN32
    DWORD                       dwObjectRid = 0;
//#else
//    QWORD dwObjectRid = 0;
//#endif
    PSTR                        pszObjectSid = NULL;
    PSTR                        pszObjectDN = NULL;
    PSTR                        pszDomainDn = NULL;
    PSTR                        pszRIDStackStr = NULL;
    BOOLEAN                     IsDomainObject = FALSE;

    pszObjectDN = BERVAL_NORM_VAL(pEntry->dn);

    // Check to see whether the entry is an OC_DC_OBJECT
    dwError = VmDirIsDomainObjectWithEntry(pEntry, &IsDomainObject);
    BAIL_ON_VMDIR_ERROR(dwError);

    if (!IsDomainObject)
    {
        pszDomainDn = (PSTR)VmDirFindDomainDN(pszObjectDN);
        if (IsNullOrEmptyString(pszDomainDn))
        {
            // special object for instance
            // SUB_SCHEMA_SUB_ENTRY_DN, CFG_ROOT_DN, CFG_INDEX_ENTRY_DN, CFG_MANAGER_ENTRY_DN
            // Do nothing
            // and object cannot find an existing domain object
            dwError = ERROR_NO_OBJECT_SID_GEN;
            BAIL_ON_VMDIR_ERROR(dwError);
        }
    }
    else
    {
        pszDomainDn = pszObjectDN;
    }

    // S-1-7-21-sub1-sub2-sub3-sub4 --> domainSid  (vmwobjectSid)
    // S-1-7-21-sub1-sub2-sub3-sub4-rid --> objectSid    (vmwobjectSid)
    //PVDIR_O_SID_GEN_STATE pOrgSidGenState = NULL;
    VMDIR_LOCK_MUTEX(bInLock, gSidGenState.mutex);

    // pSidGenState refers to the state found in gSidGenState
    dwError = VmDirGetSidGenStateIfDomain_inlock(pszDomainDn, IsDomainObject ? pEntry->pszGuid : NULL, &pSidGenState);
    BAIL_ON_VMDIR_ERROR(dwError);
    assert(pSidGenState!=NULL);

    // for non-domain object, generate RID
    if (!IsDomainObject)
    {
        dwError = VmDirGenerateObjectRid(gVmdirServerGlobals.serverId,
                                         &pSidGenState->dwDomainRidSeqence,
                                         &dwObjectRid);
        BAIL_ON_VMDIR_ERROR(dwError);

        VMDIR_LOG_VERBOSE( VMDIR_LOG_MASK_ALL,
                           "allocate objectsid: (%s)(%lu)(%lu)",
                           VDIR_SAFE_STRING(pSidGenState->pszDomainSid),
                           dwObjectRid,
                           pSidGenState->dwDomainRidSeqence);

        pSidGenState->dwCount++;
        if ( pSidGenState->dwCount >= MAX_COUNT_PRIOR_WRITE )
        {
            dwError = VmDirAllocateStringPrintf(
                        &pszRIDStackStr, "%lu%c%s",
                        pSidGenState->dwDomainRidSeqence,
                        VMDIR_RID_STACK_SEPARATOR,
                        pSidGenState->pszDomainDn);
            BAIL_ON_VMDIR_ERROR(dwError);

            if ( VmDirPushTSStack( gSidGenState.pStack, pszRIDStackStr) != 0 )
            {
                VMDIR_LOG_WARNING( VMDIR_LOG_MASK_ALL,
                                   "gSidGenState.pStack push failed, (%s)",
                                   VDIR_SAFE_STRING(pszRIDStackStr));
            }
            else
            {
                pszRIDStackStr = NULL;
                pSidGenState->dwCount = 0;
                VmDirSrvThrSignal( gSidGenState.pRIDSyncThr );
            }
        }

        dwError = VmDirAllocateStringPrintf(
                        &pszObjectSid,
                        "%s-%lu",
                        pSidGenState->pszDomainSid,
//TODO: pgu
// Clean this up. ObjectRid should be 64 bit.
#ifndef _WIN32
                        dwObjectRid
#else
                        (long long)dwObjectRid
#endif
                        );
        BAIL_ON_VMDIR_ERROR(dwError);
    }
    else
    {
        dwError = VmDirAllocateStringA(
                        pSidGenState->pszDomainSid,
                        &pszObjectSid);
        BAIL_ON_VMDIR_ERROR(dwError);
    }

error:
    VMDIR_UNLOCK_MUTEX(bInLock, gSidGenState.mutex);

    VMDIR_SAFE_FREE_MEMORY( pszRIDStackStr );

    if (dwError != 0)
    {
        VMDIR_SAFE_FREE_MEMORY(pszObjectSid);
        pszObjectSid = NULL;
    }

    *ppszObjectSid = pszObjectSid;

    return dwError;
}

void
VmDirFindDomainRidSequenceWithDN(
    PCSTR   pszDomainDN,
    PDWORD  pRidSeq
    )
{
    PVDIR_DOMAIN_SID_GEN_STATE  pFoundState = NULL;
    BOOLEAN                     bInLock = FALSE;
    DWORD                       dwError = 0;

    VMDIR_LOCK_MUTEX(bInLock, gSidGenState.mutex);

    dwError = VmDirGetSidGenStateIfDomain_inlock( pszDomainDN, NULL, &pFoundState );

    VMDIR_UNLOCK_MUTEX(bInLock, gSidGenState.mutex);

    *pRidSeq = ((dwError == 0) && pFoundState) ? pFoundState->dwDomainRidSeqence : 0;

    return;
}

DWORD
VmDirIsDomainObjectWithEntry(
    PVDIR_ENTRY pEntry,
    PBOOLEAN    pbIsDomainObject
    )
{
    DWORD           dwError = 0;
    BOOLEAN         bIsDomainObject = FALSE;
    PVDIR_ATTRIBUTE pAttr = NULL;
    unsigned int    iCnt = 0;

    if (!pEntry)
    {
        dwError = ERROR_INVALID_ENTRY;
        BAIL_ON_VMDIR_ERROR(dwError);
    }

    pAttr = VmDirEntryFindAttribute(ATTR_OBJECT_CLASS, pEntry);
    if (!pAttr)
    {
        dwError = ERROR_INVALID_ENTRY;
        BAIL_ON_VMDIR_ERROR(dwError);
    }

    for (; iCnt < pAttr->numVals; iCnt++)
    {
        if (!VmDirStringCompareA((PSTR)pAttr->vals[iCnt].lberbv.bv_val, OC_DC_OBJECT, FALSE))
        {
            bIsDomainObject = TRUE;
            break;
        }
    }

error:
    if (dwError != ERROR_SUCCESS)
    {
        bIsDomainObject = FALSE;
    }

    *pbIsDomainObject = bIsDomainObject;

    return dwError;
}

PCSTR
VmDirFindDomainDN(
    PCSTR pszObjectDN
    )
{
    PSTR                        pszCurrDn = (PSTR)pszObjectDN;
    BOOLEAN                     bInLock = FALSE;
    PVDIR_DOMAIN_SID_GEN_STATE  pSidGenState = NULL;
    DWORD                       dwError = 0;

    VMDIR_LOCK_MUTEX(bInLock, gSidGenState.mutex);

    while (!IsNullOrEmptyString(pszCurrDn))
    {
        dwError = VmDirGetSidGenStateIfDomain_inlock( pszCurrDn, NULL, &pSidGenState );
        BAIL_ON_VMDIR_ERROR(dwError);

        if (pSidGenState)
        {
            break;
        }

        pszCurrDn = VmDirStringChrA(pszCurrDn, RDN_SEPARATOR_CHAR);

        if (!IsNullOrEmptyString(pszCurrDn)) pszCurrDn++;
    }

cleanup:
    VMDIR_UNLOCK_MUTEX(bInLock, gSidGenState.mutex);
    return pszCurrDn;

error:
    pszCurrDn = NULL;
    goto cleanup;
}

VOID
VmDirFreeOrgState(
    PVOID pOrgStat
    )
{
    if (pOrgStat)
    {
        PVDIR_DOMAIN_SID_GEN_STATE pOrgCurrState =  pOrgStat;

        VMDIR_SAFE_FREE_MEMORY(pOrgCurrState->pszDomainDn);
        VMDIR_SAFE_FREE_MEMORY(pOrgCurrState->pszDomainSid);

        VMDIR_SAFE_FREE_MEMORY(pOrgCurrState);
    }
}

DWORD
VmDirInternalRemoveOrgConfig(
    PVDIR_OPERATION pOperation,
    PSTR            pszDomainDN
    )
{
    DWORD                       dwError = 0;
    BOOLEAN                     bInLock = FALSE;
    PVDIR_DOMAIN_SID_GEN_STATE pFoundState = NULL;

    VMDIR_LOCK_MUTEX(bInLock, gSidGenState.mutex);

    pFoundState = VmDirFindSidGenStateWithDN_inlock(pszDomainDN);
    if (!pFoundState)
    {
        goto cleanup;
    }
    dwError = LwNtStatusToWin32Error(
                 LwRtlHashTableRemove(gSidGenState.pHashtable, &pFoundState->Node));
    BAIL_ON_VMDIR_ERROR(dwError);

    VmDirFreeOrgState(pFoundState);

    VMDIR_UNLOCK_MUTEX(bInLock, gSidGenState.mutex);

cleanup:
    VMDIR_UNLOCK_MUTEX(bInLock, gSidGenState.mutex);

    return dwError;

error:
    goto cleanup;
}

/* Given a domain DN, and a well-known RID
 * generate a valid well-known objectSid
 *
 * This API uses global cache, so not backend operations*/
DWORD
VmDirGenerateWellknownSid(
    PCSTR pszDomainDN,
    DWORD dwWellKnowRid,
    PSTR* ppszWellKnownSid
    )
{
    DWORD                       dwError = 0;
    BOOLEAN                     bInLock = FALSE;
    // Do not free ref
    PVDIR_DOMAIN_SID_GEN_STATE  pSidGenState = NULL;
    PSTR                        pszWellKnownSid = NULL;

    VMDIR_LOCK_MUTEX(bInLock, gSidGenState.mutex);

    // pSidGenState refers to the state found in gSidGenState
    dwError = VmDirGetSidGenStateIfDomain_inlock(pszDomainDN, NULL, &pSidGenState);
    BAIL_ON_VMDIR_ERROR(dwError);
    assert(pSidGenState!=NULL);

    dwError = VmDirAllocateStringAVsnprintf(
                    &pszWellKnownSid,
                    "%s-%lu",
                    pSidGenState->pszDomainSid,
                    //TODO: pgu
// Clean this up. ObjectRid should be 64 bit.
#ifndef _WIN32
                        dwWellKnowRid
#else
                        (long long)dwWellKnowRid
#endif
                    );

    BAIL_ON_VMDIR_ERROR(dwError);

    *ppszWellKnownSid = pszWellKnownSid;

cleanup:
    VMDIR_UNLOCK_MUTEX(bInLock, gSidGenState.mutex);

    return dwError;

error:
    VMDIR_SAFE_FREE_MEMORY(pszWellKnownSid);
    *ppszWellKnownSid = NULL;

    goto cleanup;
}

/* Holding 'gSidGenState.mutex' to find/create the state entry for a given DN in global 'gSidGenState' cache
 * if it corresponds to a domain object.
 *
 * PCSTR    pszObjectDN: may or may not be a domain DN
 *
 * PSTR     pszGuid: may or may not be NULL. Non-null => domain DN => create cache entry if not already there
 *
 * Function performs the following tasks (bit overloaded):
 *
 *  1) Checks if a given pszObjectDN is a domain (OC_DC_OBECT) DN or NOT by:
 *      - First checking cache
 *      - If not in cache, by reading the entry from DB, and checking if it is a OC_DC_OBJECT
 *
 *  2) Creates an entry in cache if it is a domain DN:
 *      - SID is either picked from the entry present in DB, OR
 *      - SID is generated from the given GUID
 *
 *  Returns:
 *      - non-NULL PVDIR_DOMAIN_SID_GEN_STATE* ppDomainState if pszObjectDN is a domain DN
 *      - NULL PVDIR_DOMAIN_SID_GEN_STATE* ppDomainState if pszObjectDN is NOT a domain DN
 *
 */

DWORD
VmDirGetSidGenStateIfDomain_inlock(
    PCSTR                       pszObjectDN,
    PSTR                        pszGuid,
    PVDIR_DOMAIN_SID_GEN_STATE* ppDomainState
    )
{
    DWORD                       dwError = 0;
    PVDIR_DOMAIN_SID_GEN_STATE  pOrgState = NULL;
    PVDIR_ENTRY                 pEntry = NULL;
    BOOLEAN                     IsDomainObject = FALSE;
    PVDIR_ATTRIBUTE             pObjSidAttr = NULL;
    PVDIR_ATTRIBUTE             pRidSeqAttr = NULL;
    DWORD                       dwDomainRidSequence = VMDIR_DOMAIN_USER_RID_MAX + 1;
    PSTR                        pszLocalErrorMsg = NULL;

    pOrgState = VmDirFindSidGenStateWithDN_inlock(pszObjectDN);
    if (pOrgState) // Found in cache
    {
        goto cleanup;
    }

    if (pszGuid == NULL)
    {
        if ((dwError = VmDirSimpleDNToEntry(pszObjectDN, &pEntry)) != 0)
        {
            if (dwError == VMDIR_ERROR_BACKEND_ENTRY_NOTFOUND || dwError == VMDIR_ERROR_ENTRY_NOT_FOUND)
            {
                dwError = 0;
                goto cleanup;
            }
            BAIL_ON_VMDIR_ERROR(dwError);
        }

        dwError = VmDirIsDomainObjectWithEntry(pEntry, &IsDomainObject);
        BAIL_ON_VMDIR_ERROR(dwError);

        if (!IsDomainObject)
        {
            goto cleanup;
        }

        if ((pObjSidAttr = VmDirEntryFindAttribute(ATTR_OBJECT_SID, pEntry)) == NULL)
        {
            dwError = VMDIR_ERROR_INVALID_ENTRY;
            BAIL_ON_VMDIR_ERROR_WITH_MSG( dwError, (pszLocalErrorMsg),
                "VmDirGetSidGenStateIfDomain_inlock(): Domain object (%s), ATTR_OBJECT_SID not found", pszObjectDN );
        }

        if ((pRidSeqAttr = VmDirEntryFindAttribute(VDIR_ATTRIBUTE_SEQUENCE_RID, pEntry)) != NULL)
        {
            dwDomainRidSequence = VmDirStringToIA( (PSTR)pRidSeqAttr->vals[0].lberbv.bv_val );
        }
    }

    // For domain object create new state
    dwError = VmDirAllocateMemory( sizeof(VDIR_DOMAIN_SID_GEN_STATE), (PVOID*)&pOrgState );
    BAIL_ON_VMDIR_ERROR(dwError);

    dwError = VmDirAllocateStringA( pszObjectDN, &pOrgState->pszDomainDn );
    BAIL_ON_VMDIR_ERROR(dwError);

    if (pObjSidAttr)
    {
        dwError = VmDirAllocateStringA( (PSTR)pObjSidAttr->vals[0].lberbv.bv_val, &pOrgState->pszDomainSid );
        BAIL_ON_VMDIR_ERROR(dwError);
    }
    else
    {
        // Generate domain SID
        dwError = VmDirGenerateDomainGuidSid_inlock( pszGuid, &pOrgState->pszDomainSid );
        BAIL_ON_VMDIR_ERROR(dwError);
    }

    pOrgState->dwDomainRidSeqence = dwDomainRidSequence;
    dwError = _VmDirSynchronizeRidSequence( pOrgState );
    BAIL_ON_VMDIR_ERROR(dwError);

    VMDIR_LOG_INFO( VMDIR_LOG_MASK_ALL,
                    "Init Sid cache (%s) RID (%u)",
                    pOrgState->pszDomainDn,
                    pOrgState->dwDomainRidSeqence);

    LwRtlHashTableResizeAndInsert(gSidGenState.pHashtable, &pOrgState->Node, NULL);

cleanup:
    *ppDomainState = pOrgState;

    VMDIR_SAFE_FREE_MEMORY(pszLocalErrorMsg);

    if (pEntry)
    {
        VmDirFreeEntry(pEntry);
    }
    return dwError;

error:
    VmDirFreeOrgState(pOrgState);
    pOrgState = NULL;

    VMDIR_LOG_ERROR( VMDIR_LOG_MASK_ALL, "VmDirGetSidGenStateIfDomain_inlock() failed. Error code = %d, objectDN = %s, "
                     "local error message = %s", dwError, VDIR_SAFE_STRING(pszObjectDN),
                     VDIR_SAFE_STRING(pszLocalErrorMsg) );

    goto cleanup;
}

/* Holding 'gSidGenState.mutex' to find a reference to the state entry for a given domain
 * DN in global 'gSidGenState' cache */
static
PVDIR_DOMAIN_SID_GEN_STATE
VmDirFindSidGenStateWithDN_inlock(
    PCSTR pszDomainDN
    )
{
    DWORD                       dwError = 0;
    PVDIR_DOMAIN_SID_GEN_STATE  pOrgState = NULL;
    PLW_HASHTABLE_NODE       pNode = NULL;

    dwError = LwRtlHashTableFindKey(gSidGenState.pHashtable, &pNode, (PVOID)pszDomainDN);
    BAIL_ON_VMDIR_ERROR(dwError);

    pOrgState = (PVDIR_DOMAIN_SID_GEN_STATE)LW_STRUCT_FROM_FIELD(pNode, VDIR_DOMAIN_SID_GEN_STATE, Node);

error:
    return pOrgState;
}

static
DWORD
_VmDirGenerateDomainGuid(
    PSTR    pszGuid, /* optional */
    uuid_t* pDomainGuid
    )
{
    DWORD dwError = 0;

    BAIL_ON_VMDIR_INVALID_POINTER(pDomainGuid, dwError);

    if (!IsNullOrEmptyString(pszGuid))
    {
        dwError = VmDirUuidFromString(pszGuid, pDomainGuid);
        BAIL_ON_VMDIR_ERROR(dwError);
    }
    else
    {
        dwError = VmDirUuidGenerate(pDomainGuid);
        BAIL_ON_VMDIR_ERROR(dwError);
    }

 cleanup:
     return dwError;

 error:
    goto cleanup;
}

/* gSidGenState.mutex held calling this function */
static
DWORD
VmDirGenerateDomainGuidSid_inlock(
    PSTR    pszGuid, /* optional, if given used directly. caller should only use a unique Guid once.*/
    PSTR*   ppszDomainSid
    )
{
    // S-1-7-21-sub1-sub2-sub3-sub4 --> organizationSid  (vmwobjectSid)
    DWORD                       dwError = 0;
    uuid_t                      OrgGuid = {0};
    uuid_t*                     pOrgGuid = NULL;
    PSTR                        pszDomainSid = NULL;
    PSID                        pOrgSid = NULL;
    ULONG                       ulOrgSidLength = 0;
    SID_IDENTIFIER_AUTHORITY    IdAuthority = { SECURITY_VMWARE_AUTHORITY };

    dwError = _VmDirGenerateDomainGuid(pszGuid, &OrgGuid);
    BAIL_ON_VMDIR_ERROR(dwError);

    dwError = VmDirAllocateMemory(sizeof(uuid_t), (PVOID*)&pOrgGuid);
    BAIL_ON_VMDIR_ERROR(dwError);

    dwError = VmDirCopyMemory(
        pOrgGuid, sizeof(uuid_t), &OrgGuid, sizeof(uuid_t) );
    BAIL_ON_VMDIR_ERROR(dwError);

    ulOrgSidLength = VmDirLengthRequiredSid(ORGANIZATION_SUB_AUTHORITY_NUMBER);

    dwError = VmDirAllocateMemory(ulOrgSidLength,
                                 (PVOID*)&pOrgSid);
    BAIL_ON_VMDIR_ERROR(dwError);

    dwError = VmDirInitializeSid(pOrgSid,
                                &IdAuthority,
                                ORGANIZATION_SUB_AUTHORITY_NUMBER);
    BAIL_ON_VMDIR_ERROR(dwError);

    // SECURITY_SUBAUTHORITY_ORGANIZATION-sub1-sub2-sub3-sub4 (total 5 parts)
    dwError = VmDirSetSidSubAuthority( pOrgSid, 4, *((PULONG)pOrgGuid) );
    BAIL_ON_VMDIR_ERROR(dwError);

    dwError = VmDirSetSidSubAuthority( pOrgSid, 3, *((PULONG)pOrgGuid + 1) );
    BAIL_ON_VMDIR_ERROR(dwError);

    dwError = VmDirSetSidSubAuthority( pOrgSid, 2, *((PULONG)pOrgGuid + 2) );
    BAIL_ON_VMDIR_ERROR(dwError);

    dwError = VmDirSetSidSubAuthority( pOrgSid, 1, *((PULONG)pOrgGuid + 3) );
    BAIL_ON_VMDIR_ERROR(dwError);

    dwError = VmDirSetSidSubAuthority( pOrgSid, 0, (ULONG)SECURITY_SUBAUTHORITY_ORGANIZATION );
    BAIL_ON_VMDIR_ERROR(dwError);

    dwError = VmDirAllocateCStringFromSid(&pszDomainSid,pOrgSid);
    BAIL_ON_VMDIR_ERROR(dwError);

    *ppszDomainSid = pszDomainSid;

cleanup:
    VMDIR_SAFE_FREE_MEMORY(pOrgGuid);
    VMDIR_SAFE_FREE_MEMORY(pOrgSid);
    return dwError;

error:
    dwError = VMDIR_ERROR_ORG_ID_GEN_FAILED;
    VMDIR_SAFE_FREE_MEMORY(pszDomainSid);
    *ppszDomainSid = NULL;
    goto cleanup;
}

/* RID is structured in two parts:
 * first 8-bit: serverId representing the server instance where an object is created
 * last 24-bit: rid sequence number (0-2^24-1)
 *
 */
static
DWORD
VmDirGenerateObjectRid(
    UCHAR   ucServerId,
    PDWORD  pdwRidSequence,
    PDWORD  pdwObjectRid
    )
{
    DWORD dwError = 0;
    DWORD dwRid = *pdwRidSequence;

    // Check to see whether current Rid hits the MAX
    if (dwRid+1 > MAX_RID_SEQUENCE)
    {
        dwError = ERROR_RID_LIMIT_EXCEEDED;
        BAIL_ON_VMDIR_ERROR(dwError);
    }

    dwRid++;
    *pdwRidSequence = dwRid;
    *pdwObjectRid = VMDIR_RID_SEQUENCE_NUMBER(dwRid, ucServerId);

error:
    if (dwError)
    {
        *pdwObjectRid = 0;
    }

    return dwError;
}

/*
 * Called during PVDIR_DOMAIN_SID_GEN_STATE instantiation.
 *
 * Make sure rid sequence number from db is up-to-date.
 * For example, if vmdird is not shutdown properly, rid sequence number in DB will be old.
 * If we do NOT re-synchronize, we will see ldap error (19) for ldap add operations.
 */
static
DWORD
_VmDirSynchronizeRidSequence(
    PVDIR_DOMAIN_SID_GEN_STATE  pDomainSidState
    )
{
    DWORD               dwError = 0;
    VDIR_ENTRY_ARRAY    entryArray = {0};
    PSTR                pszObjectSid = NULL;
    DWORD               dwCnt = 0;
    VDIR_BERVALUE       bvRID = VDIR_BERVALUE_INIT;
    char                buf64[ 64+1 ] = {0};

    // Walk down from the next batch and look for the first used
    // With potential issue from 5.5. upgrade, extend the scan to 5 batches
    for ( dwCnt = pDomainSidState->dwDomainRidSeqence + (MAX_COUNT_PRIOR_WRITE * 5);
          dwCnt > pDomainSidState->dwDomainRidSeqence;
          dwCnt--
        )
    {
        DWORD   dwObjectRid = VMDIR_RID_SEQUENCE_NUMBER( dwCnt, gVmdirServerGlobals.serverId);

        dwError = VmDirAllocateStringPrintf(
                        &pszObjectSid,
                        "%s-%lu",
                        pDomainSidState->pszDomainSid,
                        dwObjectRid);
        BAIL_ON_VMDIR_ERROR(dwError);

        dwError = VmDirSimpleEqualFilterInternalSearch(
                        "",
                        LDAP_SCOPE_SUBTREE,
                        ATTR_OBJECT_SID,    // objectsid is unique indexed.
                        pszObjectSid,
                        &entryArray);
        BAIL_ON_VMDIR_ERROR(dwError);

        if (entryArray.iSize != 0)
        {   // done, last used objectsid.
            VmDirFreeEntryArrayContent(&entryArray);
            break;
        }

        VMDIR_SAFE_FREE_MEMORY(pszObjectSid);
    }

    if (dwCnt != pDomainSidState->dwDomainRidSeqence)
    {
        VMDIR_LOG_WARNING( VMDIR_LOG_MASK_ALL,
                           "RID recovery: domain (%s) rid out of sync (%d)->(%d)",
                           VDIR_SAFE_STRING(pDomainSidState->pszDomainDn),
                           pDomainSidState->dwDomainRidSeqence,
                           (dwCnt));

        dwError = VmDirStringPrintFA( buf64, sizeof(buf64), "%lu", dwCnt );
        BAIL_ON_VMDIR_ERROR(dwError);

        bvRID.lberbv_val = buf64;
        bvRID.lberbv_len = VmDirStringLenA(buf64);
        dwError = VmDirInternalEntryAttributeReplace( NULL,
                                                      pDomainSidState->pszDomainDn,
                                                      VDIR_ATTRIBUTE_SEQUENCE_RID,
                                                      &bvRID);
        BAIL_ON_VMDIR_ERROR(dwError);
    }

    // dwCnt + 1 is the next available RID
    pDomainSidState->dwDomainRidSeqence = dwCnt;

cleanup:

    VmDirFreeEntryArrayContent(&entryArray);
    VMDIR_SAFE_FREE_MEMORY(pszObjectSid);

    return dwError;

error:

    VMDIR_LOG_ERROR( VMDIR_LOG_MASK_ALL, "_VmDirSynchronizeRidSequence failed (%d)", dwError);

    goto cleanup;
}


text:
using std::map;
using std::set;
using std::string;
using std::vector;

using namespace process;

namespace mesos {
namespace internal {
namespace slave {

// TODO(idownes): Move this to the Containerizer interface to complete
// the delegation of containerization.
Try<Resources> Containerizer::resources(const Flags& flags)
{
  Try<Resources> parsed = Resources::parse(
      flags.resources.getOrElse(""), flags.default_role);

  if (parsed.isError()) {
    return Error(parsed.error());
  }

  Resources resources = parsed.get();

  // NOTE: We need to check for the "cpus" resource within the flags
  // because once the `Resources` object is created, we cannot distinguish
  // between
  //  (1) "cpus:0", and
  //  (2) no cpus specified.
  // due to `Resources:add` discarding empty resources.
  // We only auto-detect cpus in case (2).
  // The same logic applies for the other resources!
  // `Resources::fromString().get()` is safe because `Resources::parse()` above
  // is valid.
  vector<Resource> resourceList = Resources::fromString(
      flags.resources.getOrElse(""), flags.default_role).get();

  bool hasCpus = false;
  bool hasMem = false;
  bool hasDisk = false;
  bool hasPorts = false;

  foreach (const Resource& resource, resourceList) {
    if (resource.name() == "cpus")
      hasCpus = true;
    else if (resource.name() == "mem")
      hasMem = true;
    else if (resource.name() == "disk")
      hasDisk = true;
    else if (resource.name() == "ports")
      hasPorts = true;
  }

  if (!hasCpus) {
    // No CPU specified so probe OS or resort to DEFAULT_CPUS.
    double cpus;
    Try<long> cpus_ = os::cpus();
    if (!cpus_.isSome()) {
      LOG(WARNING) << "Failed to auto-detect the number of cpus to use: '"
                   << cpus_.error()
                   << "'; defaulting to " << DEFAULT_CPUS;
      cpus = DEFAULT_CPUS;
    } else {
      cpus = cpus_.get();
    }

    resources += Resources::parse(
        "cpus",
        stringify(cpus),
        flags.default_role).get();
  }

#ifdef __linux__
  // GPU resource.
  Try<Resources> gpus = NvidiaGpuAllocator::resources(flags);
  if (gpus.isError()) {
    return Error("Failed to obtain GPU resources: " + gpus.error());
  }

  // When adding in the GPU resources, make sure that we filter out
  // the existing GPU resources (if any) so that we do not double
  // allocate GPUs.
  resources = gpus.get() + resources.filter(
      [](const Resource& resource) {
        return resource.name() != "gpus";
      });
#endif

  // Memory resource.
  if (!hasMem) {
    // No memory specified so probe OS or resort to DEFAULT_MEM.
    Bytes mem;
    Try<os::Memory> mem_ = os::memory();
    if (mem_.isError()) {
      LOG(WARNING) << "Failed to auto-detect the size of main memory: '"
                    << mem_.error()
                    << "' ; defaulting to DEFAULT_MEM";
      mem = DEFAULT_MEM;
    } else {
      Bytes total = mem_.get().total;
      if (total >= Gigabytes(2)) {
        mem = total - Gigabytes(1); // Leave 1GB free.
      } else {
        mem = Bytes(total.bytes() / 2); // Use 50% of the memory.
      }
    }

    resources += Resources::parse(
        "mem",
        stringify(mem.megabytes()),
        flags.default_role).get();
  }

  // Disk resource.
  if (!hasDisk) {
    // No disk specified so probe OS or resort to DEFAULT_DISK.
    Bytes disk;

    // NOTE: We calculate disk size of the file system on
    // which the slave work directory is mounted.
    Try<Bytes> disk_ = fs::size(flags.work_dir);
    if (!disk_.isSome()) {
      LOG(WARNING) << "Failed to auto-detect the disk space: '"
                   << disk_.error()
                   << "' ; defaulting to " << DEFAULT_DISK;
      disk = DEFAULT_DISK;
    } else {
      Bytes total = disk_.get();
      if (total >= Gigabytes(10)) {
        disk = total - Gigabytes(5); // Leave 5GB free.
      } else {
        disk = Bytes(total.bytes() / 2); // Use 50% of the disk.
      }
    }

    resources += Resources::parse(
        "disk",
        stringify(disk.megabytes()),
        flags.default_role).get();
  }

  // Network resource.
  if (!hasPorts) {
    // No ports specified so resort to DEFAULT_PORTS.
    resources += Resources::parse(
        "ports",
        stringify(DEFAULT_PORTS),
        flags.default_role).get();
  }

  Option<Error> error = Resources::validate(resources);
  if (error.isSome()) {
    return error.get();
  }

  return resources;
}

Try<Containerizer*> Containerizer::create(
    const Flags& flags,
    bool local,
    Fetcher* fetcher,
    SecretResolver* secretResolver)
{
  // Get the set of containerizer types.
  const vector<string> _types = strings::split(flags.containerizers, ",");
  const set<string> containerizerTypes(_types.begin(), _types.end());

  if (containerizerTypes.size() != _types.size()) {
    return Error("Duplicate entries found in --containerizer flag"
                 " '" + flags.containerizers + "'");
  }

  // Optionally create the Nvidia components.
  Option<NvidiaComponents> nvidia;

#ifdef __linux__
  if (nvml::isAvailable()) {
    // If we are using the docker containerizer (either alone or in
    // conjunction with the mesos containerizer), unconditionally
    // create the Nvidia components and pass them through. If we are
    // using the mesos containerizer alone, make sure we also have the
    // `gpu/nvidia` isolator flag set before creating these components.
    bool shouldCreate = false;

    if (containerizerTypes.count("docker") > 0) {
      shouldCreate = true;
    } else if (containerizerTypes.count("mesos") > 0) {
      const vector<string> _isolators = strings::tokenize(flags.isolation, ",");
      const set<string> isolators(_isolators.begin(), _isolators.end());

      if (isolators.count("gpu/nvidia") > 0) {
        shouldCreate = true;
      }
    }

    if (shouldCreate) {
      Try<Resources> gpus = NvidiaGpuAllocator::resources(flags);

      if (gpus.isError()) {
        return Error("Failed call to NvidiaGpuAllocator::resources: " +
                     gpus.error());
      }

      Try<NvidiaGpuAllocator> allocator =
        NvidiaGpuAllocator::create(flags, gpus.get());

      if (allocator.isError()) {
        return Error("Failed to NvidiaGpuAllocator::create: " +
                     allocator.error());
      }

      Try<NvidiaVolume> volume = NvidiaVolume::create();

      if (volume.isError()) {
        return Error("Failed to NvidiaVolume::create: " + volume.error());
      }

      nvidia = NvidiaComponents(allocator.get(), volume.get());
    }
  }
#endif

  // TODO(benh): We need to store which containerizer or
  // containerizers were being used. See MESOS-1663.

  // Create containerizer(s).
  vector<Containerizer*> containerizers;

  foreach (const string& type, containerizerTypes) {
    if (type == "mesos") {
      Try<MesosContainerizer*> containerizer = MesosContainerizer::create(
          flags, local, fetcher, secretResolver, nvidia);
      if (containerizer.isError()) {
        return Error("Could not create MesosContainerizer: " +
                     containerizer.error());
      } else {
        containerizers.push_back(containerizer.get());
      }
    } else if (type == "docker") {
      Try<DockerContainerizer*> containerizer =
        DockerContainerizer::create(flags, fetcher, nvidia);
      if (containerizer.isError()) {
        return Error("Could not create DockerContainerizer: " +
                     containerizer.error());
      } else {
        containerizers.push_back(containerizer.get());
      }
    } else {
      return Error("Unknown or unsupported containerizer: " + type);
    }
  }

  if (containerizers.size() == 1) {
    return containerizers.front();
  }

  Try<ComposingContainerizer*> containerizer =
    ComposingContainerizer::create(containerizers);

  if (containerizer.isError()) {
    return Error(containerizer.error());
  }

  return containerizer.get();
}

} // namespace slave {
} // namespace internal {
} // namespace mesos {


text:
extern crate polish;

use polish::test_case::{TestRunner, TestCase, TestCaseStatus, TEST_RUNNER_ATTRIBUTES as attributes};
use polish::logger::Logger;

fn main() {
    TestRunner::new()
        .set_attribute(attributes.minimize_output)
        .set_attribute(attributes.disable_final_stats)
        .set_attribute(attributes.bail_out_after_first_failure)
        .run_test(TestCase::new("title", "criteria", Box::new(|_: &mut Logger| -> TestCaseStatus {TestCaseStatus::UNKNOWN})));
}


text:
```@meta
CurrentModule = Migration
```

```@contents
```

```@docs
new
migration_hash
migration_file_name
migration_module_name
last_up
last_down
up_by_module_name
down_by_module_name
migration_by_module_name
all_migrations
last_migration
run_migration
store_migration_status
upped_migrations
downed_migrations
status
all_with_status
all_down
all_up
```


text:
package eu.hyvar.mspl.manifest.resource.hymanifest.mopp;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.resource.Resource.Factory;

public class HymanifestMetaInformation implements eu.hyvar.mspl.manifest.resource.hymanifest.IHymanifestMetaInformation {

	public String getSyntaxName() {
		return "hymanifest";
	}

	public String getURI() {
		return "http://hyvar-project.eu/mspl/manifest/1.0";
	}

	public eu.hyvar.mspl.manifest.resource.hymanifest.IHymanifestTextScanner createLexer() {
		return new eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestAntlrScanner(new eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestLexer());
	}

	public eu.hyvar.mspl.manifest.resource.hymanifest.IHymanifestTextParser createParser(InputStream inputStream, String encoding) {
		return new eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestParser().createInstance(inputStream, encoding);
	}

	public eu.hyvar.mspl.manifest.resource.hymanifest.IHymanifestTextPrinter createPrinter(OutputStream outputStream, eu.hyvar.mspl.manifest.resource.hymanifest.IHymanifestTextResource resource) {
		return new eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestPrinter2(outputStream, resource);
	}

	public EClass[] getClassesWithSyntax() {
		return new eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestSyntaxCoverageInformationProvider().getClassesWithSyntax();
	}

	public EClass[] getStartSymbols() {
		return new eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestSyntaxCoverageInformationProvider().getStartSymbols();
	}

	public eu.hyvar.mspl.manifest.resource.hymanifest.IHymanifestReferenceResolverSwitch getReferenceResolverSwitch() {
		return new eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestReferenceResolverSwitch();
	}

	public eu.hyvar.mspl.manifest.resource.hymanifest.IHymanifestTokenResolverFactory getTokenResolverFactory() {
		return new eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestTokenResolverFactory();
	}

	public String getPathToCSDefinition() {
		return "eu.hyvar.mspl.manifest/model/Manifest.cs";
	}

	public String[] getTokenNames() {
		return eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestParser.tokenNames;
	}

	public eu.hyvar.mspl.manifest.resource.hymanifest.IHymanifestTokenStyle getDefaultTokenStyle(String tokenName) {
		return new eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestTokenStyleInformationProvider().getDefaultTokenStyle(tokenName);
	}

	public Collection<eu.hyvar.mspl.manifest.resource.hymanifest.IHymanifestBracketPair> getBracketPairs() {
		return new eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestBracketInformationProvider().getBracketPairs();
	}

	public EClass[] getFoldableClasses() {
		return new eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestFoldingInformationProvider().getFoldableClasses();
	}

	public Factory createResourceFactory() {
		return new eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestResourceFactory();
	}

	public eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestNewFileContentProvider getNewFileContentProvider() {
		return new eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestNewFileContentProvider();
	}

	public void registerResourceFactory() {
		// if no resource factory registered, register delegator
		if (Factory.Registry.INSTANCE.getExtensionToFactoryMap().get(getSyntaxName()) == null) {
			Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(getSyntaxName(), new eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestResourceFactoryDelegator());
		}
	}

	/**
	 * Returns the key of the option that can be used to register a preprocessor that
	 * is used as a pipe when loading resources. This key is language-specific. To
	 * register one preprocessor for multiple resource types, it must be registered
	 * individually using all keys.
	 */
	public String getInputStreamPreprocessorProviderOptionKey() {
		return getSyntaxName() + "_" + "INPUT_STREAM_PREPROCESSOR_PROVIDER";
	}

	/**
	 * Returns the key of the option that can be used to register a post-processors
	 * that are invoked after loading resources. This key is language-specific. To
	 * register one post-processor for multiple resource types, it must be registered
	 * individually using all keys.
	 */
	public String getResourcePostProcessorProviderOptionKey() {
		return getSyntaxName() + "_" + "RESOURCE_POSTPROCESSOR_PROVIDER";
	}

	public String getLaunchConfigurationType() {
		return "eu.hyvar.mspl.manifest.resource.hymanifest.ui.launchConfigurationType";
	}

	public eu.hyvar.mspl.manifest.resource.hymanifest.IHymanifestNameProvider createNameProvider() {
		return new eu.hyvar.mspl.manifest.resource.hymanifest.analysis.HymanifestDefaultNameProvider();
	}

	public String[] getSyntaxHighlightableTokenNames() {
		eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestAntlrTokenHelper tokenHelper = new eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestAntlrTokenHelper();
		List<String> highlightableTokens = new ArrayList<String>();
		String[] parserTokenNames = getTokenNames();
		for (int i = 0; i < parserTokenNames.length; i++) {
			// If ANTLR is used we need to normalize the token names
			if (!tokenHelper.canBeUsedForSyntaxHighlighting(i)) {
				continue;
			}
			String tokenName = tokenHelper.getTokenName(parserTokenNames, i);
			if (tokenName == null) {
				continue;
			}
			highlightableTokens.add(tokenName);
		}
		highlightableTokens.add(eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestTokenStyleInformationProvider.TASK_ITEM_TOKEN_NAME);
		return highlightableTokens.toArray(new String[highlightableTokens.size()]);
	}

}


text:
<?php  ?>
<?php

/*
 * @author: Zijad Maksuti
 */

/**
* This class manages the creation and dropping of tables
*/
class DBManager
{
    private $db=null; // the database

    public function __construct(){

    }

    /**
    * This function connects the manager to the database
    *
    * @param string $host the address of the
    * @param string $dbName the name of the database to connect to
    * @param string $user the name of the user
    * @param string $password the password needed to access the database
    */
    public function connect($host, $dbName, $user, $password){

        try{
        $this->db = new PDO("mysql:host=".$host.";dbname=".$dbName,
        $user, $password);
        }
        catch (PDOException $e) {
            print "Error!: " . $e->getMessage() . "<br/>";
            die();
            }

    }

    /**
    * This function returns the database assigned to this object
    * @return the database assigned to this object, or null
    * if no database is assigned
    */
    public function getDB(){
        return $this->db;
    }

    public function __destruct() {
       $this->db = null;
   }

}
?>


text:
{{ #if bind.daemon.first }}
{{ #with bind.daemon.first }}
SHIELD_ENDPOINT='https://{{sys.ip}}:{{cfg.port}}'
SHIELD_API_TOKEN='{{cfg.provisioning_key}}'
{{~/with}}
{{else}}
SHIELD_ENDPOINT='{{cfg.shield_endpoint}}'
SHIELD_API_TOKEN='{{cfg.provisioning_key}}'
{{ /if }}


text:
'''Tests for ReStructuredTextChecker.'''

from __future__ import (
    absolute_import,
    print_function,
    unicode_literals,
)

from pocketlint.formatcheck import ReStructuredTextChecker
from pocketlint.tests import CheckerTestCase

# This is a valid rst content.
# This comment is here so that the content starts at line 11
# and make it easier to identify errors in tests.
# Just add 10 to the reported line number.
#
valid_rst_content = '''\
=============
First section
=============

Text *for* first **section**.

--------------------
Second emtpy section
--------------------

Third section
^^^^^^^^^^^^^

Paragrhap for
third section `with link<http://my.home>`_.

::

  Literal block1.

  Literal block paragraph.

| Line blocks are useful for addresses,
| verse, and adornment-free lists.

.. _section-permalink:

Another Section with predefined link
------------------------------------

>>> print "This is a doctest block."
... with a line continuation
This is a doctest block.

A grid table.

+------------+------------+-----------+
| Header 1   | Header 2   | Header 3  |
+============+============+===========+
| body row 1 | column 2   | column 3  |
+------------+------------+-----------+
| body row 2 | Cells may span columns.|
+------------+------------+-----------+
| body row 3 | Cells may  | - Cells   |
+------------+ span rows. | - contain |
| body row 4 |            | - blocks. |
+------------+------------+-----------+

A simple table.

=====  =====  ======
   Inputs     Output
------------  ------
  A      B    A or B
=====  =====  ======
False  False  False
True   False  True
False  True   True
True   True   True
=====  =====  ======

A transition marker is a horizontal line
of 4 or more repeated punctuation
characters.

------------

A transition should not begin or end a
section or document, nor should two
transitions be immediately adjacent.

Footnote references, like [5]_.
Note that footnotes may get
rearranged, e.g., to the bottom of
the "page".

.. [5] A numerical footnote. Note
   there's no colon after the ``]``.

External hyperlinks, like Python_.
.. _Python: http://www.python.org/

For instance:

.. image:: images/ball1.gif

The |biohazard| symbol must be used on containers used to dispose of
medical waste.

.. |biohazard| image:: biohazard.png

.. This text will not be shown
   (but, for instance, in HTML might be
   rendered as an HTML comment)
'''
# The last line from multi line string is a bit hard to visualize,
# but it is there.

class TestReStructuredTextChecker(CheckerTestCase):
    """Verify reStructuredTextChecker checking."""

    def test_empty_file(self):
        self.reporter.call_count = 0
        content = ('')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check()
        self.assertEqual([], self.reporter.messages)
        self.assertEqual(0, self.reporter.call_count)

    def test_valid_content(self):
        self.reporter.call_count = 0
        checker = ReStructuredTextChecker(
            'bogus', valid_rst_content, self.reporter)
        checker.check()
        self.assertEqual([], self.reporter.messages)
        self.assertEqual(0, self.reporter.call_count)

    def test_no_empty_last_line(self):
        self.reporter.call_count = 0
        content = (
            'Some first line\n'
            'the second and last line witout newline')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_empty_last_line(2)
        expected = [(
            2, 'File does not ends with an empty line.')]
        self.assertEqual(expected, self.reporter.messages)
        self.assertEqual(1, self.reporter.call_count)

    def test_multiple_empty_last_lines(self):
        self.reporter.call_count = 0
        content = (
            'Some first line\n'
            'the second and last\n'
            '\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_empty_last_line(3)
        expected = [(
            3, 'File does not ends with an empty line.')]
        self.assertEqual(expected, self.reporter.messages)
        self.assertEqual(1, self.reporter.call_count)

    def test_isTransition_good(self):
        content = (
            '\n'
            '----\n'
            '\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        result = checker.isTransition(1)
        self.assertTrue(result)

    def test_isTransition_short_line(self):
        content = (
            '\n'
            '---\n'
            '\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        result = checker.isTransition(1)
        self.assertFalse(result)

    def test_isTransition_short_file(self):
        content = (
            '\n'
            '----\n'
            '')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        result = checker.isTransition(1)
        self.assertFalse(result)

    def test_isTransition_false(self):
        content = (
            '\n'
            '----\n'
            'some\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        result = checker.isTransition(1)
        self.assertFalse(result)

        content = (
            'some\n'
            '----\n'
            '\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        result = checker.isTransition(1)
        self.assertFalse(result)

    def test_check_transitions_good(self):
        content = (
            'some text\n'
            '\n'
            '----\n'
            '\n'
            'some text\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_transition(2)
        self.assertEqual([], self.reporter.messages)
        self.assertEqual(0, self.reporter.call_count)

    def test_check_transitions_bad_spacing_before(self):
        content = (
            'some text\n'
            '\n'
            '\n'
            '----\n'
            '\n'
            'some text\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_transition(3)
        expect = [(
            4, 'Transition markers should be bounded by single empty lines.')]
        self.assertEqual(expect, self.reporter.messages)
        self.assertEqual(1, self.reporter.call_count)

    def test_check_transitions_bad_spacing_after(self):
        content = (
            'some text\n'
            '\n'
            '----\n'
            '\n'
            '\n'
            'some text\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_transition(2)
        expect = [(
            3, 'Transition markers should be bounded by single empty lines.')]
        self.assertEqual(expect, self.reporter.messages)
        self.assertEqual(1, self.reporter.call_count)

    def test_check_transitions_bad_spacing_both(self):
        content = (
            'some text\n'
            '\n'
            '\n'
            '----\n'
            '\n'
            '\n'
            'some text\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_transition(3)
        expect = [(
            4, 'Transition markers should be bounded by single empty lines.')]
        self.assertEqual(expect, self.reporter.messages)
        self.assertEqual(1, self.reporter.call_count)

    def test_isSectionDelimiter_short_file(self):
        content = (
            'Something'
            '---------\n'
            '')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        result = checker.isSectionDelimiter(1)
        self.assertFalse(result)

    def test_isSectionDelimiter_short_line(self):
        content = (
            'Som'
            '---\n'
            '')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        result = checker.isSectionDelimiter(1)
        self.assertFalse(result)

    def test_isSectionDelimiter_table(self):
        content = (
            '---- ----'
            'Row1 Row1'
            '---- ----\n'
            '')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        result = checker.isSectionDelimiter(0)
        self.assertFalse(result)
        result = checker.isSectionDelimiter(2)
        self.assertFalse(result)

    def test_isSectionDelimiter_good(self):
        content = (
            'Section\n'
            '-------\n'
            'some text')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        result = checker.isSectionDelimiter(1)
        self.assertTrue(result)

    def test_isSectionDelimiter_good_bounded_start_of_file(self):
        content = (
            '=======\n'
            'Section\n'
            '=======\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        result = checker.isSectionDelimiter(0)
        self.assertTrue(result)
        result = checker.isSectionDelimiter(2)
        self.assertTrue(result)

    def test_check_section_delimiter_bounded(self):
        content = (
            'some text\n'
            '\n'
            '\n'
            '=======\n'
            'Section\n'
            '=======\n'
            '\n'
            'some text\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_section_delimiter(3)
        checker.check_section_delimiter(5)
        self.assertEqual([], self.reporter.messages)
        self.assertEqual(0, self.reporter.call_count)

    def test_check_section_delimiter_bad_marker_length(self):
        content = (
            'Section\n'
            '------\n'
            '\n'
            'some text\n'
            'other text\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_section_delimiter(1)
        expect = [(2, 'Section marker has wrong length.')]
        self.assertEqual(expect, self.reporter.messages)
        self.assertEqual(1, self.reporter.call_count)

    def test_check_section_delimiter_bad_length_both_markers(self):
        content = (
            '---------\n'
            'Section\n'
            '---------\n'
            '\n'
            'some text\n'
            'other text\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_section_delimiter(0)
        checker.check_section_delimiter(2)
        expect = [(1, 'Section marker has wrong length.')]
        self.assertEqual(expect, self.reporter.messages)
        self.assertEqual(1, self.reporter.call_count)

    def test_check_section_before_space_good_start_both(self):
        content = (
            '-------\n'
            'Section\n'
            '-------\n'
            '\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_section_delimiter(0)
        checker.check_section_delimiter(2)
        self.assertEqual([], self.reporter.messages)
        self.assertEqual(0, self.reporter.call_count)

    def test_check_section_before_space_good_start_bottom(self):
        content = (
            'Section\n'
            '-------\n'
            '\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_section_delimiter(1)
        self.assertEqual([], self.reporter.messages)
        self.assertEqual(0, self.reporter.call_count)

    def test_check_section_before_space_bad_only_one_line_near_start(self):
        content = (
            '\n'
            'Section\n'
            '-------\n'
            '\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_section_delimiter(2)
        expect = [(3, 'Section should be divided by 2 empty lines.')]
        self.assertEqual(expect, self.reporter.messages)
        self.assertEqual(1, self.reporter.call_count)

    def test_check_section_before_space_bad_only_one_line(self):
        content = (
            'end of previous section.\n'
            '\n'
            'Section\n'
            '-------\n'
            '\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_section_delimiter(3)
        expect = [(4, 'Section should be divided by 2 empty lines.')]
        self.assertEqual(expect, self.reporter.messages)
        self.assertEqual(1, self.reporter.call_count)

    def test_check_section_before_space_multiple_empty_lines(self):
        content = (
            'end of previous section.\n'
            '\n'
            '\n'
            '\n'
            'Section\n'
            '-------\n'
            '\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_section_delimiter(5)
        expect = [(6, 'Section should be divided by 2 empty lines.')]
        self.assertEqual(expect, self.reporter.messages)
        self.assertEqual(1, self.reporter.call_count)

    def test_check_section_after_space_last_line(self):
        content = (
            'Section\n'
            '-------\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_section_delimiter(1)
        self.assertEqual([], self.reporter.messages)
        self.assertEqual(0, self.reporter.call_count)

    def test_check_section_after_space_bad(self):
        content = (
            'Section\n'
            '-------\n'
            'Paragraph start.\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_section_delimiter(1)
        expect = [(2, 'Section title should be followed by 1 empty line.')]
        self.assertEqual(expect, self.reporter.messages)
        self.assertEqual(1, self.reporter.call_count)

    def test_check_section_after_space_too_many_empty_lines(self):
        content = (
            'Section\n'
            '-------\n'
            '\n'
            '\n'
            'Paragraph start.\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_section_delimiter(1)
        expect = [(2, 'Section title should be followed by 1 empty line.')]
        self.assertEqual(expect, self.reporter.messages)
        self.assertEqual(1, self.reporter.call_count)

    def test_check_section_empty_section_next_section_only_bottom(self):
        content = (
            'Emtpy Section\n'
            '=============\n'
            '\n'
            '\n'
            'Another Section\n'
            '---------------\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_section_delimiter(1)
        self.assertEqual([], self.reporter.messages)
        self.assertEqual(0, self.reporter.call_count)

    def test_check_section_empty_section_next_section_both_markers(self):
        content = (
            'Emtpy Section\n'
            '=============\n'
            '\n'
            '\n'
            '---------------\n'
            'Another Section\n'
            '---------------\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_section_delimiter(1)
        self.assertEqual([], self.reporter.messages)
        self.assertEqual(0, self.reporter.call_count)

    def disable_check_section_delimiter_both_markers_not_sync(self):
        # When both top and bottom markers are used, and they don't have
        # the same size, they are interpreted as separate markers.
        content = (
            '------\n'
            'Section\n'
            '--------\n'
            '\n'
            'some text\n'
            'other text\n')
        checker = ReStructuredTextChecker('bogus', content, self.reporter)
        checker.check_lines()
        expect = [
            (1, 'Section marker has wrong length.'),
            (1, 'Section title should be followed by 1 empty line.'),
            (3, 'Section marker has wrong length.')]
        self.assertEqual(expect, self.reporter.messages)
        self.assertEqual(3, self.reporter.call_count)


text:
Dependency Injection Containers
===============================

Before diving head first into the world of Dependency Injection Containers,
let's start with a bold statement:

  *Most of the time, you don't need a Dependency Injection Container to
  benefit from Dependency Injection*.

But when you need to manage a lot of different objects with a lot of
dependencies, a Dependency Injection Container can be really helpful (think of
a framework for instance).

If you remember the example in the first chapter, creating a `User` object
required us to first create a `SessionStorage` object. Not a big deal, but still,
you have to know about all the dependencies you need before creating the
object you need:

    [php]
    $storage = new SessionStorage('SESSION_ID');
    $user = new User($storage);

In the upcoming chapters, we will specifically talk about the Symfony
Dependency Injection Container component. As we want to make it clear that the
implementation is in no way bound to Symfony, this book also uses Zend
Framework examples.

The Zend Framework `Mail` library, which eases email management, uses the PHP
`mail()` function by default to send emails, which is not really flexible.
Thankfully, it is quite easy to change this behavior by providing a transport
object. The following snippet of code shows how to create a `Zend_Mail` object
that sends its emails using a Gmail account:

    [php]
    $transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', array(
      'auth'     => 'login',
      'username' => 'foo',
      'password' => 'bar',
      'ssl'      => 'ssl',
      'port'     => 465,
    ));

    $mailer = new Zend_Mail();
    $mailer->setDefaultTransport($transport);

>**NOTE**
>To keep this book short enough, we use simple examples. Of course,
>for these simple examples, it does not make sense to have a
>container. Think of the examples as being just a small part of the
>collections of objects that need to be managed by the container.

A Dependency Injection Container is an object that knows how to instantiate
and configure objects. And to be able to do its job, it needs to knows about
the constructor arguments and the relationships between the objects.

Here is a simple hardcoded container for the above `Zend_Mail` example:

    [php]
    class Container
    {
      public function getMailTransport()
      {
        return new Zend_Mail_Transport_Smtp('smtp.gmail.com', array(
          'auth'     => 'login',
          'username' => 'foo',
          'password' => 'bar',
          'ssl'      => 'ssl',
          'port'     => 465,
        ));
      }

      public function getMailer()
      {
        $mailer = new Zend_Mail();
        $mailer->setDefaultTransport($this->getMailTransport());

        return $mailer;
      }
    }

Using the container class is simple enough:

    [php]
    $container = new Container();
    $mailer = $container->getMailer();

When using the container, we just ask for a mailer object, and we don't need
to know anything about how to create it anymore; all the knowledge about how
to create an instance of the mailer is now embedded into the container. The
mail transport dependency will be injected automatically by the container,
thanks to the `getMailTransport()` call. All the power of the container lies
in this simple call!

But, astute readers might have noticed a problem here. The container itself
has everything hardcoded! So, we need to go one step further and add
parameters to the mix to make the container really useful:

    [php]
    class Container
    {
      protected $parameters = array();

      public function __construct(array $parameters = array())
      {
        $this->parameters = $parameters;
      }

      public function getMailTransport()
      {
        return new Zend_Mail_Transport_Smtp('smtp.gmail.com', array(
          'auth'     => 'login',
          'username' => $this->parameters['mailer.username'],
          'password' => $this->parameters['mailer.password'],
          'ssl'      => 'ssl',
          'port'     => 465,
        ));
      }

      public function getMailer()
      {
        $mailer = new Zend_Mail();
        $mailer->setDefaultTransport($this->getMailTransport());

        return $mailer;
      }
    }

It is now easy to change the Google username and password by passing some
parameters to the container constructor:

    [php]
    $container = new Container(array(
      'mailer.username' => 'foo',
      'mailer.password' => 'bar',
    ));
    $mailer = $container->getMailer();

If you need to change the mailer class for testing, the object class name can
also be passed as a parameter:

    [php]
    class Container
    {
      // ...

      public function getMailer()
      {
        $class = $this->parameters['mailer.class'];

        $mailer = new $class();
        $mailer->setDefaultTransport($this->getMailTransport());

        return $mailer;
      }
    }

    $container = new Container(array(
      'mailer.username' => 'foo',
      'mailer.password' => 'bar',
      'mailer.class'    => 'Zend_Mail',
    ));
    $mailer = $container->getMailer();

Last, but not least, each time you want to get a mailer, you don't need a
new instance of it. So, the container can be changed to always return the same
object:

    [php]
    class Container
    {
      static protected $shared = array();

      // ...

      public function getMailer()
      {
        if (isset(self::$shared['mailer']))
        {
          return self::$shared['mailer'];
        }

        $class = $this->parameters['mailer.class'];

        $mailer = new $class();
        $mailer->setDefaultTransport($this->getMailTransport());

        return self::$shared['mailer'] = $mailer;
      }
    }

With the introduction of the static `$shared` property, each time you call the
`getMailer()` method, the object created for the first call will be returned.

That wraps up the basic features that need to be implemented by a Dependency
Injection Container. A Dependency Injection Container manages objects: from
their instantiation to their configuration. The objects themselves do not know
that they are managed by a container and know nothing about the container.
That's why a container is able to manage any PHP object. It is even better if
the objects use dependency injection for their dependencies, but that's not a
prerequisite.

Of course, creating and maintaining the container class by hand can become a
nightmare pretty fast. But as the requirements are quite minimal for a
container to be useful, it is easy to implement one.