text:
flika
=====

.. image:: flika/docs/_static/img/flika_screencapture.gif

**flika** is an interactive image processing program for biologists written in Python.

Website
-------
`flika-org.github.io <http://flika-org.github.io/>`_

Documentation
-------------
`flika-org.github.io/contents.html <http://flika-org.github.io/contents.html>`_

Install
-------
`flika-org.github.io/getting-started.html#installation <http://flika-org.github.io/getting-started.html#installation>`_

.. code:: python

	pip install flika


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Streams.Messages;

namespace Orleans.Streams.Endpoints
{
    /// <summary>
    /// Consumes items from multiple streams.
    /// </summary>
    /// <typeparam name="T">Type of items to consume.</typeparam>
    public class MultiStreamConsumer<T> : ITransactionalStreamConsumerAggregate<T>, IStreamMessageVisitor<T>
    {
        private readonly IStreamProvider _streamProvider;
        protected readonly List<SingleStreamConsumer<T>> Consumers;
        private bool _tearDownExecuted;
        protected Func<IEnumerable<T>, Task> StreamItemBatchReceivedFunc;
        protected Func<TransactionMessage, Task> StreamTransactionReceivedFunc;

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="streamProvider">Stream provider to be used.</param>
        /// <param name="streamItemBatchReceivedFunc">Asynchronous function to be executed when an item is received.</param>
        /// <param name="streamTransactionReceivedFunc">Asynchronous function to be executed when a transaction message is received.</param>
        public MultiStreamConsumer(IStreamProvider streamProvider, Func<IEnumerable<T>, Task> streamItemBatchReceivedFunc,
            Func<TransactionMessage, Task> streamTransactionReceivedFunc = null)
        {
            Consumers = new List<SingleStreamConsumer<T>>();
            _streamProvider = streamProvider;
            StreamTransactionReceivedFunc = streamTransactionReceivedFunc;
            StreamItemBatchReceivedFunc = streamItemBatchReceivedFunc;
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="streamProvider">Stream provider to be used.</param>
        /// <param name="streamItemBatchReceivedAction">Action to be executed when an item is received.</param>
        /// <param name="streamTransactionReceivedAction">Action to be executed when a transaction message is received.</param>
        public MultiStreamConsumer(IStreamProvider streamProvider, Action<IEnumerable<T>> streamItemBatchReceivedAction = null,
            Action<TransactionMessage> streamTransactionReceivedAction = null)
        {
            Consumers = new List<SingleStreamConsumer<T>>();
            _streamProvider = streamProvider;

            if (streamTransactionReceivedAction != null)
            {
                StreamTransactionReceivedFunc = transaction =>
                {
                    streamTransactionReceivedAction(transaction);
                    return TaskDone.Done;
                };
            }

            if (streamItemBatchReceivedAction != null)
            {
                StreamItemBatchReceivedFunc = items =>
                {
                    streamItemBatchReceivedAction(items);
                    return TaskDone.Done;
                };
            }
            ;
        }

        public async Task SetInput(IEnumerable<StreamIdentity<T>> streamIdentities)
        {
            _tearDownExecuted = false;
            foreach (var identity in streamIdentities)
            {
                var consumer = new SingleStreamConsumer<T>(_streamProvider, this);

                await consumer.SetInput(identity);

                Consumers.Add(consumer);
            }
        }

        /// <summary>
        /// Returns when a transaction is complete.
        /// </summary>
        /// <param name="transactionId">Transaction identifier.</param>
        /// <returns></returns>
        public async Task TransactionComplete(int transactionId)
        {
            await Task.WhenAll(Consumers.Select(c => c.TransactionComplete(transactionId)));
        }

        /// <summary>
        /// Returns true if consumer is teared down.
        /// </summary>
        /// <returns></returns>
        public Task<bool> IsTearedDown()
        {
            return Task.FromResult(_tearDownExecuted);
        }

        public virtual async Task TearDown()
        {
            await Task.WhenAll(Consumers.Select(c => c.TearDown()));
            _tearDownExecuted = true;
        }

        public async Task Visit(ItemMessage<T> message)
        {
            if (StreamItemBatchReceivedFunc != null)
            {
                await StreamItemBatchReceivedFunc(message.Items);
            }
        }

        public async Task Visit(TransactionMessage transactionMessage)
        {
            if (StreamTransactionReceivedFunc != null)
            {
                await StreamTransactionReceivedFunc(transactionMessage);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
var Schema = {};
var Schemas = {};

Schema.UserCountry = new SimpleSchema({
    name: {
        type: String
    },
    code: {
        type: String,
        regEx: /^[A-Z]{2}$/
    }
});

Schemas.listDetail = new SimpleSchema({
    title: {
        type: String
    },
    backgroundStyle: {
        type: String,
        optional: true
    },
    permalink: {
        type: String,
        regEx: /^[A-Za-z0-9\-\_]+/
    },
    desc: {
        type: String,
        optional: true
    },
    username: {
        type: String
    },
    user: {
        type: String
    },
    background: {
        type: String,
        regEx: SimpleSchema.RegEx.Url,
        optional: true
    },
    itemStyle: {
        type: String,
        optional: true
    }
});

Schemas.itemDetail = new SimpleSchema({
    itemName: {
        type: String
    },
    itemDesc: {
        type: String,
        optional: true
    },
    order: {
        type: Number,
        optional: true
    },
    list: {
        type: String
    },
    user: {
        type: String
    },
    itemUrl: {
        type: String,
        regEx: SimpleSchema.RegEx.Url,
        optional: true
    },
    itemBackground: {
        type: String,
        regEx: SimpleSchema.RegEx.Url,
        optional: true
    }
});

Schema.UserProfile = new SimpleSchema({
    firstName: {
        type: String,
        regEx: /^[a-zA-Z-]{2,25}$/,
        optional: true
    },
    lastName: {
        type: String,
        regEx: /^[a-zA-Z]{2,25}$/,
        optional: true
    },
    location: {
        type: String,
        optional: true
    },
    birthday: {
        type: Date,
        optional: true
    },
    gender: {
        type: String,
        allowedValues: ['Male', 'Female'],
        optional: true
    },
    organization : {
        type: String,
        regEx: /^[a-z0-9A-z .]{3,30}$/,
        optional: true
    },
    website: {
        type: String,
        regEx: SimpleSchema.RegEx.Url,
        optional: true
    },
    background: {
        type: String,
        regEx: SimpleSchema.RegEx.Url,
        optional: true
    },
    bio: {
        type: String,
        optional: true
    },
    country: {
        type: Schema.UserCountry,
        optional: true
    }
});

Schema.User = new SimpleSchema({
    username: {
        type: String,
        regEx: /^[a-z0-9A-Z_]{3,15}$/
    },
    emails: {
        type: [Object],
        // this must be optional if you also use other login services like facebook,
        // but if you use only accounts-password, then it can be required
        optional: true
    },
    "emails.$.address": {
        type: String,
        regEx: SimpleSchema.RegEx.Email
    },
    "emails.$.verified": {
        type: Boolean
    },
    createdAt: {
        type: Date
    },
    profile: {
        type: Schema.UserProfile,
        optional: true
    },
    services: {
        type: Object,
        optional: true,
        blackbox: true
    }
});

Meteor.users.attachSchema(Schema.User);
Lists.attachSchema(Schemas.listDetail);
Items.attachSchema(Schemas.itemDetail);


text:
require 'test_helper'

class DynamicFormHelperTest < ActiveSupport::TestCase
  # Replace this with your real tests.
  test "the truth" do
    assert true
  end
end


text:
use strict;
use warnings;
# This class is generated from DBIx.pm. Do not modify.

package WWW::Shopify::Model::DBIx::Schema::Result::Model::MetafieldShop;
use base qw/DBIx::Class::Core/;

__PACKAGE__->table('shopify_metafieldsshops');
__PACKAGE__->add_columns(
	'id', { data_type => 'INT', is_nullable => '0', is_auto_increment => 1 },
	'shop_id', { data_type => 'bigint', is_nullable => 0 },
	'metafield_id', { data_type => 'bigint', is_nullable => 0 }
);
__PACKAGE__->set_primary_key('id');
__PACKAGE__->belongs_to(shop => 'WWW::Shopify::Model::DBIx::Schema::Result::Model::Shop', 'shop_id');
__PACKAGE__->belongs_to(metafield => 'WWW::Shopify::Model::DBIx::Schema::Result::Model::Metafield', 'metafield_id');

1;


text:
__author__ = 'jason'

from NewsAggregator import NewsAggregator
from NewsArticle import NewsArticle
from XMLparser import *
from nltk.corpus import stopwords

countries = ["Greece"]

aggr = NewsAggregator(0.35)

xmlfiles = ["cbsnews.xml", "Global News.xml", "chathamdailynews.xml", "Sky-News.xml", "npr.xml",
            "whittierdailynews.xml", "dailynews.xml", "galvestondailynews.xml", "cbc.xml", "metro.xml", "Latimes.xml",
            "thestar.xml", "Huffingtonpost.xml", "express.xml", "rte.xml", "nwfdailynews.xml", "irishtimes.xml",
            "zeenews-india.xml", "scrippsobfeeds.xml", "Breaking News.xml", "abcnews.xml", "Independent.xml",
            "Yahoo.xml", "Telegraph.xml", "FOX News.xml", "nbcnews.xml", "news24.xml", "Reuters.xml", "Google.xml",
            "caribbeannewsnow.xml", "The Guardian.xml", "BBC.xml", "CNN.xml", "dailymail.xml", "sciencedaily.xml",
            "tvnz.xml"]

id = 0
for filename in xmlfiles:
    larct = parse(filename)
    for arcticle in larct:
        newarticle = NewsArticle(id, arcticle[1], arcticle[0], arcticle[4], arcticle[2], countries)
        newarticle.extract_metadata()
        aggr.add_article(newarticle)
        print id
        id += 1
        print aggr.topics

print "done"

print aggr.topics


text:
package com.iluwatar.prototype;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;

import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

/**
 * Date: 12/28/15 - 8:45 PM
 * @param <P> Prototype
 * @author Jeroen Meulemeester
 */
@RunWith(Parameterized.class)
public class PrototypeTest<P extends Prototype> {

  @Parameterized.Parameters
  public static Collection<Object[]> data() {
    return Arrays.asList(
            new Object[]{new OrcBeast(), "Orcish wolf"},
            new Object[]{new OrcMage(), "Orcish mage"},
            new Object[]{new OrcWarlord(), "Orcish warlord"},
            new Object[]{new ElfBeast(), "Elven eagle"},
            new Object[]{new ElfMage(), "Elven mage"},
            new Object[]{new ElfWarlord(), "Elven warlord"}
    );
  }

  /**
   * The tested prototype instance
   */
  private final P testedPrototype;

  /**
   * The expected {@link Prototype#toString()} value
   */
  private final String expectedToString;

  /**
   * Create a new test instance, using the given test object and expected value
   *
   * @param testedPrototype  The tested prototype instance
   * @param expectedToString The expected {@link Prototype#toString()} value
   */
  public PrototypeTest(final P testedPrototype, final String expectedToString) {
    this.expectedToString = expectedToString;
    this.testedPrototype = testedPrototype;
  }

  @Test
  public void testPrototype() throws Exception {
    assertEquals(this.expectedToString, this.testedPrototype.toString());

    final Object clone = this.testedPrototype.clone();
    assertNotNull(clone);
    assertNotSame(clone, this.testedPrototype);
    assertSame(this.testedPrototype.getClass(), clone.getClass());
  }

}


text:
@*
 * Copyright 2021 HM Revenue & Customs
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *@

@import iht.models.application.tnrb.TnrbEligibiltyModel
@import iht.config.AppConfig

@this(
    implicit val appConfig: AppConfig,
    form: FormWithCSRF,
    ihtMainTemplateApplication: iht_main_template_application,
    errorSummary: ihtHelpers.custom.error_summary,
    inputYesNoRadioGroup: ihtHelpers.standard.input_yes_no_radio_group,
    nameHelper: ihtHelpers.custom.name
)

@(estatePassedToDeceasedOrCharityForm:Form[TnrbEligibiltyModel],
deceasedName:String,
cancelUrl:Call)(implicit request:Request[_], messages: Messages)

@ihtMainTemplateApplication(
    title = "",
    browserTitle = Some(Messages("page.iht.application.tnrb.estatePassedToDeceasedOrCharity.browserTitle")),
    cancelLabel=Some(Messages("page.iht.application.tnrb.returnToIncreasingThreshold")),
    cancelUrl = Some(cancelUrl)
){
    @errorSummary(estatePassedToDeceasedOrCharityForm)

    @form(action = iht.controllers.application.tnrb.routes.EstatePassedToDeceasedOrCharityController.onSubmit,'autoComplete -> "off") {

        @inputYesNoRadioGroup(
            estatePassedToDeceasedOrCharityForm("isEstateBelowIhtThresholdApplied"),
            '_divClass -> Some("form-group"),
            '_legend -> Messages("page.iht.application.tnrb.estatePassedToDeceasedOrCharity.question", nameHelper(deceasedName)),
            '_legendClass -> Some("legend-with-heading"),
            '_legendIsHeading -> true,
            '_headingClass -> "heading-large"
        )

        <div id="action-button" class="form-group">
          <button class="button" id="save-continue" name="action" value="save">@Messages("iht.saveAndContinue")</button>
        </div>

     }
}


text:
import ruleComposer from "eslint-rule-composer";
import eslint from "eslint";

const rule = new eslint.Linter().getRules().get("object-curly-spacing");

export default ruleComposer.filterReports(rule, problem => {
  const node = problem.node;

  // Allow exportDefaultFrom syntax:
  // export x from '...';
  if (
    node.type === "ExportNamedDeclaration" &&
    node.specifiers.length === 1 &&
    node.specifiers[0].type === "ExportDefaultSpecifier"
  ) {
    return false;
  }

  return true;
});


text:
<?php

abstract class Dwoo_Plugin
{
	/**
	 * the dwoo instance that runs this plugin
	 *
	 * @var Dwoo
	 */
	protected $dwoo;

	/**
	 * constructor, if you override it, call parent::__construct($dwoo); or assign
	 * the dwoo instance yourself if you need it
	 *
	 * @param Dwoo $dwoo the dwoo instance that runs this plugin
	 */
	public function __construct(Dwoo $dwoo)
	{
		$this->dwoo = $dwoo;
	}

	// plugins should always implement :
	// public function process($arg, $arg, ...)
	// or for block plugins :
	// public function init($arg, $arg, ...)

	// this could be enforced with :
	// abstract public function process(...);
	// if my feature request gets enough interest one day
	// see => http://bugs.php.net/bug.php?id=44043

	/**
	 * utility function that converts an array of compiled parameters (or rest array) to a string of xml/html tag attributes
	 *
	 * this is to be used in preProcessing or postProcessing functions, example :
	 *  $p = $compiler->getCompiledParams($params);
	 *  // get only the rest array as attributes
	 *  $attributes = Dwoo_Plugin::paramsToAttributes($p['*']);
	 *  // get all the parameters as attributes (if there is a rest array, it will be included)
	 *  $attributes = Dwoo_Plugin::paramsToAttributes($p);
	 *
	 * @param array $params an array of attributeName=>value items that will be compiled to be ready for inclusion in a php string
	 * @param string $delim the string delimiter you want to use (defaults to ')
	 * @return string
	 */
	public static function paramsToAttributes(array $params, $delim = '\'')
	{
		if (isset($params['*'])) {
			$params = array_merge($params, $params['*']);
			unset($params['*']);
		}

		$out = '';
		foreach ($params as $attr=>$val) {
			$out .= ' '.$attr.'=';
			if (trim($val, '"\'')=='' || $val=='null') {
				$out .= str_replace($delim, '\\'.$delim, '""');
			} elseif (substr($val, 0, 1) === $delim && substr($val, -1) === $delim) {
				$out .= str_replace($delim, '\\'.$delim, '"'.substr($val, 1, -1).'"');
			} else {
				$out .= str_replace($delim, '\\'.$delim, '"') . $delim . '.'.$val.'.' . $delim . str_replace($delim, '\\'.$delim, '"');
			}
		}

		return ltrim($out);
	}
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>WorkerTaskData (worker-framework 10.13.0-SNAPSHOT API)</title>
<meta name="date" content="2016-10-11">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.hpe.caf.api.worker

Interface WorkerTaskData

All Known Subinterfaces:

WorkerTask

public interface WorkerTaskData

Represents a task to be completed by the CAF Worker.

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

String
getClassifier()

Retrieves an indicator of the type of the task

byte[]
getContext()

Retrieves any task specific context associated with the task

byte[]
getData()

Retrieves the actual task data in a serialised form

TaskSourceInfo
getSourceInfo()

Retrieves information relating to the source of the task

TaskStatus
getStatus()

Retrieves the task status

TrackingInfo
getTrackingInfo()

Retrieves tracking information associated with the task

int
getVersion()

Retrieves the version of the task message used

Method Detail

getClassifier

String getClassifier()

Retrieves an indicator of the type of the task

getVersion

int getVersion()

Retrieves the version of the task message used

getStatus

TaskStatus getStatus()

Retrieves the task status

getData

byte[] getData()

Retrieves the actual task data in a serialised form

getContext

byte[] getContext()

Retrieves any task specific context associated with the task

getTrackingInfo

TrackingInfo getTrackingInfo()

Retrieves tracking information associated with the task

getSourceInfo

TaskSourceInfo getSourceInfo()

Retrieves information relating to the source of the task

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2016. All rights reserved.


text:
"""Implementation for the app.events shortcuts."""
from __future__ import absolute_import, unicode_literals

from contextlib import contextmanager

from kombu.utils.objects import cached_property

class Events(object):
    """Implements app.events."""

    receiver_cls = 'celery.events.receiver:EventReceiver'
    dispatcher_cls = 'celery.events.dispatcher:EventDispatcher'
    state_cls = 'celery.events.state:State'

    def __init__(self, app=None):
        self.app = app

    @cached_property
    def Receiver(self):
        return self.app.subclass_with_self(
            self.receiver_cls, reverse='events.Receiver')

    @cached_property
    def Dispatcher(self):
        return self.app.subclass_with_self(
            self.dispatcher_cls, reverse='events.Dispatcher')

    @cached_property
    def State(self):
        return self.app.subclass_with_self(
            self.state_cls, reverse='events.State')

    @contextmanager
    def default_dispatcher(self, hostname=None, enabled=True,
                           buffer_while_offline=False):
        with self.app.amqp.producer_pool.acquire(block=True) as prod:
            # pylint: disable=too-many-function-args
            # This is a property pylint...
            with self.Dispatcher(prod.connection, hostname, enabled,
                                 prod.channel, buffer_while_offline) as d:
                yield d


text:
<?php
/**
 * Created by PhpStorm.
 * User: hong
 * Date: 16-11-9
 * Time: 下午9:39
 */

namespace O\DesignPatterns\Behavioral\Specification;

class NotSpecification implements SpecificationInterface
{
    /**
     * @var SpecificationInterface
     */
    private $specification;

    public function __construct(SpecificationInterface $specification)
    {
        $this->specification = $specification;
    }

    public function isSatisfiedBy(Item $item): bool
    {
        return !$this->specification->isSatisfiedBy($item);
    }
}


text:
// Copyright (C) 2000 - 2012 Philip Aston
// All rights reserved.
//
// This file is part of The Grinder software distribution. Refer to
// the file LICENSE which is part of The Grinder distribution for
// licensing details. The Grinder distribution is available on the
// Internet at http://grinder.sourceforge.net/
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
package net.grinder.console.communication;

import net.grinder.communication.*;
import net.grinder.console.common.DisplayMessageConsoleException;
import net.grinder.console.common.ErrorHandler;
import net.grinder.console.common.Resources;
import net.grinder.console.model.ConsoleCommunicationSetting;
import net.grinder.console.model.ConsoleProperties;
import net.grinder.util.TimeAuthority;
import net.grinder.util.thread.BooleanCondition;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.Thread.UncaughtExceptionHandler;
import java.net.Socket;

import static org.ngrinder.common.util.NoOp.noOp;

/**
 * Handles communication for the console. This is the extension of
 * {@link ConsoleCommunicationImplementation}.
 *
 * @author JunHo Yoon
 * @see ConsoleCommunicationImplementation
 * @since 3.0
 */
public final class ConsoleCommunicationImplementationEx implements ConsoleCommunication {

	private final Resources m_resources;
	private final ConsoleProperties m_properties;
	private final ErrorHandler m_errorHandler;
	private final TimeAuthority m_timeAuthority;
	private final long m_idlePollDelay;
	private long m_inactiveClientTimeOut;

	private final MessageDispatchSender m_messageDispatcher = new MessageDispatchSender();

	private final BooleanCondition m_processing = new BooleanCondition();
	private final BooleanCondition m_shutdown = new BooleanCondition();

	private Acceptor m_acceptor = null;
	private ServerReceiver m_receiver = null;
	private FanOutServerSender m_sender = null;
	private Thread m_acceptorProblemListener = null;
	private AcceptorResolver acceptorResolver = null;

	/**
	 * Constructor.
	 *
	 * @param resources             Resources.
	 * @param properties            Console properties.
	 * @param errorHandler          Error handler.
	 * @param timeAuthority         Knows the time
	 * @throws DisplayMessageConsoleException If properties are invalid.
	 */
	@SuppressWarnings("UnusedDeclaration")
	public ConsoleCommunicationImplementationEx(Resources resources, ConsoleProperties properties,
	                                            ErrorHandler errorHandler, TimeAuthority timeAuthority,
												ConsoleCommunicationSetting consoleCommunicationSetting) {
		m_resources = resources;
		m_properties = properties;
		m_errorHandler = errorHandler;
		m_timeAuthority = timeAuthority;
		if (consoleCommunicationSetting == null) {
			consoleCommunicationSetting = ConsoleCommunicationSetting.asDefault();
		}
		m_idlePollDelay = consoleCommunicationSetting.getIdlePollDelay();
		m_inactiveClientTimeOut = consoleCommunicationSetting.getInactiveClientTimeOut();

		properties.addPropertyChangeListener(new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent event) {
				final String property = event.getPropertyName();

				if (property.equals(ConsoleProperties.CONSOLE_HOST_PROPERTY)
						|| property.equals(ConsoleProperties.CONSOLE_PORT_PROPERTY)) {
					reset();
				}
			}
		});

		reset();
	}

	private void reset() {
		if (m_acceptorProblemListener != null) {
			m_acceptorProblemListener.interrupt();
			m_acceptorProblemListener = null;
		}

		try {
			if (m_acceptor != null) {
				m_acceptor.shutdown();
			}
		} catch (CommunicationException e) {
			m_errorHandler.handleException(e);
			return;
		}

		if (m_sender != null) {
			m_sender.shutdown();
		}

		if (m_receiver != null) {
			m_receiver.shutdown();

			// Wait until we're deaf. This requires that some other thread
			// executes
			// processOneMessage(). We can't suck on m_receiver ourself as there
			// may
			// be valid pending messages queued up.

			m_processing.await(false);
		}

		if (m_shutdown.get()) {
			return;
		}

		try {
			m_acceptor = new Acceptor(m_properties.getConsoleHost(), m_properties.getConsolePort(), 1, m_timeAuthority);
			acceptorResolver = new AcceptorResolver();
			acceptorResolver.addSocketListener(m_acceptor);
		} catch (CommunicationException e) {
			m_errorHandler.handleException(new DisplayMessageConsoleException(m_resources, "localBindError.text", e));

			// Wake up any threads waiting in processOneMessage().
			m_processing.wakeUpAllWaiters();

			return;
		}

		m_acceptorProblemListener = new Thread("Acceptor problem listener") {
			public void run() {
				while (true) {

					Exception exception = null;
					try {
						exception = m_acceptor.getPendingException();
					} catch (Exception e) {
						// FALL THROUGH
						noOp();
					}

					if (exception == null) {
						// Acceptor is shutting down.
						break;
					}

					m_errorHandler.handleException(exception);
				}
			}
		};

		m_acceptorProblemListener.setDaemon(true);
		// Ignore any exception in acceptor problem listener
		m_acceptorProblemListener.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
			@Override
			public void uncaughtException(Thread t, Throwable e) {
				m_errorHandler.handleInformationMessage(e.getMessage());
			}
		});
		m_acceptorProblemListener.start();

		m_receiver = new ServerReceiver();

		try {
			m_receiver.receiveFrom(m_acceptor, new ConnectionType[]{ConnectionType.AGENT,
					ConnectionType.CONSOLE_CLIENT, ConnectionType.WORKER,}, 5, m_idlePollDelay,
					m_inactiveClientTimeOut);
		} catch (CommunicationException e) {
			throw new AssertionError(e);
		}

		try {
			m_sender = new FanOutServerSender(m_acceptor, ConnectionType.AGENT, 3);
		} catch (Acceptor.ShutdownException e) {
			// I am tempted to make this an assertion.
			// Currently, this condition can only happen if the accept() call
			// throws
			// an exception. I guess this might reasonably happen if a network
			// i/f
			// goes away immediately after we create the Acceptor. It's not easy
			// for
			// us to reset ourselves at this point (I certainly don't want to
			// recurse), so we notify the user. Users could get going again by
			// reseting new console address info, but most likely they'll just
			// restart
			// the console.
			m_processing.wakeUpAllWaiters();
			m_errorHandler.handleException(e);
			return;
		}

		m_processing.set(true);
	}

	/**
	 * Returns the message dispatch registry which callers can use to register new message handlers.
	 *
	 * @return The registry.
	 */
	public MessageDispatchRegistry getMessageDispatchRegistry() {
		return m_messageDispatcher;
	}

	/**
	 * Shut down communication.
	 */
	public void shutdown() {
		m_shutdown.set(true);
		m_processing.set(false);
		reset();
	}

	/**
	 * Wait to receive a message, then process it.
	 *
	 * @return true if we processed a message successfully; false if we've
	 *         been shut down.
	 * @see #shutdown()
	 */
	public boolean processOneMessage() {
		while (true) {
			if (m_shutdown.get()) {
				return false;
			}

			if (m_processing.await(true)) {
				try {
					final Message message = m_receiver.waitForMessage();

					if (message == null) {
						// Current receiver has been shut down.
						m_processing.set(false);
					} else {
						m_messageDispatcher.send(message);
						return true;
					}
				} catch (CommunicationException e) {
					// The receive or send failed. We only set m_processing to
					// false when
					// our receiver has been shut down.
					m_errorHandler.handleException(e);
				}
			}
		}
	}

	public String getLocalConnectingAddress(Address agentAddress) {
		return acceptorResolver.getServerAddress(agentAddress);
	}

	/**
	 * The number of connections that have been accepted and are still active. Used by the unit
	 * tests.
	 *
	 * @return The number of accepted connections.
	 */
	@SuppressWarnings("UnusedDeclaration")
	public int getNumberOfConnections() {
		return m_acceptor == null ? 0 : m_acceptor.getNumberOfConnections();
	}

	/**
	 * Send the given message to the agent processes (which may pass it on to their workers).
	 *
	 *

	 * Any errors that occur will be handled with the error handler.
	 *

	 *
	 * @param message The message to send.
	 */
	public void sendToAgents(Message message) {
		if (m_sender == null) {
			m_errorHandler.handleErrorMessage(m_resources.getString("sendError.text"));
		} else {
			try {
				m_sender.send(message);
			} catch (CommunicationException e) {
				m_errorHandler.handleException(new DisplayMessageConsoleException(m_resources, "sendError.text", e));
			}
		}
	}

	/**
	 * Send the given message to the given agent processes (which may pass it on to its workers).
	 *
	 *

	 * Any errors that occur will be handled with the error handler.
	 *

	 *
	 * @param address The address to which the message should be sent.
	 * @param message The message to send.
	 */
	public void sendToAddressedAgents(Address address, Message message) {
		if (m_sender == null) {
			m_errorHandler.handleErrorMessage(m_resources.getString("sendError.text"));
		} else {
			try {
				m_sender.send(address, message);
			} catch (CommunicationException e) {
				m_errorHandler.handleException(new DisplayMessageConsoleException(m_resources, "sendError.text", e));
			}
		}
	}

	public void discriminateConnection(Socket socket) {
		try {
			m_acceptor.discriminateConnection(socket);
		} catch (Exception e) {
			m_errorHandler.handleException(new DisplayMessageConsoleException(m_resources, "sendError.text", e));
		}
	}
}


text:
// ==++==
//
//   Copyright (c) Microsoft Corporation.  All rights reserved.
//
// ==--==
/*=============================================================================
**
** Class: Thread
**
**
** Purpose: Class for creating and managing a thread.
**
**
=============================================================================*/

namespace System.Threading
{
    using System;
    using System.Threading;
    using System.Runtime.InteropServices;
////using System.Runtime.Remoting.Contexts;
////using System.Runtime.Remoting.Messaging;
    using System.Diagnostics;
////using System.Security.Permissions;
////using System.Security.Principal;
    using System.Globalization;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using System.Runtime.CompilerServices;
    using System.Runtime.ConstrainedExecution;
////using System.Security;
////using System.Runtime.Versioning;

////internal delegate Object InternalCrossContextDelegate( Object[] args );

////internal class ThreadHelper
////{
////    Delegate         m_start;
////    Object           m_startArg         = null;
////    ExecutionContext m_executionContext = null;
////
////    internal ThreadHelper( Delegate start )
////    {
////        m_start = start;
////    }
////
////    internal void SetExecutionContextHelper( ExecutionContext ec )
////    {
////        m_executionContext = ec;
////    }
////
////    static internal ContextCallback s_ccb = new ContextCallback( ThreadStart_Context );
////
////    static internal void ThreadStart_Context( Object state )
////    {
////        ThreadHelper t = (ThreadHelper)state;
////        if(t.m_start is ThreadStart)
////        {
////            ((ThreadStart)t.m_start)();
////        }
////        else
////        {
////            ((ParameterizedThreadStart)t.m_start)( t.m_startArg );
////        }
////    }
////
////    // call back helper
////    internal void ThreadStart( object obj )
////    {
////        m_startArg = obj;
////
////        if(m_executionContext != null)
////        {
////            ExecutionContext.Run( m_executionContext, s_ccb, (Object)this );
////        }
////        else
////        {
////            ((ParameterizedThreadStart)m_start)( obj );
////        }
////    }
////
////    // call back helper
////    internal void ThreadStart()
////    {
////        if(m_executionContext != null)
////        {
////            ExecutionContext.Run( m_executionContext, s_ccb, (Object)this );
////        }
////        else
////        {
////            ((ThreadStart)m_start)();
////        }
////    }
////}

    // deliberately not [serializable]
    [Microsoft.Zelig.Internals.WellKnownType( "System_Threading_Thread" )]
    public sealed class Thread : CriticalFinalizerObject
    {
////    /*=========================================================================
////    ** Data accessed from managed code that needs to be defined in
////    ** ThreadBaseObject to maintain alignment between the two classes.
////    ** DON'T CHANGE THESE UNLESS YOU MODIFY ThreadBaseObject in vm\object.h
////    =========================================================================*/
////    private Context          m_Context;
////
////    private ExecutionContext m_ExecutionContext;    // this call context follows the logical thread
        private String           m_Name;
////    private Delegate         m_Delegate;             // Delegate
////
////    private Object[][]       m_ThreadStaticsBuckets; // Holder for thread statics
////    private int[]            m_ThreadStaticsBits;    // Bit-markers for slot availability
////    private CultureInfo      m_CurrentCulture;
////    private CultureInfo      m_CurrentUICulture;
////    private Object           m_ThreadStartArg;
////
////    /*=========================================================================
////    ** The base implementation of Thread is all native.  The following fields
////    ** should never be used in the C# code.  They are here to define the proper
////    ** space so the thread object may be allocated.  DON'T CHANGE THESE UNLESS
////    ** YOU MODIFY ThreadBaseObject in vm\object.h
////    =========================================================================*/
////#pragma warning disable 169
////#pragma warning disable 414  // These fields are not used from managed.
////    // IntPtrs need to be together, and before ints, because IntPtrs are 64-bit
////    //  fields on 64-bit platforms, where they will be sorted together.
////
////    private IntPtr           DONT_USE_InternalThread;        // Pointer
////    private int              m_Priority;                     // INT32
////#pragma warning restore 414
////#pragma warning restore 169
////
////    /*=========================================================================
////    ** This manager is responsible for storing the global data that is
////    ** shared amongst all the thread local stores.
////    =========================================================================*/
////    static private LocalDataStoreMgr s_LocalDataStoreMgr;
////
////    /*=========================================================================
////    ** Thread-local data store
////    =========================================================================*/
////    [ThreadStatic]
////    static private LocalDataStoreHolder s_LocalDataStore;
////
////    // Has to be in sync with THREAD_STATICS_BUCKET_SIZE in vm/threads.cpp
////    private const int STATICS_BUCKET_SIZE = 32;

        /*=========================================================================
        ** Creates a new Thread object which will begin execution at
        ** start.ThreadStart on a new thread when the Start method is called.
        **
        ** Exceptions: ArgumentNullException if start == null.
        =========================================================================*/
        [MethodImpl( MethodImplOptions.InternalCall )]
        public extern Thread( ThreadStart start );
////    {
////        if(start == null)
////        {
////            throw new ArgumentNullException( "start" );
////        }
////
////        SetStartHelper( (Delegate)start, 0 );  //0 will setup Thread with default stackSize
////    }

////    public Thread( ThreadStart start, int maxStackSize )
////    {
////        if(start == null)
////        {
////            throw new ArgumentNullException( "start" );
////        }
////
////        if(0 > maxStackSize)
////        {
////            throw new ArgumentOutOfRangeException( "maxStackSize", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) );
////        }
////
////        SetStartHelper( (Delegate)start, maxStackSize );
////    }
////
////    public Thread( ParameterizedThreadStart start )
////    {
////        if(start == null)
////        {
////            throw new ArgumentNullException( "start" );
////        }
////
////        SetStartHelper( (Delegate)start, 0 );
////    }
////
////    public Thread( ParameterizedThreadStart start, int maxStackSize )
////    {
////        if(start == null)
////        {
////            throw new ArgumentNullException( "start" );
////        }
////
////        if(0 > maxStackSize)
////        {
////            throw new ArgumentOutOfRangeException( "maxStackSize", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) );
////        }
////
////        SetStartHelper( (Delegate)start, maxStackSize );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    public extern override int GetHashCode();

        public extern int ManagedThreadId
        {
////        [ResourceExposure( ResourceScope.None )]
////        [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
            [MethodImpl( MethodImplOptions.InternalCall )]
            get;
        }

        /*=========================================================================
        ** Spawns off a new thread which will begin executing at the ThreadStart
        ** method on the IThreadable interface passed in the constructor. Once the
        ** thread is dead, it cannot be restarted with another call to Start.
        **
        ** Exceptions: ThreadStateException if the thread has already been started.
        =========================================================================*/
////    [HostProtection( Synchronization = true, ExternalThreading = true )]
        [MethodImpl( MethodImplOptions.InternalCall )]
        public extern void Start();
////    {
////        // Attach current thread's security principal object to the new
////        // thread. Be careful not to bind the current thread to a principal
////        // if it's not already bound.
////        if(m_Delegate != null)
////        {
////            // If we reach here with a null delegate, something is broken. But we'll let the StartInternal method take care of
////            // reporting an error. Just make sure we dont try to dereference a null delegate.
////            ThreadHelper t = (ThreadHelper)(m_Delegate.Target);
////
////            ExecutionContext ec = ExecutionContext.Capture();
////
////            ExecutionContext.ClearSyncContext( ec );
////
////            t.SetExecutionContextHelper( ec );
////        }
////
////        IPrincipal principal = (IPrincipal)CallContext.Principal;
////
////        StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
////
////        StartInternal( principal, ref stackMark );
////    }

////    [HostProtection( Synchronization = true, ExternalThreading = true )]
////    public void Start( object parameter )
////    {
////        //In the case of a null delegate (second call to start on same thread)
////        //    StartInternal method will take care of the error reporting
////        if(m_Delegate is ThreadStart)
////        {
////            //We expect the thread to be setup with a ParameterizedThreadStart
////            //    if this constructor is called.
////            //If we got here then that wasn't the case
////            throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_ThreadWrongThreadStart" ) );
////        }
////
////        m_ThreadStartArg = parameter;
////        Start();
////    }
////
////    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
////    internal ExecutionContext GetExecutionContextNoCreate()
////    {
////        return m_ExecutionContext;
////    }
////
////
////    public ExecutionContext ExecutionContext
////    {
////        [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
////        get
////        {
////            if(m_ExecutionContext == null && this == Thread.CurrentThread)
////            {
////                m_ExecutionContext = new ExecutionContext();
////                m_ExecutionContext.Thread = this;
////            }
////
////            return m_ExecutionContext;
////        }
////    }
////
////    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
////    internal void SetExecutionContext( ExecutionContext value )
////    {
////        m_ExecutionContext = value;
////        if(value != null)
////        {
////            m_ExecutionContext.Thread = this;
////        }
////    }
////
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void StartInternal( IPrincipal principal, ref StackCrawlMark stackMark );
////
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
////    internal extern IntPtr SetAppDomainStack( SafeCompressedStackHandle csHandle );
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
////    internal extern void RestoreAppDomainStack( IntPtr appDomainStack );
////
////
////    // Helper method to get a logical thread ID for StringBuilder (for
////    // correctness) and for FileStream's async code path (for perf, to
////    // avoid creating a Thread instance).
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern static IntPtr InternalGetCurrentThread();
////
////    /*=========================================================================
////    ** Raises a ThreadAbortException in the thread, which usually
////    ** results in the thread's death. The ThreadAbortException is a special
////    ** exception that is not catchable. The finally clauses of all try
////    ** statements will be executed before the thread dies. This includes the
////    ** finally that a thread might be executing at the moment the Abort is raised.
////    ** The thread is not stopped immediately--you must Join on the
////    ** thread to guarantee it has stopped.
////    ** It is possible for a thread to do an unbounded amount of computation in
////    ** the finally's and thus indefinitely delay the threads death.
////    ** If Abort() is called on a thread that has not been started, the thread
////    ** will abort when Start() is called.
////    ** If Abort is called twice on the same thread, a DuplicateThreadAbort
////    ** exception is thrown.
////    =========================================================================*/
////
////    [SecurityPermissionAttribute( SecurityAction.Demand, ControlThread = true )]
////    public void Abort( Object stateInfo )
////    {
////        // If two aborts come at the same time, it is possible that the state info
////        //  gets set by one, and the actual abort gets delivered by another. But this
////        //  is not distinguishable by an application.
////        // The accessor helper will only set the value if it isn't already set,
////        //  and that particular bit of native code can test much faster than this
////        //  code could, because testing might cause a cross-appdomain marshalling.
////        AbortReason = stateInfo;
////
////        // Note: we demand ControlThread permission, then call AbortInternal directly
////        // rather than delegating to the Abort() function below. We do this to ensure
////        // that only callers with ControlThread are allowed to change the AbortReason
////        // of the thread. We call AbortInternal directly to avoid demanding the same
////        // permission twice.
////        AbortInternal();
////    }

////    [SecurityPermissionAttribute( SecurityAction.Demand, ControlThread = true )]
        public void Abort()
        {
            throw new NotImplementedException();
////        AbortInternal();
        }

////    // Internal helper (since we can't place security demands on
////    // ecalls/fcalls).
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void AbortInternal();
////
////    /*=========================================================================
////    ** Resets a thread abort.
////    ** Should be called by trusted code only
////      =========================================================================*/
////    [SecurityPermissionAttribute( SecurityAction.Demand, ControlThread = true )]
////    public static void ResetAbort()
////    {
////        Thread thread = Thread.CurrentThread;
////        if((thread.ThreadState & ThreadState.AbortRequested) == 0)
////        {
////            throw new ThreadStateException( Environment.GetResourceString( "ThreadState_NoAbortRequested" ) );
////        }
////
////        thread.ResetAbortNative();
////        thread.ClearAbortReason();
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void ResetAbortNative();
////
////    /*=========================================================================
////    ** Interrupts a thread that is inside a Wait(), Sleep() or Join().  If that
////    ** thread is not currently blocked in that manner, it will be interrupted
////    ** when it next begins to block.
////    =========================================================================*/
////    [SecurityPermission( SecurityAction.Demand, ControlThread = true )]
////    public void Interrupt()
////    {
////        InterruptInternal();
////    }
////
////    // Internal helper (since we can't place security demands on
////    // ecalls/fcalls).
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void InterruptInternal();

        /*=========================================================================
        ** Returns the priority of the thread.
        **
        ** Exceptions: ThreadStateException if the thread is dead.
        =========================================================================*/
        public extern ThreadPriority Priority
        {
            [MethodImpl( MethodImplOptions.InternalCall )]
            get;
////        {
////            return (ThreadPriority)GetPriorityNative();
////        }

////        [HostProtection( SelfAffectingThreading = true )]
            [MethodImpl( MethodImplOptions.InternalCall )]
            set;
////        {
////            SetPriorityNative( (int)value );
////        }
        }

////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern int GetPriorityNative();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void SetPriorityNative( int priority );

        /*=========================================================================
        ** Returns true if the thread has been started and is not dead.
        =========================================================================*/
        public extern bool IsAlive
        {
            [MethodImpl(MethodImplOptions.InternalCall)]
            get;
        }

////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern bool IsAliveNative();
////
////    /*=========================================================================
////    ** Returns true if the thread is a threadpool thread.
////    =========================================================================*/
////    public bool IsThreadPoolThread
////    {
////        get
////        {
////            return IsThreadpoolThreadNative();
////        }
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern bool IsThreadpoolThreadNative();
////
////    /*=========================================================================
////    ** Waits for the thread to die.
////    **
////    ** Exceptions: ThreadInterruptedException if the thread is interrupted while waiting.
////    **             ThreadStateException if the thread has not been started yet.
////    =========================================================================*/
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    [HostProtection( Synchronization = true, ExternalThreading = true )]
////    private extern void JoinInternal();

////    [HostProtection( Synchronization = true, ExternalThreading = true )]
        [MethodImpl( MethodImplOptions.InternalCall )]
        public extern void Join();
////    {
////        JoinInternal();
////    }

////    /*=========================================================================
////    ** Waits for the thread to die or for timeout milliseconds to elapse.
////    ** Returns true if the thread died, or false if the wait timed out. If
////    ** Timeout.Infinite is given as the parameter, no timeout will occur.
////    **
////    ** Exceptions: ArgumentException if timeout < 0.
////    **             ThreadInterruptedException if the thread is interrupted while waiting.
////    **             ThreadStateException if the thread has not been started yet.
////    =========================================================================*/
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    [HostProtection( Synchronization = true, ExternalThreading = true )]
////    private extern bool JoinInternal( int millisecondsTimeout );
////
////    [HostProtection( Synchronization = true, ExternalThreading = true )]
        [MethodImpl( MethodImplOptions.InternalCall )]
        public extern bool Join( int millisecondsTimeout );
////    {
////        return JoinInternal( millisecondsTimeout );
////    }
////
////    [HostProtection( Synchronization = true, ExternalThreading = true )]
        [MethodImpl( MethodImplOptions.InternalCall )]
        public extern bool Join( TimeSpan timeout );
////    {
////        long tm = (long)timeout.TotalMilliseconds;
////        if(tm < -1 || tm > (long)Int32.MaxValue)
////        {
////            throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) );
////        }
////
////        return Join( (int)tm );
////    }

        /*=========================================================================
        ** Suspends the current thread for timeout milliseconds. If timeout == 0,
        ** forces the thread to give up the remainer of its timeslice.  If timeout
        ** == Timeout.Infinite, no timeout will occur.
        **
        ** Exceptions: ArgumentException if timeout < 0.
        **             ThreadInterruptedException if the thread is interrupted while sleeping.
        =========================================================================*/
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private static extern void SleepInternal( int millisecondsTimeout );

        [MethodImpl( MethodImplOptions.InternalCall )]
        public static extern void Sleep( int millisecondsTimeout );
////    {
////        SleepInternal( millisecondsTimeout );
////    }

        [MethodImpl( MethodImplOptions.InternalCall )]
        public static extern void Sleep( TimeSpan timeout );
////    {
////        long tm = (long)timeout.TotalMilliseconds;
////        if(tm < -1 || tm > (long)Int32.MaxValue)
////        {
////            throw new ArgumentOutOfRangeException( "timeout", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegOrNegative1" ) );
////        }
////
////        Sleep( (int)tm );
////    }

////    /* wait for a length of time proportial to 'iterations'.  Each iteration is should
////       only take a few machine instructions.  Calling this API is preferable to coding
////       a explict busy loop because the hardware can be informed that it is busy waiting. */
////
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    [HostProtection( Synchronization = true, ExternalThreading = true )]
////    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
////    [ResourceExposure( ResourceScope.None )]
////    private static extern void SpinWaitInternal( int iterations );
////
////    [HostProtection( Synchronization = true, ExternalThreading = true )]
////    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
////    public static void SpinWait( int iterations )
////    {
////        SpinWaitInternal( iterations );
////    }

        public extern static Thread CurrentThread
        {
////        [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
            [MethodImpl( MethodImplOptions.InternalCall )]
            get;
////        {
////            Thread th = GetFastCurrentThreadNative();
////            if(th == null)
////            {
////                th = GetCurrentThreadNative();
////            }
////            return th;
////        }
        }

////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
////    private static extern Thread GetCurrentThreadNative();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
////    private static extern Thread GetFastCurrentThreadNative();
////
////    private void SetStartHelper( Delegate start, int maxStackSize )
////    {
////        ThreadHelper threadStartCallBack = new ThreadHelper( start );
////        if(start is ThreadStart)
////        {
////            SetStart( new ThreadStart( threadStartCallBack.ThreadStart ), maxStackSize );
////        }
////        else
////        {
////            SetStart( new ParameterizedThreadStart( threadStartCallBack.ThreadStart ), maxStackSize );
////        }
////    }
////
////    /*=========================================================================
////    ** PRIVATE Sets the IThreadable interface for the thread. Assumes that
////    ** start != null.
////    =========================================================================*/
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void SetStart( Delegate start, int maxStackSize );
////
////    /*=========================================================================
////    ** Clean up the thread when it goes away.
////    =========================================================================*/
////    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
////    ~Thread()
////    {
////        // Delegate to the unmanaged portion.
////        InternalFinalize();
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void InternalFinalize();

        /*=========================================================================
        ** Return whether or not this thread is a background thread.  Background
        ** threads do not affect when the Execution Engine shuts down.
        **
        ** Exceptions: ThreadStateException if the thread is dead.
        =========================================================================*/
        public extern bool IsBackground
        {
            [MethodImpl( MethodImplOptions.InternalCall )]
            get;
////        {
////            return IsBackgroundNative();
////        }

////        [HostProtection( SelfAffectingThreading = true )]
            [MethodImpl( MethodImplOptions.InternalCall )]
            set;
////        {
////            SetBackgroundNative( value );
////        }
        }

////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern bool IsBackgroundNative();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern void SetBackgroundNative( bool isBackground );
////
////
////    /*=========================================================================
////    ** Return the thread state as a consistent set of bits.  This is more
////    ** general then IsAlive or IsBackground.
////    =========================================================================*/
////    public ThreadState ThreadState
////    {
////        get
////        {
////            return (ThreadState)GetThreadStateNative();
////        }
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private extern int GetThreadStateNative();
////
////    /*=========================================================================
////    ** Allocates an un-named data slot. The slot is allocated on ALL the
////    ** threads.
////    =========================================================================*/
////    [HostProtection( SharedState = true, ExternalThreading = true )]
////    public static LocalDataStoreSlot AllocateDataSlot()
////    {
////        return LocalDataStoreManager.AllocateDataSlot();
////    }
////
////    /*=========================================================================
////    ** Allocates a named data slot. The slot is allocated on ALL the
////    ** threads.  Named data slots are "public" and can be manipulated by
////    ** anyone.
////    =========================================================================*/
////    [HostProtection( SharedState = true, ExternalThreading = true )]
////    public static LocalDataStoreSlot AllocateNamedDataSlot( String name )
////    {
////        return LocalDataStoreManager.AllocateNamedDataSlot( name );
////    }
////
////    /*=========================================================================
////    ** Looks up a named data slot. If the name has not been used, a new slot is
////    ** allocated.  Named data slots are "public" and can be manipulated by
////    ** anyone.
////    =========================================================================*/
////    [HostProtection( SharedState = true, ExternalThreading = true )]
////    public static LocalDataStoreSlot GetNamedDataSlot( String name )
////    {
////        return LocalDataStoreManager.GetNamedDataSlot( name );
////    }
////
////    /*=========================================================================
////    ** Frees a named data slot. The slot is allocated on ALL the
////    ** threads.  Named data slots are "public" and can be manipulated by
////    ** anyone.
////    =========================================================================*/
////    [HostProtection( SharedState = true, ExternalThreading = true )]
////    public static void FreeNamedDataSlot( String name )
////    {
////        LocalDataStoreManager.FreeNamedDataSlot( name );
////    }
////
////    /*=========================================================================
////    ** Retrieves the value from the specified slot on the current thread, for that thread's current domain.
////    =========================================================================*/
////    [HostProtection( SharedState = true, ExternalThreading = true )]
////    [ResourceExposure( ResourceScope.AppDomain )]
////    public static Object GetData( LocalDataStoreSlot slot )
////    {
////        LocalDataStoreHolder dls = s_LocalDataStore;
////        if(dls == null)
////        {
////            // Make sure to validate the slot even if we take the quick path
////            LocalDataStoreManager.ValidateSlot( slot );
////            return null;
////        }
////
////        return dls.Store.GetData( slot );
////    }
////
////    /*=========================================================================
////    ** Sets the data in the specified slot on the currently running thread, for that thread's current domain.
////    =========================================================================*/
////    [HostProtection( SharedState = true, ExternalThreading = true )]
////    [ResourceExposure( ResourceScope.AppDomain )]
////    public static void SetData( LocalDataStoreSlot slot, Object data )
////    {
////        LocalDataStoreHolder dls = s_LocalDataStore;
////
////        // Create new DLS if one hasn't been created for this domain for this thread
////        if(dls == null)
////        {
////            dls = LocalDataStoreManager.CreateLocalDataStore();
////
////            s_LocalDataStore = dls;
////        }
////
////        dls.Store.SetData( slot, data );
////    }
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    static extern private bool nativeGetSafeCulture( Thread t, int appDomainId, bool isUI, ref CultureInfo safeCulture );
////
////    // As the culture can be customized object then we cannot hold any
////    // reference to it before we check if it is safe because the app domain
////    // owning this customized culture may get unloaded while executing this
////    // code. To achieve that we have to do the check using nativeGetSafeCulture
////    // as the thread cannot get interrupted during the FCALL.
////    // If the culture is safe (not customized or created in current app domain)
////    // then the FCALL will return a reference to that culture otherwise the
////    // FCALL will return failure. In case of failure we'll return the default culture.
////    // If the app domain owning a customized culture that is set to teh thread and this
////    // app domain get unloaded there is a code to clean up the culture from the thread
////    // using the code in AppDomain::ReleaseDomainStores.
////
////    public CultureInfo CurrentUICulture
////    {
////        get
////        {
////            // Fetch a local copy of m_CurrentUICulture to
////            // avoid races that malicious user can introduce
////            if(m_CurrentUICulture == null)
////            {
////                return CultureInfo.UserDefaultUICulture;
////            }
////
////            CultureInfo culture = null;
////
////            if(!nativeGetSafeCulture( this, GetDomainID(), true, ref culture ) || culture == null)
////            {
////                return CultureInfo.UserDefaultUICulture;
////            }
////
////            return culture;
////        }
////
////        [HostProtection( ExternalThreading = true )]
////        set
////        {
////            if(value == null)
////            {
////                throw new ArgumentNullException( "value" );
////            }
////
////            //If they're trying to use a Culture with a name that we can't use in resource lookup,
////            //don't even let them set it on the thread.
////            CultureInfo.VerifyCultureName( value, true );
////
////            if(nativeSetThreadUILocale( value.LCID ) == false)
////            {
////                throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidResourceCultureName", value.Name ) );
////            }
////
////            value.StartCrossDomainTracking();
////
////            m_CurrentUICulture = value;
////        }
////    }
////
////    // This returns the exposed context for a given context ID.
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    static extern private bool nativeSetThreadUILocale( int LCID );

        // As the culture can be customized object then we cannot hold any
        // reference to it before we check if it is safe because the app domain
        // owning this customized culture may get unloaded while executing this
        // code. To achieve that we have to do the check using nativeGetSafeCulture
        // as the thread cannot get interrupted during the FCALL.
        // If the culture is safe (not customized or created in current app domain)
        // then the FCALL will return a reference to that culture otherwise the
        // FCALL will return failure. In case of failure we'll return the default culture.
        // If the app domain owning a customized culture that is set to teh thread and this
        // app domain get unloaded there is a code to clean up the culture from the thread
        // using the code in AppDomain::ReleaseDomainStores.

        public CultureInfo CurrentCulture
        {
            get
            {
////            // Fetch a local copy of m_CurrentCulture to
////            // avoid races that malicious user can introduce
////            if(m_CurrentCulture == null)
////            {
                    return CultureInfo.UserDefaultCulture;
////            }
////
////            CultureInfo culture = null;
////
////            if(!nativeGetSafeCulture( this, GetDomainID(), false, ref culture ) || culture == null)
////            {
////                return CultureInfo.UserDefaultCulture;
////            }
////
////            return culture;
            }

////        [SecurityPermission( SecurityAction.Demand, ControlThread = true )]
////        set
////        {
////            if(value == null)
////            {
////                throw new ArgumentNullException( "value" );
////            }
////
////            CultureInfo.CheckNeutral( value );
////
////            //If we can't set the nativeThreadLocale, we'll just let it stay
////            //at whatever value it had before.  This allows people who use
////            //just managed code not to be limited by the underlying OS.
////            CultureInfo.nativeSetThreadLocale( value.LCID );
////
////            value.StartCrossDomainTracking();
////
////            m_CurrentCulture = value;
////        }
        }

////    /*===============================================================
////    ====================== Thread Statics ===========================
////    ===============================================================*/
////    private int ReserveSlot()
////    {
////        // This is called by the thread on itself so no need for locks
////        if(m_ThreadStaticsBuckets == null)
////        {
////            BCLDebug.Assert( STATICS_BUCKET_SIZE % 32 == 0, "STATICS_BUCKET_SIZE should be a multiple of 32" );
////
////            // allocate bucket holder
////            // do not publish the data until all the intialization is done, in case of asynchronized exceptions
////            Object[][] newBuckets = new Object[1][];
////
////            SetIsThreadStaticsArray( newBuckets );
////
////            // allocate the first bucket
////            newBuckets[0] = new Object[STATICS_BUCKET_SIZE];
////            SetIsThreadStaticsArray( newBuckets[0] );
////
////            int[] newBits = new int[newBuckets.Length * STATICS_BUCKET_SIZE / 32];
////
////            // use memset!
////            for(int i = 0; i < newBits.Length; i++)
////            {
////                newBits[i] = unchecked( (int)0xffffffff );
////            }
////
////            // block the 0th position, we don't want any static to have
////            // slot #0 (we use it to indicate invalid slot)
////            newBits[0] &= ~1;
////
////            // also we clear the bit for slot #1, as that is the one we will be returning
////            newBits[0] &= ~2;
////
////            // now publish the arrays
////            // the write order matters here, because we check m_ThreadStaticsBuckets for initialization,
////            // we should write it at the last
////            m_ThreadStaticsBits    = newBits;
////            m_ThreadStaticsBuckets = newBuckets;
////
////            return 1;
////        }
////        int slot = FindSlot();
////
////        // slot == 0 => all slots occupied
////        if(slot == 0)
////        {
////            // We need to expand. Allocate a new bucket
////            int oldLength     = m_ThreadStaticsBuckets.Length;
////            int oldLengthBits = m_ThreadStaticsBits.Length;
////
////            int        newLength  = m_ThreadStaticsBuckets.Length + 1;
////            Object[][] newBuckets = new Object[newLength][];
////            SetIsThreadStaticsArray( newBuckets );
////
////            int   newLengthBits = newLength * STATICS_BUCKET_SIZE / 32;
////            int[] newBits       = new int[newLengthBits];
////
////            // Copy old buckets into new holder
////            Array.Copy( m_ThreadStaticsBuckets, newBuckets, m_ThreadStaticsBuckets.Length );
////
////            // Allocate new buckets
////            for(int i = oldLength; i < newLength; i++)
////            {
////                newBuckets[i] = new Object[STATICS_BUCKET_SIZE];
////                SetIsThreadStaticsArray( newBuckets[i] );
////            }
////
////
////            // Copy old bits into new bit array
////            Array.Copy( m_ThreadStaticsBits, newBits, m_ThreadStaticsBits.Length );
////
////            // Initalize new bits
////            for(int i = oldLengthBits; i < newLengthBits; i++)
////            {
////                newBits[i] = unchecked( (int)0xffffffff );
////            }
////
////            // Return the first slot in the expanded area
////            newBits[oldLengthBits] &= ~1;
////
////            // warning: if exceptions happen between the two writes, we are in a corrupted state
////            // but the chances are very low
////            m_ThreadStaticsBits    = newBits;
////            m_ThreadStaticsBuckets = newBuckets;
////
////            return oldLength * STATICS_BUCKET_SIZE;
////        }
////
////        return slot;
////    }
////
////    int FindSlot()
////    {
#if DEBUG
////        BCLDebug.Assert( m_ThreadStaticsBits != null, "m_ThreadStaticsBits must already be initialized" );
////        if(m_ThreadStaticsBits.Length != 0)
////        {
////            BCLDebug.Assert( m_ThreadStaticsBuckets != null && m_ThreadStaticsBits.Length == m_ThreadStaticsBuckets.Length * STATICS_BUCKET_SIZE / 32,
////                    "m_ThreadStaticsBuckets must already be intialized" );
////
////            for(int j = 0; j < m_ThreadStaticsBuckets.Length; j++)
////            {
////                BCLDebug.Assert( m_ThreadStaticsBuckets[j] != null && m_ThreadStaticsBuckets[j].Length == STATICS_BUCKET_SIZE,
////                                     "m_ThreadStaticsBuckets must already be initialized" );
////            }
////        }
#endif //DEBUG
////
////        int  slot = 0;   // 0 is not a valid slot number
////        int  bits = 0;
////        int  i;
////        bool bFound = false;
////
////        if(m_ThreadStaticsBits.Length != 0 && m_ThreadStaticsBits.Length != m_ThreadStaticsBuckets.Length * STATICS_BUCKET_SIZE / 32)
////        {
////            return 0;
////        }
////
////        for(i = 0; i < m_ThreadStaticsBits.Length; i++)
////        {
////            bits = m_ThreadStaticsBits[i];
////            if(bits != 0)
////            {
////                if((bits & 0xffff) != 0)
////                {
////                    bits = bits & 0xffff;
////                }
////                else
////                {
////                    bits = (bits >> 16) & 0xffff;
////                    slot += 16;
////                }
////
////                if((bits & 0xff) != 0)
////                {
////                    bits = bits & 0xff;
////                }
////                else
////                {
////                    slot += 8;
////                    bits = (bits >> 8) & 0xff;
////                }
////
////                int j;
////                for(j = 0; j < 8; j++)
////                {
////                    if((bits & (1 << j)) != 0)
////                    {
////                        bFound = true;
////                        break;
////                    }
////                }
////
////                BCLDebug.Assert( j < 8, "Bad bits?" );
////
////                slot += j;
////
////                m_ThreadStaticsBits[i] &= ~(1 << slot);
////                break;
////            }
////        }
////
////        if(bFound)
////        {
////            slot = slot + 32 * i;
////        }
////
////        BCLDebug.Assert( bFound || slot == 0, "Bad bits" );
////        return slot;
////    }
////    /*=============================================================*/
////
////    /*======================================================================
////    **  Current thread context is stored in a slot in the thread local store
////    **  CurrentContext gets the Context from the slot.
////    ======================================================================*/
////
////    public static Context CurrentContext
////    {
////        [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure )]
////        get
////        {
////            return CurrentThread.GetCurrentContextInternal();
////        }
////    }
////
////    internal Context GetCurrentContextInternal()
////    {
////        if(m_Context == null)
////        {
////            m_Context = Context.DefaultContext;
////        }
////
////        return m_Context;
////    }
////
////    [HostProtection( SharedState = true, ExternalThreading = true )]
////    internal LogicalCallContext GetLogicalCallContext()
////    {
////        return ExecutionContext.LogicalCallContext;
////    }
////
////    [HostProtection( SharedState = true, ExternalThreading = true )]
////    internal LogicalCallContext SetLogicalCallContext( LogicalCallContext callCtx )
////    {
////        LogicalCallContext oldCtx = ExecutionContext.LogicalCallContext;
////
////        ExecutionContext.LogicalCallContext = callCtx;
////
////        return oldCtx;
////    }
////
////    internal IllogicalCallContext GetIllogicalCallContext()
////    {
////        return ExecutionContext.IllogicalCallContext;
////    }
////
////    // Get and set thread's current principal (for role based security).
////    public static IPrincipal CurrentPrincipal
////    {
////        get
////        {
////            lock(CurrentThread)
////            {
////                IPrincipal principal = (IPrincipal)CallContext.Principal;
////                if(principal == null)
////                {
////                    principal = GetDomain().GetThreadPrincipal();
////
////                    CallContext.Principal = principal;
////                }
////
////                return principal;
////            }
////        }
////
////        [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal )]
////        set
////        {
////            CallContext.Principal = value;
////        }
////    }
////
////    // Private routine called from unmanaged code to set an initial
////    // principal for a newly created thread.
////    private void SetPrincipalInternal( IPrincipal principal )
////    {
////        GetLogicalCallContext().SecurityData.Principal = principal;
////    }
////
////    // This returns the exposed context for a given context ID.
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal static extern Context GetContextInternal( IntPtr id );
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern Object InternalCrossContextCallback( Context ctx, IntPtr ctxID, Int32 appDomainID, InternalCrossContextDelegate ftnToCall, Object[] args );
////
////    internal Object InternalCrossContextCallback( Context ctx, InternalCrossContextDelegate ftnToCall, Object[] args )
////    {
////        return InternalCrossContextCallback( ctx, ctx.InternalContextID, 0, ftnToCall, args );
////    }
////
////    // CompleteCrossContextCallback is called by the EE after transitioning to the requested context
////    private static Object CompleteCrossContextCallback( InternalCrossContextDelegate ftnToCall, Object[] args )
////    {
////        return ftnToCall( args );
////    }
////
////    /*======================================================================
////    ** Returns the current domain in which current thread is running.
////    ======================================================================*/
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private static extern AppDomain GetDomainInternal();
////
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private static extern AppDomain GetFastDomainInternal();
////
////    public static AppDomain GetDomain()
////    {
////        if(CurrentThread.m_Context == null)
////        {
////            AppDomain ad;
////            ad = GetFastDomainInternal();
////            if(ad == null)
////            {
////                ad = GetDomainInternal();
////            }
////
////            return ad;
////        }
////        else
////        {
////            BCLDebug.Assert( GetDomainInternal() == CurrentThread.m_Context.AppDomain, "AppDomains on the managed & unmanaged threads should match" );
////            return CurrentThread.m_Context.AppDomain;
////        }
////    }
////
////
////    /*
////     *  This returns a unique id to identify an appdomain.
////     */
////    public static int GetDomainID()
////    {
////        return GetDomain().GetId();
////    }

        // Retrieves the name of the thread.
        //
        public String Name
        {
            get
            {
                return m_Name;

            }

////        [HostProtection( ExternalThreading = true )]
            set
            {
                lock(this)
                {
                    if(m_Name != null)
                    {
#if EXCEPTION_STRINGS
                        throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_WriteOnce" ) );
#else
                        throw new InvalidOperationException();
#endif
                    }

                    m_Name = value;

////                InformThreadNameChangeEx( this, m_Name );
                }
            }
        }

////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal static extern void InformThreadNameChangeEx( Thread t, String name );
////
////    internal Object AbortReason
////    {
////        get
////        {
////            object result = null;
////
////            try
////            {
////                result = GetAbortReason();
////            }
////            catch(Exception e)
////            {
////                throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_ExceptionStateCrossAppDomain" ), e );
////            }
////
////            return result;
////        }
////
////        set
////        {
////            SetAbortReason( value );
////        }
////    }

        /*
         *  This marks the beginning of a critical code region.
         */
////    [HostProtection( Synchronization = true, ExternalThreading = true )]
////    [ResourceExposure( ResourceScope.None )]
        [MethodImpl( MethodImplOptions.InternalCall )]
////    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
        public static extern void BeginCriticalRegion();

        /*
         *  This marks the end of a critical code region.
         */
////    [HostProtection( Synchronization = true, ExternalThreading = true )]
////    [ResourceExposure( ResourceScope.None )]
        [MethodImpl( MethodImplOptions.InternalCall )]
////    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
        public static extern void EndCriticalRegion();

////    /*
////     *  This marks the beginning of a code region that requires thread affinity.
////     */
////    [SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlThread = true )]
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
////    public static extern void BeginThreadAffinity();
////
////    /*
////     *  This marks the end of a code region that requires thread affinity.
////     */
////    [SecurityPermissionAttribute( SecurityAction.LinkDemand, ControlThread = true )]
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
////    public static extern void EndThreadAffinity();

        /*=========================================================================
        ** Volatile Read & Write and MemoryBarrier methods.
        ** Provides the ability to read and write values ensuring that the values
        ** are read/written each time they are accessed.
        =========================================================================*/

        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static byte VolatileRead( ref byte address )
        {
            byte ret = address;

            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            return ret;
        }

        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static short VolatileRead( ref short address )
        {
            short ret = address;

            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            return ret;
        }

        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static int VolatileRead( ref int address )
        {
            int ret = address;

            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            return ret;
        }

        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static long VolatileRead( ref long address )
        {
            long ret = address;

            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            return ret;
        }

        [CLSCompliant( false )]
        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static sbyte VolatileRead( ref sbyte address )
        {
            sbyte ret = address;

            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            return ret;
        }

        [CLSCompliant( false )]
        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static ushort VolatileRead( ref ushort address )
        {
            ushort ret = address;

            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            return ret;
        }

        [CLSCompliant( false )]
        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static uint VolatileRead( ref uint address )
        {
            uint ret = address;

            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            return ret;
        }

        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static IntPtr VolatileRead( ref IntPtr address )
        {
            IntPtr ret = address;

            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            return ret;
        }

        [CLSCompliant( false )]
        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static UIntPtr VolatileRead( ref UIntPtr address )
        {
            UIntPtr ret = address;

            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            return ret;
        }

        [CLSCompliant( false )]
        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static ulong VolatileRead( ref ulong address )
        {
            ulong ret = address;

            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            return ret;
        }

        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static float VolatileRead( ref float address )
        {
            float ret = address;

            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            return ret;
        }

        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static double VolatileRead( ref double address )
        {
            double ret = address;

            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            return ret;
        }

        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static Object VolatileRead( ref Object address )
        {
            Object ret = address;

            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            return ret;
        }

        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static void VolatileWrite( ref byte address, byte value )
        {
            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            address = value;
        }

        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static void VolatileWrite( ref short address, short value )
        {
            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            address = value;
        }

        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static void VolatileWrite( ref int address, int value )
        {
            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            address = value;
        }

        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static void VolatileWrite( ref long address, long value )
        {
            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            address = value;
        }

        [CLSCompliant( false )]
        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static void VolatileWrite( ref sbyte address, sbyte value )
        {
            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            address = value;
        }

        [CLSCompliant( false )]
        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static void VolatileWrite( ref ushort address, ushort value )
        {
            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            address = value;
        }

        [CLSCompliant( false )]
        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static void VolatileWrite( ref uint address, uint value )
        {
            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            address = value;
        }

        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static void VolatileWrite( ref IntPtr address, IntPtr value )
        {
            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            address = value;
        }

        [CLSCompliant( false )]
        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static void VolatileWrite( ref UIntPtr address, UIntPtr value )
        {
            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            address = value;
        }

        [CLSCompliant( false )]
        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static void VolatileWrite( ref ulong address, ulong value )
        {
            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            address = value;
        }

        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static void VolatileWrite( ref float address, float value )
        {
            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
            address = value;
        }

        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static void VolatileWrite( ref double address, double value )
        {
            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            address = value;
        }

        [MethodImpl( MethodImplOptions.NoInlining )] // disable optimizations
        public static void VolatileWrite( ref Object address, Object value )
        {
            MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.

            address = value;
        }

////    [ResourceExposure( ResourceScope.None )]
        [MethodImpl( MethodImplOptions.InternalCall )]
        public static extern void MemoryBarrier();

////    //We need to mark thread statics array for AppDomain leak checking purpose
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    private static extern void SetIsThreadStaticsArray( Object o );
////
////    private static LocalDataStoreMgr LocalDataStoreManager
////    {
////        get
////        {
////            if(s_LocalDataStoreMgr == null)
////            {
////                Interlocked.CompareExchange( ref s_LocalDataStoreMgr, new LocalDataStoreMgr(), null );
////            }
////
////            return s_LocalDataStoreMgr;
////        }
////    }
////
////    // Helper function to set the AbortReason for a thread abort.
////    //  Checks that they're not alredy set, and then atomically updates
////    //  the reason info (object + ADID).
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern void SetAbortReason( Object o );
////
////    // Helper function to retrieve the AbortReason from a thread
////    //  abort.  Will perform cross-AppDomain marshalling if the object
////    //  lives in a different AppDomain from the requester.
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern Object GetAbortReason();
////
////    // Helper function to clear the AbortReason.  Takes care of
////    //  AppDomain related cleanup if required.
////    [ResourceExposure( ResourceScope.None )]
////    [MethodImpl( MethodImplOptions.InternalCall )]
////    internal extern void ClearAbortReason();
    } // End of class Thread

    // declaring a local var of this enum type and passing it by ref into a function that needs to do a
    // stack crawl will both prevent inlining of the calle and pass an ESP point to stack crawl to
    // Declaring these in EH clauses is illegal; they must declared in the main method body
    [Serializable]
    internal enum StackCrawlMark
    {
        LookForMe              = 0,
        LookForMyCaller        = 1,
        LookForMyCallersCaller = 2,
        LookForThread          = 3,
    }
}


text:
namespace spvtools {
namespace fuzz {
namespace {

TEST(TransformationAddTypeVectorTest, BasicTest) {
  std::string shader = R"(
               OpCapability Shader
          %1 = OpExtInstImport "GLSL.std.450"
               OpMemoryModel Logical GLSL450
               OpEntryPoint Fragment %4 "main"
               OpExecutionMode %4 OriginUpperLeft
               OpSource ESSL 310
          %2 = OpTypeVoid
          %3 = OpTypeFunction %2
          %6 = OpTypeFloat 32
          %7 = OpTypeInt 32 1
          %8 = OpTypeInt 32 0
          %9 = OpTypeBool
          %4 = OpFunction %2 None %3
          %5 = OpLabel
               OpReturn
               OpFunctionEnd
  )";

  const auto env = SPV_ENV_UNIVERSAL_1_4;
  const auto consumer = nullptr;
  const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption);
  spvtools::ValidatorOptions validator_options;
  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));
  TransformationContext transformation_context(
      MakeUnique<FactManager>(context.get()), validator_options);
  // Id already in use
  ASSERT_FALSE(TransformationAddTypeVector(4, 6, 2).IsApplicable(
      context.get(), transformation_context));
  // %1 is not a type
  ASSERT_FALSE(TransformationAddTypeVector(100, 1, 2).IsApplicable(
      context.get(), transformation_context));

  {
    // %100 = OpTypeVector %6 2
    TransformationAddTypeVector transformation(100, 6, 2);
    ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(100));
    ASSERT_EQ(nullptr, context->get_type_mgr()->GetType(100));
    ASSERT_TRUE(
        transformation.IsApplicable(context.get(), transformation_context));
    ApplyAndCheckFreshIds(transformation, context.get(),
                          &transformation_context);
    ASSERT_EQ(spv::Op::OpTypeVector,
              context->get_def_use_mgr()->GetDef(100)->opcode());
    ASSERT_NE(nullptr, context->get_type_mgr()->GetType(100)->AsVector());
  }

  TransformationAddTypeVector transformations[] = {
      // %101 = OpTypeVector %7 3
      TransformationAddTypeVector(101, 7, 3),

      // %102 = OpTypeVector %8 4
      TransformationAddTypeVector(102, 8, 4),

      // %103 = OpTypeVector %9 2
      TransformationAddTypeVector(103, 9, 2)};

  for (auto& transformation : transformations) {
    ASSERT_TRUE(
        transformation.IsApplicable(context.get(), transformation_context));
    ApplyAndCheckFreshIds(transformation, context.get(),
                          &transformation_context);
  }
  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));

  std::string after_transformation = R"(
               OpCapability Shader
          %1 = OpExtInstImport "GLSL.std.450"
               OpMemoryModel Logical GLSL450
               OpEntryPoint Fragment %4 "main"
               OpExecutionMode %4 OriginUpperLeft
               OpSource ESSL 310
          %2 = OpTypeVoid
          %3 = OpTypeFunction %2
          %6 = OpTypeFloat 32
          %7 = OpTypeInt 32 1
          %8 = OpTypeInt 32 0
          %9 = OpTypeBool
        %100 = OpTypeVector %6 2
        %101 = OpTypeVector %7 3
        %102 = OpTypeVector %8 4
        %103 = OpTypeVector %9 2
          %4 = OpFunction %2 None %3
          %5 = OpLabel
               OpReturn
               OpFunctionEnd
  )";
  ASSERT_TRUE(IsEqual(env, after_transformation, context.get()));
}

}  // namespace
}  // namespace fuzz
}  // namespace spvtools


text:
module.exports = {
  cond: require('./cond')
};