text:
'use strict';

/**
 * @class
 * Initializes a new instance of the PowerShellCommandParameters class.
 * @constructor
 * the parameters to a powershell script execution command
 * @member {string} [command] Script to execute
 *
 */
function PowerShellCommandParameters() {
}

/**
 * Defines the metadata of PowerShellCommandParameters
 *
 * @returns {object} metadata of PowerShellCommandParameters
 *
 */
PowerShellCommandParameters.prototype.mapper = function () {
  return {
    required: false,
    serializedName: 'PowerShellCommandParameters',
    type: {
      name: 'Composite',
      className: 'PowerShellCommandParameters',
      modelProperties: {
        command: {
          required: false,
          serializedName: 'properties.command',
          type: {
            name: 'String'
          }
        }
      }
    }
  };
};

module.exports = PowerShellCommandParameters;

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<Form xmlns="http://v8.1c.ru/8.3/xcf/logform" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core" xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.1">
	<AutoCommandBar name="ФормаКоманднаяПанель" id="-1">
		<Autofill>false</Autofill>
	</AutoCommandBar>
	<Events>
		<Event name="OnCreateAtServer">ПриСозданииНаСервере</Event>
	</Events>
	<ChildItems>
		<UsualGroup name="ГруппаОтборов" id="12">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Группа отборов</v8:content>
				</v8:item>
			</Title>
			<ToolTip>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Группа отборов</v8:content>
				</v8:item>
			</ToolTip>
			<Group>Horizontal</Group>
			<Representation>None</Representation>
			<ShowTitle>false</ShowTitle>
			<ExtendedTooltip name="ГруппаОтборовExtendedTooltip" id="19"/>
			<ChildItems>
				<InputField name="Организация" id="13">
					<DataPath>Организация</DataPath>
					<ClearButton>true</ClearButton>
					<OpenButton>false</OpenButton>
					<QuickChoice>true</QuickChoice>
					<ContextMenu name="ОрганизацияКонтекстноеМеню" id="14"/>
					<ExtendedTooltip name="ОрганизацияExtendedTooltip" id="20"/>
					<Events>
						<Event name="OnChange">ОрганизацияПриИзменении</Event>
					</Events>
				</InputField>
				<InputField name="Склад" id="15">
					<DataPath>Склад</DataPath>
					<ClearButton>true</ClearButton>
					<OpenButton>false</OpenButton>
					<QuickChoice>true</QuickChoice>
					<ContextMenu name="СкладКонтекстноеМеню" id="16"/>
					<ExtendedTooltip name="СкладExtendedTooltip" id="21"/>
					<Events>
						<Event name="OnChange">СкладПриИзменении</Event>
					</Events>
				</InputField>
			</ChildItems>
		</UsualGroup>
		<UsualGroup name="ГруппаПользовательскихНастроек" id="31">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Группа пользовательских настроек</v8:content>
				</v8:item>
			</Title>
			<ToolTip>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Группа пользовательских настроек</v8:content>
				</v8:item>
			</ToolTip>
			<Group>Vertical</Group>
			<Representation>None</Representation>
			<ShowTitle>false</ShowTitle>
			<ExtendedTooltip name="ГруппаПользовательскихНастроекРасширеннаяПодсказка" id="32"/>
		</UsualGroup>
		<CommandBar name="КоманднаяПанель" id="33">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Командная панель</v8:content>
				</v8:item>
			</Title>
			<ToolTip>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Командная панель</v8:content>
				</v8:item>
			</ToolTip>
			<CommandSource>Form</CommandSource>
			<ExtendedTooltip name="КоманднаяПанельРасширеннаяПодсказка" id="34"/>
		</CommandBar>
		<Table name="Список" id="1">
			<Representation>List</Representation>
			<CommandBarLocation>None</CommandBarLocation>
			<DefaultItem>true</DefaultItem>
			<Height>10</Height>
			<UseAlternationRowColor>true</UseAlternationRowColor>
			<InitialTreeView>ExpandTopLevel</InitialTreeView>
			<EnableStartDrag>true</EnableStartDrag>
			<DataPath>Список</DataPath>
			<RowPictureDataPath>Список.DefaultPicture</RowPictureDataPath>
			<SearchStringLocation>None</SearchStringLocation>
			<ViewStatusLocation>None</ViewStatusLocation>
			<SearchControlLocation>None</SearchControlLocation>
			<AutoRefresh>false</AutoRefresh>
			<AutoRefreshPeriod>60</AutoRefreshPeriod>
			<Period>
				<v8:variant xsi:type="v8:StandardPeriodVariant">Custom</v8:variant>
				<v8:startDate>0001-01-01T00:00:00</v8:startDate>
				<v8:endDate>0001-01-01T00:00:00</v8:endDate>
			</Period>
			<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>
			<RestoreCurrentRow>false</RestoreCurrentRow>
			<TopLevelParent xsi:nil="true"/>
			<ShowRoot>true</ShowRoot>
			<AllowRootChoice>false</AllowRootChoice>
			<UpdateOnDataChange>Auto</UpdateOnDataChange>
			<UserSettingsGroup>ГруппаПользовательскихНастроек</UserSettingsGroup>
			<ContextMenu name="СписокКонтекстноеМеню" id="2"/>
			<AutoCommandBar name="СписокКоманднаяПанель" id="3">
				<Autofill>false</Autofill>
			</AutoCommandBar>
			<ExtendedTooltip name="СписокExtendedTooltip" id="22"/>
			<SearchStringAddition name="СписокSearchString" id="52">
				<AdditionSource>
					<Item>Список</Item>
					<Type>SearchStringRepresentation</Type>
				</AdditionSource>
				<ContextMenu name="СписокSearchStringContextMenu" id="53"/>
				<ExtendedTooltip name="СписокSearchStringExtendedTooltip" id="54"/>
			</SearchStringAddition>
			<ViewStatusAddition name="СписокViewStatus" id="55">
				<AdditionSource>
					<Item>Список</Item>
					<Type>ViewStatusRepresentation</Type>
				</AdditionSource>
				<ContextMenu name="СписокViewStatusContextMenu" id="56"/>
				<ExtendedTooltip name="СписокViewStatusExtendedTooltip" id="57"/>
			</ViewStatusAddition>
			<SearchControlAddition name="СписокSearchControl" id="58">
				<AdditionSource>
					<Item>Список</Item>
					<Type>SearchControl</Type>
				</AdditionSource>
				<ContextMenu name="СписокSearchControlContextMenu" id="59"/>
				<ExtendedTooltip name="СписокSearchControlExtendedTooltip" id="60"/>
			</SearchControlAddition>
			<ChildItems>
				<ColumnGroup name="ДатаНомер" id="35">
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Дата номер</v8:content>
						</v8:item>
					</Title>
					<ToolTip>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Дата номер</v8:content>
						</v8:item>
					</ToolTip>
					<ExtendedTooltip name="ДатаНомерРасширеннаяПодсказка" id="36"/>
					<ChildItems>
						<LabelField name="Дата" id="4">
							<DataPath>Список.Date</DataPath>
							<DefaultItem>true</DefaultItem>
							<Width>9</Width>
							<ContextMenu name="ДатаКонтекстноеМеню" id="5"/>
							<ExtendedTooltip name="ДатаExtendedTooltip" id="23"/>
						</LabelField>
						<LabelField name="Номер" id="6">
							<DataPath>Список.Number</DataPath>
							<Width>12</Width>
							<HorizontalStretch>false</HorizontalStretch>
							<ContextMenu name="НомерКонтекстноеМеню" id="7"/>
							<ExtendedTooltip name="НомерExtendedTooltip" id="24"/>
						</LabelField>
					</ChildItems>
				</ColumnGroup>
				<ColumnGroup name="КонтрагентОрганизация" id="37">
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Контрагент организация</v8:content>
						</v8:item>
					</Title>
					<ExtendedTooltip name="КонтрагентОрганизацияРасширеннаяПодсказка" id="38"/>
					<ChildItems>
						<LabelField name="Партнер" id="8">
							<DataPath>Список.Партнер</DataPath>
							<ContextMenu name="ПартнерКонтекстноеМеню" id="9"/>
							<ExtendedTooltip name="ПартнерРасширеннаяПодсказка" id="25"/>
						</LabelField>
						<LabelField name="ГоловнаяОрганизация" id="39">
							<DataPath>Список.ГоловнаяОрганизация</DataPath>
							<ContextMenu name="ГоловнаяОрганизацияКонтекстноеМеню" id="40"/>
							<ExtendedTooltip name="ГоловнаяОрганизацияРасширеннаяПодсказка" id="41"/>
						</LabelField>
					</ChildItems>
				</ColumnGroup>
				<ColumnGroup name="МестоХраненияОтветственныйКомментарий" id="42">
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Место хранения ответственный комментарий</v8:content>
						</v8:item>
					</Title>
					<ExtendedTooltip name="МестоХраненияОтветственныйКомментарийРасширеннаяПодсказка" id="43"/>
					<ChildItems>
						<ColumnGroup name="МестоХраненияОтветственный" id="44">
							<Title>
								<v8:item>
									<v8:lang>ru</v8:lang>
									<v8:content>Место хранения ответственный</v8:content>
								</v8:item>
							</Title>
							<ToolTip>
								<v8:item>
									<v8:lang>ru</v8:lang>
									<v8:content>Место хранения ответственный</v8:content>
								</v8:item>
							</ToolTip>
							<Group>Horizontal</Group>
							<ExtendedTooltip name="МестоХраненияОтветственныйРасширеннаяПодсказка" id="45"/>
							<ChildItems>
								<LabelField name="МестоХранения" id="10">
									<DataPath>Список.МестоХранения</DataPath>
									<ContextMenu name="МестоХраненияКонтекстноеМеню" id="11"/>
									<ExtendedTooltip name="МестоХраненияExtendedTooltip" id="26"/>
								</LabelField>
								<LabelField name="Ответственный" id="49">
									<DataPath>Список.Ответственный</DataPath>
									<ContextMenu name="ОтветственныйКонтекстноеМеню" id="50"/>
									<ExtendedTooltip name="ОтветственныйРасширеннаяПодсказка" id="51"/>
								</LabelField>
							</ChildItems>
						</ColumnGroup>
						<LabelField name="Комментарий" id="46">
							<DataPath>Список.Комментарий</DataPath>
							<ContextMenu name="КомментарийКонтекстноеМеню" id="47"/>
							<ExtendedTooltip name="КомментарийРасширеннаяПодсказка" id="48"/>
						</LabelField>
					</ChildItems>
				</ColumnGroup>
				<LabelField name="Ссылка" id="28">
					<DataPath>Список.Ref</DataPath>
					<UserVisible>
						<xr:Common>false</xr:Common>
					</UserVisible>
					<Width>1</Width>
					<HorizontalStretch>false</HorizontalStretch>
					<ContextMenu name="СсылкаКонтекстноеМеню" id="29"/>
					<ExtendedTooltip name="СсылкаРасширеннаяПодсказка" id="30"/>
				</LabelField>
			</ChildItems>
		</Table>
	</ChildItems>
	<Attributes>
		<Attribute name="Список" id="1">
			<Type>
				<v8:Type>cfg:DynamicList</v8:Type>
			</Type>
			<MainAttribute>true</MainAttribute>
			<UseAlways>
				<Field>Список.Ref</Field>
			</UseAlways>
			<Settings xsi:type="DynamicList">
				<ManualQuery>false</ManualQuery>
				<DynamicDataRead>true</DynamicDataRead>
				<MainTable>Document._ДемоРеализацияТоваров</MainTable>
				<ListSettings>
					<dcsset:filter>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>dfcece9d-5077-440b-b6b3-45a5cb4538eb</dcsset:userSettingID>
					</dcsset:filter>
					<dcsset:order>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>88619765-ccb3-46c6-ac52-38e9c992ebd4</dcsset:userSettingID>
					</dcsset:order>
					<dcsset:conditionalAppearance>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>b75fecce-942b-4aed-abc9-e6a02e460fb3</dcsset:userSettingID>
					</dcsset:conditionalAppearance>
					<dcsset:itemsViewMode>Normal</dcsset:itemsViewMode>
					<dcsset:itemsUserSettingID>911b6018-f537-43e8-a417-da56b22f9aec</dcsset:itemsUserSettingID>
				</ListSettings>
			</Settings>
		</Attribute>
		<Attribute name="Организация" id="2">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Организация</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>cfg:CatalogRef._ДемоОрганизации</v8:Type>
			</Type>
			<FunctionalOptions>
				<Item>ab0b6824-99ba-4b8d-857d-ed8ef017d499</Item>
			</FunctionalOptions>
		</Attribute>
		<Attribute name="Склад" id="3">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Склад</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>cfg:CatalogRef._ДемоМестаХранения</v8:Type>
			</Type>
		</Attribute>
	</Attributes>
</Form>


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Cocos2D;

namespace Cocos2D
{
    //
    // CCTimer
    //
    /** @brief Light weight timer */

    public class CCTimer : ICCSelectorProtocol
    {
        private CCScheduler _scheduler;
        private readonly ICCSelectorProtocol m_pTarget;

        private readonly bool m_bRunForever;
        private readonly float m_fDelay;
        private readonly uint m_uRepeat; //0 = once, 1 is 2 x executed
        private float m_fElapsed;
        private bool m_bUseDelay;

        //private int m_nScriptHandler;
        private uint m_uTimesExecuted;

        public float OriginalInterval;
        public float Interval;
        public Action<float> Selector;

        public CCTimer()
        {
        }

        /** Initializes a timer with a target and a selector.
         */

        public CCTimer(CCScheduler scheduler, ICCSelectorProtocol target, Action<float> selector)
            : this(scheduler, target, selector, 0, 0, 0)
        {
        }

        /** Initializes a timer with a target, a selector and an interval in seconds.
         *  Target is not needed in c#, it is just for compatibility.
         */

        public CCTimer(CCScheduler scheduler, ICCSelectorProtocol target, Action<float> selector, float seconds)
            : this(scheduler, target, selector, seconds, 0, 0)
        {
        }

        public CCTimer(CCScheduler scheduler, ICCSelectorProtocol target, Action<float> selector, float seconds,
                       uint repeat, float delay)
        {
            _scheduler = scheduler;
            m_pTarget = target;
            Selector = selector;
            m_fElapsed = -1;
            OriginalInterval = seconds;
            Interval = seconds;
            m_fDelay = delay;
            m_bUseDelay = delay > 0f;
            m_uRepeat = repeat;
            m_bRunForever = m_uRepeat == uint.MaxValue;
        }

        /*
        public CCTimer(int scriptHandler, float seconds)
        {
            m_nScriptHandler = scriptHandler;
            Elapsed = -1;
            Interval = seconds;
        }
        */

        #region SelectorProtocol Members

        public void Update(float dt)
        {
            if (m_fElapsed == -1)
            {
                m_fElapsed = 0;
                m_uTimesExecuted = 0;
            }
            else
            {
                if (m_bRunForever && !m_bUseDelay)
                {
                    //standard timer usage
                    m_fElapsed += dt;
                    if (m_fElapsed >= Interval)
                    {
                        if (Selector != null)
                        {
                            Selector(m_fElapsed);
                        }

                        /*
                        if (m_nScriptHandler != 0)
                        {
                            CCScriptEngineManager::sharedManager()->getScriptEngine()->executeSchedule(this, m_fElapsed);
                        }
                        */
                        Interval = OriginalInterval - (m_fElapsed - Interval);
                    }
                }
                else
                {
                    //advanced usage
                    m_fElapsed += dt;

                    if (m_bUseDelay)
                    {
                        if (m_fElapsed >= m_fDelay)
                        {
                            if (Selector != null)
                            {
                                Selector(m_fElapsed);
                            }

                            /*
                            if (m_nScriptHandler != 0)
                            {
                                CCScriptEngineManager::sharedManager()->getScriptEngine()->executeSchedule(this, m_fElapsed);
                            }
                            */

                            m_fElapsed = m_fElapsed - m_fDelay;
                            m_uTimesExecuted += 1;
                            m_bUseDelay = false;
                        }
                    }
                    else
                    {
                        if (m_fElapsed >= Interval)
                        {
                            if (Selector != null)
                            {
                                Selector(m_fElapsed);
                            }

                            /*
                            if (m_nScriptHandler)
                            {
                                CCScriptEngineManager::sharedManager()->getScriptEngine()->executeSchedule(m_nScriptHandler, m_fElapsed);
                            }
                            */

                            Interval = OriginalInterval - (m_fElapsed - Interval);
                            m_fElapsed = 0;
                            m_uTimesExecuted += 1;
                        }
                    }

                    if (!m_bRunForever && m_uTimesExecuted > m_uRepeat)
                    {
                        //unschedule timer
                        _scheduler.UnscheduleSelector(Selector, m_pTarget);
                    }
                }
            }
        }

        #endregion
    }
}

/** @brief Scheduler is responsible for triggering the scheduled callbacks.
    You should not use NSTimer. Instead use this class.

    There are 2 different types of callbacks (selectors):

    - update selector: the 'update' selector will be called every frame. You can customize the priority.
    - custom selector: A custom selector will be called every frame, or with a custom interval of time

    The 'custom selectors' should be avoided when possible. It is faster, and consumes less memory to use the 'update selector'.
    */

namespace Cocos2D
{
    public class CCScheduler
    {
        public const uint kCCRepeatForever = uint.MaxValue - 1;
        public const int kCCPrioritySystem = int.MinValue;
        public const int kCCPriorityNonSystemMin = kCCPrioritySystem + 1;

        private readonly Dictionary<ICCSelectorProtocol, HashTimeEntry> m_pHashForTimers =
            new Dictionary<ICCSelectorProtocol, HashTimeEntry>();

        private readonly Dictionary<ICCSelectorProtocol, HashUpdateEntry> m_pHashForUpdates =
            new Dictionary<ICCSelectorProtocol, HashUpdateEntry>();

        // hash used to fetch quickly the list entries for pause,delete,etc
        private readonly LinkedList<ListEntry> m_pUpdates0List = new LinkedList<ListEntry>(); // list priority == 0
        private readonly LinkedList<ListEntry> m_pUpdatesNegList = new LinkedList<ListEntry>(); // list of priority < 0
        private readonly LinkedList<ListEntry> m_pUpdatesPosList = new LinkedList<ListEntry>(); // list priority > 0

        private HashTimeEntry m_pCurrentTarget;
        private bool m_bCurrentTargetSalvaged;
        private bool m_bUpdateHashLocked;

        public float TimeScale = 1.0f;

        private static HashTimeEntry[] s_pTmpHashSelectorArray = new HashTimeEntry[128];
        private static ICCSelectorProtocol[] s_pTmpSelectorArray = new ICCSelectorProtocol[128];

        internal void update(float dt)
        {
            m_bUpdateHashLocked = true;

            try
            {
                if (TimeScale != 1.0f)
                {
                    dt *= TimeScale;
                }

                LinkedListNode<ListEntry> next;

                // updates with priority < 0
                //foreach (ListEntry entry in _updatesNegList)
                for (LinkedListNode<ListEntry> node = m_pUpdatesNegList.First; node != null; node = next)
                {
                    next = node.Next;
                    if (!node.Value.Paused && !node.Value.MarkedForDeletion)
                    {
                        node.Value.Target.Update(dt);
                    }
                }

                // updates with priority == 0
                //foreach (ListEntry entry in _updates0List)
                for (LinkedListNode<ListEntry> node = m_pUpdates0List.First; node != null; node = next)
                {
                    next = node.Next;
                    if (!node.Value.Paused && !node.Value.MarkedForDeletion)
                    {
                        node.Value.Target.Update(dt);
                    }
                }

                // updates with priority > 0
                for (LinkedListNode<ListEntry> node = m_pUpdatesPosList.First; node != null; node = next)
                {
                    next = node.Next;
                    if (!node.Value.Paused && !node.Value.MarkedForDeletion)
                    {
                        node.Value.Target.Update(dt);
                    }
                }

                // Iterate over all the custom selectors
                var count = m_pHashForTimers.Keys.Count;
                if (s_pTmpSelectorArray.Length < count)
                {
                    s_pTmpSelectorArray = new ICCSelectorProtocol[s_pTmpSelectorArray.Length * 2];
                }
                m_pHashForTimers.Keys.CopyTo(s_pTmpSelectorArray, 0);

                for (int i = 0; i < count; i++)
                {
                    ICCSelectorProtocol key = s_pTmpSelectorArray[i];
                    if (!m_pHashForTimers.ContainsKey(key))
                    {
                        continue;
                    }
                    HashTimeEntry elt = m_pHashForTimers[key];

                    m_pCurrentTarget = elt;
                    m_bCurrentTargetSalvaged = false;

                    if (!m_pCurrentTarget.Paused)
                    {
                        // The 'timers' array may change while inside this loop
                        for (elt.TimerIndex = 0; elt.TimerIndex < elt.Timers.Count; ++elt.TimerIndex)
                        {
                            elt.CurrentTimer = elt.Timers[elt.TimerIndex];
                            elt.CurrentTimerSalvaged = false;

                            elt.CurrentTimer.Update(dt);

                            elt.CurrentTimer = null;
                        }
                    }

                    // only delete currentTarget if no actions were scheduled during the cycle (issue #481)
                    if (m_bCurrentTargetSalvaged && m_pCurrentTarget.Timers.Count == 0)
                    {
                        RemoveHashElement(m_pCurrentTarget);
                    }
                }
                /*
                // Iterate over all the script callbacks
                if (m_pScriptHandlerEntries)
                {
                    for (int i = m_pScriptHandlerEntries->count() - 1; i >= 0; i--)
                    {
                        CCSchedulerScriptHandlerEntry* pEntry = static_cast<CCSchedulerScriptHandlerEntry*>(m_pScriptHandlerEntries->objectAtIndex(i));
                        if (pEntry->isMarkedForDeletion())
                        {
                            m_pScriptHandlerEntries->removeObjectAtIndex(i);
                        }
                        else if (!pEntry->isPaused())
                        {
                            pEntry->getTimer()->update(dt);
                        }
                    }
                }
                */

                // delete all updates that are marked for deletion
                // updates with priority < 0
                for (LinkedListNode<ListEntry> node = m_pUpdatesNegList.First; node != null; node = next)
                {
                    next = node.Next;
                    if (node.Value.MarkedForDeletion)
                    {
                        m_pUpdatesNegList.Remove(node);
                        RemoveUpdateFromHash(node.Value);
                    }
                }

                // updates with priority == 0
                for (LinkedListNode<ListEntry> node = m_pUpdates0List.First; node != null; node = next)
                {
                    next = node.Next;
                    if (node.Value.MarkedForDeletion)
                    {
                        m_pUpdates0List.Remove(node);
                        RemoveUpdateFromHash(node.Value);
                    }
                }

                // updates with priority > 0
                for (LinkedListNode<ListEntry> node = m_pUpdatesPosList.First; node != null; node = next)
                {
                    next = node.Next;
                    if (node.Value.MarkedForDeletion)
                    {
                        m_pUpdatesPosList.Remove(node);
                        RemoveUpdateFromHash(node.Value);
                    }
                }
            }
            finally
            {
                // Always do this just in case there is a problem

                m_bUpdateHashLocked = false;
                m_pCurrentTarget = null;
            }
        }

        /** The scheduled method will be called every 'interval' seconds.
         If paused is YES, then it won't be called until it is resumed.
         If 'interval' is 0, it will be called every frame, but if so, it's recommended to use 'scheduleUpdateForTarget:' instead.
         If the selector is already scheduled, then only the interval parameter will be updated without re-scheduling it again.
         repeat let the action be repeated repeat + 1 times, use kCCRepeatForever to let the action run continuously
         delay is the amount of time the action will wait before it'll start

         @since v0.99.3, repeat and delay added in v1.1
         */

        public void ScheduleSelector(Action<float> selector, ICCSelectorProtocol target, float interval, uint repeat,
                                     float delay, bool paused)
        {
            Debug.Assert(selector != null);
            Debug.Assert(target != null);

            HashTimeEntry element;

            lock (m_pHashForTimers)
            {
                if (!m_pHashForTimers.TryGetValue(target, out element))
                {
                    element = new HashTimeEntry { Target = target };
                    m_pHashForTimers[target] = element;

                    // Is this the 1st element ? Then set the pause level to all the selectors of this target
                    element.Paused = paused;
                }
                else
                {
                    Debug.Assert(element.Paused == paused);
                }

                if (element.Timers == null)
                {
                    element.Timers = new List<CCTimer>();
                }
                else
                {
                    CCTimer[] timers = element.Timers.ToArray();
                    foreach (var timer in timers)
                    {
                        if (timer == null)
                        {
                            continue;
                        }
                        if (selector == timer.Selector)
                        {
                            CCLog.Log(
                                "CCSheduler#scheduleSelector. Selector already scheduled. Updating interval from: {0} to {1}",
                                timer.Interval, interval);
                            timer.Interval = interval;
                            return;
                        }
                    }
                }

                element.Timers.Add(new CCTimer(this, target, selector, interval, repeat, delay));
            }
        }

        /** Schedules the 'update' selector for a given target with a given priority.
    	     The 'update' selector will be called every frame.
    	     The lower the priority, the earlier it is called.
    	     @since v0.99.3
    	     */

        public void ScheduleUpdateForTarget(ICCSelectorProtocol targt, int priority, bool paused)
        {
            HashUpdateEntry element;

            if (m_pHashForUpdates.TryGetValue(targt, out element))
            {
                Debug.Assert(element.Entry.MarkedForDeletion);

                // TODO: check if priority has changed!
                element.Entry.MarkedForDeletion = false;

                return;
            }

            // most of the updates are going to be 0, that's way there
            // is an special list for updates with priority 0
            if (priority == 0)
            {
                AppendIn(m_pUpdates0List, targt, paused);
            }
            else if (priority < 0)
            {
                PriorityIn(m_pUpdatesNegList, targt, priority, paused);
            }
            else
            {
                PriorityIn(m_pUpdatesPosList, targt, priority, paused);
            }
        }

        /** Unschedule a selector for a given target.
    	     If you want to unschedule the "update", use unscheudleUpdateForTarget.
    	     @since v0.99.3
    	     */

        public void UnscheduleSelector(Action<float> selector, ICCSelectorProtocol target)
        {
            // explicity handle nil arguments when removing an object
            if (selector == null || target == null)
            {
                return;
            }

            HashTimeEntry element;
            if (m_pHashForTimers.TryGetValue(target, out element))
            {
                for (int i = 0; i < element.Timers.Count; i++)
                {
                    var timer = element.Timers[i];

                    if (selector == timer.Selector)
                    {
                        if (timer == element.CurrentTimer && (!element.CurrentTimerSalvaged))
                        {
                            element.CurrentTimerSalvaged = true;
                        }

                        element.Timers.RemoveAt(i);

                        // update timerIndex in case we are in tick:, looping over the actions
                        if (element.TimerIndex >= i)
                        {
                            element.TimerIndex--;
                        }

                        if (element.Timers.Count == 0)
                        {
                            if (m_pCurrentTarget == element)
                            {
                                m_bCurrentTargetSalvaged = true;
                            }
                            else
                            {
                                RemoveHashElement(element);
                            }
                        }

                        return;
                    }
                }
            }
        }

        /** Unschedules all selectors for a given target.
    	     This also includes the "update" selector.
    	     @since v0.99.3
    	     */

        public void UnscheduleAllForTarget(ICCSelectorProtocol target)
        {
            // explicit NULL handling
            if (target == null)
            {
                return;
            }

            // custom selectors
            HashTimeEntry element;

            if (m_pHashForTimers.TryGetValue(target, out element))
            {
                if (element.Timers.Contains(element.CurrentTimer))
                {
                    element.CurrentTimerSalvaged = true;
                }
                element.Timers.Clear();

                if (m_pCurrentTarget == element)
                {
                    m_bCurrentTargetSalvaged = true;
                }
                else
                {
                    RemoveHashElement(element);
                }
            }

            // update selector
            UnscheduleUpdateForTarget(target);
        }

        /*
        unsigned int CCScheduler::scheduleScriptFunc(unsigned int nHandler, float fInterval, bool bPaused)
        {
            CCSchedulerScriptHandlerEntry* pEntry = CCSchedulerScriptHandlerEntry::create(nHandler, fInterval, bPaused);
            if (!m_pScriptHandlerEntries)
            {
                m_pScriptHandlerEntries = CCArray::create(20);
                m_pScriptHandlerEntries->retain();
            }
            m_pScriptHandlerEntries->addObject(pEntry);
            return pEntry->getEntryId();
        }

        void CCScheduler::unscheduleScriptEntry(unsigned int uScheduleScriptEntryID)
        {
            for (int i = m_pScriptHandlerEntries->count() - 1; i >= 0; i--)
            {
                CCSchedulerScriptHandlerEntry* pEntry = static_cast<CCSchedulerScriptHandlerEntry*>(m_pScriptHandlerEntries->objectAtIndex(i));
                if (pEntry->getEntryId() == uScheduleScriptEntryID)
                {
                    pEntry->markedForDeletion();
                    break;
                }
            }
        }
        */

        public void UnscheduleUpdateForTarget(ICCSelectorProtocol target)
        {
            if (target == null)
            {
                return;
            }

            HashUpdateEntry element;
            if (m_pHashForUpdates.TryGetValue(target, out element))
            {
                if (m_bUpdateHashLocked)
                {
                    element.Entry.MarkedForDeletion = true;
                }
                else
                {
                    RemoveUpdateFromHash(element.Entry);
                }
            }
        }

        public void UnscheduleAll()
        {
            UnscheduleAllWithMinPriority(int.MinValue);
        }

        public void UnscheduleAllWithMinPriority(int minPriority)
        {
            var count = m_pHashForTimers.Values.Count;
            if (s_pTmpHashSelectorArray.Length < count)
            {
                s_pTmpHashSelectorArray = new HashTimeEntry[s_pTmpHashSelectorArray.Length * 2];
            }

            m_pHashForTimers.Values.CopyTo(s_pTmpHashSelectorArray, 0);

            for (int i = 0; i < count; i++)
            {
                // Element may be removed in unscheduleAllSelectorsForTarget
                UnscheduleAllForTarget(s_pTmpHashSelectorArray[i].Target);
            }

            // Updates selectors
            if (minPriority < 0 && m_pUpdatesNegList.Count > 0)
            {
                LinkedList<ListEntry> copy = new LinkedList<ListEntry>(m_pUpdatesNegList);
                foreach (ListEntry entry in copy)
                {
                    if (entry.Priority >= minPriority)
                    {
                        UnscheduleAllForTarget(entry.Target);
                    }
                }
            }

            if (minPriority <= 0 && m_pUpdates0List.Count > 0)
            {
                LinkedList<ListEntry> copy = new LinkedList<ListEntry>(m_pUpdates0List);
                foreach (ListEntry entry in copy)
                {
                    UnscheduleAllForTarget(entry.Target);
                }
            }

            if (m_pUpdatesPosList.Count > 0)
            {
                LinkedList<ListEntry> copy = new LinkedList<ListEntry>(m_pUpdatesPosList);
                foreach (ListEntry entry in copy)
                {
                    if (entry.Priority >= minPriority)
                    {
                        UnscheduleAllForTarget(entry.Target);
                    }
                }
            }
        }

        public List<ICCSelectorProtocol> PauseAllTargets()
        {
            return PauseAllTargetsWithMinPriority(int.MinValue);
        }

        public List<ICCSelectorProtocol> PauseAllTargetsWithMinPriority(int minPriority)
        {
            var idsWithSelectors = new List<ICCSelectorProtocol>();

            // Custom Selectors
            foreach (HashTimeEntry element in m_pHashForTimers.Values)
            {
                element.Paused = true;
                idsWithSelectors.Add(element.Target);
            }

            // Updates selectors
            if (minPriority < 0)
            {
                foreach (ListEntry element in m_pUpdatesNegList)
                {
                    if (element.Priority >= minPriority)
                    {
                        element.Paused = true;
                        idsWithSelectors.Add(element.Target);
                    }
                }
            }

            if (minPriority <= 0)
            {
                foreach (ListEntry element in m_pUpdates0List)
                {
                    element.Paused = true;
                    idsWithSelectors.Add(element.Target);
                }
            }

            if (minPriority < 0)
            {
                foreach (ListEntry element in m_pUpdatesPosList)
                {
                    if (element.Priority >= minPriority)
                    {
                        element.Paused = true;
                        idsWithSelectors.Add(element.Target);
                    }
                }
            }

            return idsWithSelectors;
        }

        public void ResumeTargets(List<ICCSelectorProtocol> targetsToResume)
        {
            foreach (ICCSelectorProtocol target in targetsToResume)
            {
                ResumeTarget(target);
            }
        }

        public void PauseTarget(ICCSelectorProtocol target)
        {
            Debug.Assert(target != null);

            // custom selectors
            HashTimeEntry entry;
            if (m_pHashForTimers.TryGetValue(target, out entry))
            {
                entry.Paused = true;
            }

            // Update selector
            HashUpdateEntry updateEntry;
            if (m_pHashForUpdates.TryGetValue(target, out updateEntry))
            {
                updateEntry.Entry.Paused = true;
            }
        }

        public void ResumeTarget(ICCSelectorProtocol target)
        {
            Debug.Assert(target != null);

            // custom selectors
            HashTimeEntry element;
            if (m_pHashForTimers.TryGetValue(target, out element))
            {
                element.Paused = false;
            }

            // Update selector
            HashUpdateEntry elementUpdate;
            if (m_pHashForUpdates.TryGetValue(target, out elementUpdate))
            {
                elementUpdate.Entry.Paused = false;
            }
        }

        public bool IsTargetPaused(ICCSelectorProtocol target)
        {
            Debug.Assert(target != null, "target must be non nil");

            // Custom selectors
            HashTimeEntry element;
            if (m_pHashForTimers.TryGetValue(target, out element))
            {
                return element.Paused;
            }

            // We should check update selectors if target does not have custom selectors
            HashUpdateEntry elementUpdate;
            if (m_pHashForUpdates.TryGetValue(target, out elementUpdate))
            {
                return elementUpdate.Entry.Paused;
            }

            return false; // should never get here
        }

        private void RemoveHashElement(HashTimeEntry element)
        {
            m_pHashForTimers.Remove(element.Target);

            element.Timers.Clear();
            element.Target = null;
        }

        private void RemoveUpdateFromHash(ListEntry entry)
        {
            HashUpdateEntry element;
            if (m_pHashForUpdates.TryGetValue(entry.Target, out element))
            {
                // list entry
                element.List.Remove(entry);
                element.Entry = null;

                // hash entry
                m_pHashForUpdates.Remove(entry.Target);

                element.Target = null;
            }
        }

        private void PriorityIn(LinkedList<ListEntry> list, ICCSelectorProtocol target, int priority, bool paused)
        {
            var listElement = new ListEntry
                {
                    Target = target,
                    Priority = priority,
                    Paused = paused,
                    MarkedForDeletion = false
                };

            if (list.First == null)
            {
                list.AddFirst(listElement);
            }
            else
            {
                bool added = false;
                for (LinkedListNode<ListEntry> node = list.First; node != null; node = node.Next)
                {
                    if (priority < node.Value.Priority)
                    {
                        list.AddBefore(node, listElement);
                        added = true;
                        break;
                    }
                }

                if (!added)
                {
                    list.AddLast(listElement);
                }
            }

            // update hash entry for quick access
            var hashElement = new HashUpdateEntry
                {
                    Target = target,
                    List = list,
                    Entry = listElement
                };

            m_pHashForUpdates.Add(target, hashElement);
        }

        private void AppendIn(LinkedList<ListEntry> list, ICCSelectorProtocol target, bool paused)
        {
            var listElement = new ListEntry
                {
                    Target = target,
                    Paused = paused,
                    MarkedForDeletion = false
                };

            list.AddLast(listElement);

            // update hash entry for quicker access
            var hashElement = new HashUpdateEntry
                {
                    Target = target,
                    List = list,
                    Entry = listElement
                };

            m_pHashForUpdates.Add(target, hashElement);
        }

        #region Nested type: HashSelectorEntry

        private class HashTimeEntry
        {
            public CCTimer CurrentTimer;
            public bool CurrentTimerSalvaged;
            public bool Paused;
            public ICCSelectorProtocol Target;
            public int TimerIndex;
            public List<CCTimer> Timers;
        }

        #endregion

        #region Nested type: HashUpdateEntry

        private class HashUpdateEntry
        {
            public ListEntry Entry; // entry in the list
            public LinkedList<ListEntry> List; // Which list does it belong to ?
            public ICCSelectorProtocol Target; // hash key
        }

        #endregion

        #region Nested type: ListEntry

        private class ListEntry
        {
            public bool MarkedForDeletion;
            public bool Paused;
            public int Priority;
            public ICCSelectorProtocol Target;
        }

        #endregion
    }
}


text:
import { inspect } from '../jsutils/inspect.js';
import { instanceOf } from '../jsutils/instanceOf.js';
import type { Maybe } from '../jsutils/Maybe.js';
import { toObjMap } from '../jsutils/toObjMap.js';

import type { DirectiveDefinitionNode } from '../language/ast.js';
import { DirectiveLocation } from '../language/directiveLocation.js';

import { assertName } from './assertName.js';
import type {
  GraphQLArgument,
  GraphQLFieldConfigArgumentMap,
} from './definition.js';
import {
  argsToArgsConfig,
  defineArguments,
  GraphQLNonNull,
} from './definition.js';
import { GraphQLBoolean, GraphQLInt, GraphQLString } from './scalars.js';

/**
 * Test if the given value is a GraphQL directive.
 */
export function isDirective(directive: unknown): directive is GraphQLDirective {
  return instanceOf(directive, GraphQLDirective);
}

export function assertDirective(directive: unknown): GraphQLDirective {
  if (!isDirective(directive)) {
    throw new Error(
      `Expected ${inspect(directive)} to be a GraphQL directive.`,
    );
  }
  return directive;
}

/**
 * Custom extensions
 *
 * @remarks
 * Use a unique identifier name for your extension, for example the name of
 * your library or project. Do not use a shortened identifier as this increases
 * the risk of conflicts. We recommend you add at most one extension field,
 * an object which can contain all the values you need.
 */
export interface GraphQLDirectiveExtensions {
  [attributeName: string]: unknown;
}

/**
 * Directives are used by the GraphQL runtime as a way of modifying execution
 * behavior. Type system creators will usually not create these directly.
 */
export class GraphQLDirective {
  name: string;
  description: Maybe<string>;
  locations: ReadonlyArray<DirectiveLocation>;
  args: ReadonlyArray<GraphQLArgument>;
  isRepeatable: boolean;
  extensions: Readonly<GraphQLDirectiveExtensions>;
  astNode: Maybe<DirectiveDefinitionNode>;

  constructor(config: Readonly<GraphQLDirectiveConfig>) {
    this.name = assertName(config.name);
    this.description = config.description;
    this.locations = config.locations;
    this.isRepeatable = config.isRepeatable ?? false;
    this.extensions = toObjMap(config.extensions);
    this.astNode = config.astNode;

    const args = config.args ?? {};
    this.args = defineArguments(args);
  }

  get [Symbol.toStringTag]() {
    return 'GraphQLDirective';
  }

  toConfig(): GraphQLDirectiveNormalizedConfig {
    return {
      name: this.name,
      description: this.description,
      locations: this.locations,
      args: argsToArgsConfig(this.args),
      isRepeatable: this.isRepeatable,
      extensions: this.extensions,
      astNode: this.astNode,
    };
  }

  toString(): string {
    return '@' + this.name;
  }

  toJSON(): string {
    return this.toString();
  }
}

export interface GraphQLDirectiveConfig {
  name: string;
  description?: Maybe<string>;
  locations: ReadonlyArray<DirectiveLocation>;
  args?: Maybe<GraphQLFieldConfigArgumentMap>;
  isRepeatable?: Maybe<boolean>;
  extensions?: Maybe<Readonly<GraphQLDirectiveExtensions>>;
  astNode?: Maybe<DirectiveDefinitionNode>;
}

interface GraphQLDirectiveNormalizedConfig extends GraphQLDirectiveConfig {
  args: GraphQLFieldConfigArgumentMap;
  isRepeatable: boolean;
  extensions: Readonly<GraphQLDirectiveExtensions>;
}

/**
 * Used to conditionally include fields or fragments.
 */
export const GraphQLIncludeDirective: GraphQLDirective = new GraphQLDirective({
  name: 'include',
  description:
    'Directs the executor to include this field or fragment only when the `if` argument is true.',
  locations: [
    DirectiveLocation.FIELD,
    DirectiveLocation.FRAGMENT_SPREAD,
    DirectiveLocation.INLINE_FRAGMENT,
  ],
  args: {
    if: {
      type: new GraphQLNonNull(GraphQLBoolean),
      description: 'Included when true.',
    },
  },
});

/**
 * Used to conditionally skip (exclude) fields or fragments.
 */
export const GraphQLSkipDirective: GraphQLDirective = new GraphQLDirective({
  name: 'skip',
  description:
    'Directs the executor to skip this field or fragment when the `if` argument is true.',
  locations: [
    DirectiveLocation.FIELD,
    DirectiveLocation.FRAGMENT_SPREAD,
    DirectiveLocation.INLINE_FRAGMENT,
  ],
  args: {
    if: {
      type: new GraphQLNonNull(GraphQLBoolean),
      description: 'Skipped when true.',
    },
  },
});

/**
 * Used to conditionally defer fragments.
 */
export const GraphQLDeferDirective = new GraphQLDirective({
  name: 'defer',
  description:
    'Directs the executor to defer this fragment when the `if` argument is true or undefined.',
  locations: [
    DirectiveLocation.FRAGMENT_SPREAD,
    DirectiveLocation.INLINE_FRAGMENT,
  ],
  args: {
    if: {
      type: new GraphQLNonNull(GraphQLBoolean),
      description: 'Deferred when true or undefined.',
      defaultValue: true,
    },
    label: {
      type: GraphQLString,
      description: 'Unique name',
    },
  },
});

/**
 * Used to conditionally stream list fields.
 */
export const GraphQLStreamDirective = new GraphQLDirective({
  name: 'stream',
  description:
    'Directs the executor to stream plural fields when the `if` argument is true or undefined.',
  locations: [DirectiveLocation.FIELD],
  args: {
    if: {
      type: new GraphQLNonNull(GraphQLBoolean),
      description: 'Stream when true or undefined.',
      defaultValue: true,
    },
    label: {
      type: GraphQLString,
      description: 'Unique name',
    },
    initialCount: {
      defaultValue: 0,
      type: GraphQLInt,
      description: 'Number of items to return immediately',
    },
  },
});

/**
 * Constant string used for default reason for a deprecation.
 */
export const DEFAULT_DEPRECATION_REASON = 'No longer supported';

/**
 * Used to declare element of a GraphQL schema as deprecated.
 */
export const GraphQLDeprecatedDirective: GraphQLDirective =
  new GraphQLDirective({
    name: 'deprecated',
    description: 'Marks an element of a GraphQL schema as no longer supported.',
    locations: [
      DirectiveLocation.FIELD_DEFINITION,
      DirectiveLocation.ARGUMENT_DEFINITION,
      DirectiveLocation.INPUT_FIELD_DEFINITION,
      DirectiveLocation.ENUM_VALUE,
    ],
    args: {
      reason: {
        type: GraphQLString,
        description:
          'Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).',
        defaultValue: DEFAULT_DEPRECATION_REASON,
      },
    },
  });

/**
 * Used to provide a URL for specifying the behavior of custom scalar definitions.
 */
export const GraphQLSpecifiedByDirective: GraphQLDirective =
  new GraphQLDirective({
    name: 'specifiedBy',
    description: 'Exposes a URL that specifies the behavior of this scalar.',
    locations: [DirectiveLocation.SCALAR],
    args: {
      url: {
        type: new GraphQLNonNull(GraphQLString),
        description: 'The URL that specifies the behavior of this scalar.',
      },
    },
  });

/**
 * The full list of specified directives.
 */
export const specifiedDirectives: ReadonlyArray<GraphQLDirective> =
  Object.freeze([
    GraphQLIncludeDirective,
    GraphQLSkipDirective,
    GraphQLDeprecatedDirective,
    GraphQLSpecifiedByDirective,
  ]);

export function isSpecifiedDirective(directive: GraphQLDirective): boolean {
  return specifiedDirectives.some(({ name }) => name === directive.name);
}


text:
#include "StdAfx.h"

namespace Alphaleonis { namespace Win32 { namespace Vss
{

   void ThrowException(HRESULT errorCode)
   {
      throw GetExceptionForHr(errorCode);
   }

   Exception ^ GetExceptionForHr(HRESULT errorCode)
   {
      switch (errorCode)
      {
      case E_ACCESSDENIED:
         return gcnew UnauthorizedAccessException();
      case E_INVALIDARG:
         return gcnew ArgumentException();
      case E_OUTOFMEMORY:
         return gcnew OutOfMemoryException();
      case E_NOTIMPL:
         return gcnew NotImplementedException(L"The requested operation is not supported on the current operating system or by the current provider.");
      case E_UNEXPECTED:
#if ALPHAVSS_TARGET >= ALPHAVSS_TARGET_WINVISTAORLATER
      case VSS_E_UNEXPECTED:
#endif
         return gcnew VssUnexpectedErrorException();
      case VSS_E_INVALID_XML_DOCUMENT:
         return gcnew VssInvalidXmlDocumentException();
      case VSS_E_BAD_STATE:
         return gcnew VssBadStateException();
      case VSS_E_OBJECT_NOT_FOUND:
         return gcnew VssObjectNotFoundException();
      case VSS_E_PROVIDER_VETO:
         return gcnew VssProviderVetoException();
      case VSS_E_UNEXPECTED_PROVIDER_ERROR:
         return gcnew VssUnexpectedProviderErrorException();
      case VSS_E_MAXIMUM_NUMBER_OF_VOLUMES_REACHED:
         return gcnew VssMaximumNumberOfVolumesReachedException();
      case VSS_E_MAXIMUM_NUMBER_OF_SNAPSHOTS_REACHED:
         return gcnew VssMaximumNumberOfSnapshotsReachedException();
      case VSS_E_MAXIMUM_DIFFAREA_ASSOCIATIONS_REACHED:
         return gcnew VssMaximumDiffAreaAssociationsReachedException();
      case VSS_E_PROVIDER_NOT_REGISTERED:
         return gcnew VssProviderNotRegisteredException();
      case VSS_E_VOLUME_NOT_SUPPORTED:
         return gcnew VssVolumeNotSupportedException();
      case VSS_E_VOLUME_NOT_SUPPORTED_BY_PROVIDER:
         return gcnew VssVolumeNotSupportedByProviderException();
      case VSS_E_UNEXPECTED_WRITER_ERROR:
         return gcnew VssUnexpectedWriterErrorException();
      case VSS_E_INSUFFICIENT_STORAGE:
         return gcnew VssInsufficientStorageException();
      case VSS_E_FLUSH_WRITES_TIMEOUT:
         return gcnew VssFlushWritesTimeoutException();
      case VSS_E_HOLD_WRITES_TIMEOUT:
         return gcnew VssHoldWritesTimeoutException();
      case VSS_E_OBJECT_ALREADY_EXISTS:
         return gcnew VssObjectAlreadyExistsException();
#if ALPHAVSS_TARGET >= ALPHAVSS_TARGET_WIN2003
         // Skip these if not supported
      case VSS_E_REBOOT_REQUIRED:
         return gcnew VssRebootRequiredException();
      case VSS_E_REVERT_IN_PROGRESS:
         return gcnew VssRevertInProgressException();
#if ALPHAVSS_TARGET >= ALPHAVSS_TARGET_WINVISTAORLATER
      case VSS_E_TRANSACTION_FREEZE_TIMEOUT:
         return gcnew VssTransactionFreezeTimeoutException();
      case VSS_E_TRANSACTION_THAW_TIMEOUT:
         return gcnew VssTransactionThawTimeoutException();
      case VSS_E_RESYNC_IN_PROGRESS:
         return gcnew VssResyncInProgressException();
      case VSS_E_SNAPSHOT_NOT_IN_SET:
         return gcnew VssSnapshotNotInSetException();
      case VSS_E_LEGACY_PROVIDER:
         return gcnew VssLegacyProviderException();
      case VSS_E_UNSELECTED_VOLUME:
         return gcnew VssUnselectedVolumeException();
      case VSS_E_CANNOT_REVERT_DISKID:
         return gcnew VssCannotRevertDiskIdException();
      case VSS_E_WRITERERROR_INCONSISTENTSNAPSHOT:
         return gcnew VssInconsistentSnapshotWriterException();
      case VSS_E_WRITERERROR_OUTOFRESOURCES:
         return gcnew VssOutOfResourcesWriterException();
      case VSS_E_WRITERERROR_TIMEOUT:
         return gcnew VssTimeoutWriterException();
      case VSS_E_WRITERERROR_RETRYABLE:
         return gcnew VssRetryableWriterException();
      case VSS_E_WRITERERROR_NONRETRYABLE:
         return gcnew VssNonRetryableWriterException();
      case VSS_E_WRITER_NOT_RESPONDING:
         return gcnew VssWriterNotRespondingException();
      case VSS_E_WRITER_STATUS_NOT_AVAILABLE:
         return gcnew VssWriterStatusNotAvailableException();
      case VSS_E_WRITERERROR_PARTIAL_FAILURE:
         return gcnew VssPartialFailureWriterException();
#endif
#endif
      case VSS_E_UNSUPPORTED_CONTEXT:
         return gcnew VssUnsupportedContextException();
      case VSS_E_VOLUME_IN_USE:
         return gcnew VssVolumeInUseException();
      case VSS_E_SNAPSHOT_SET_IN_PROGRESS:
         return gcnew VssSnapshotSetInProgressException();
      default:
         return System::Runtime::InteropServices::Marshal::GetExceptionForHR(errorCode);
      }
   }

   void WaitCheckAndReleaseVssAsyncOperation(::IVssAsync *pAsync)
   {
      CComPtr<::IVssAsync> spAsync;
      spAsync.Attach(pAsync);
      CheckCom(spAsync->Wait());
      HRESULT hr;
      CheckCom(spAsync->QueryStatus(&hr, NULL));
      CheckCom(hr);
      if (hr == VSS_S_ASYNC_CANCELLED)
         throw gcnew OperationCanceledException();
   }
}
} }


text:
//
//  UIView+DXBExtension.h
//  BSBDJ
//
//  Created by andyshow on 16/11/20.
//  Copyright © 2016年 andyshow. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UIView (DXBExtension)
@property(nonatomic ,assign)CGSize size;
@property(nonatomic, assign)CGFloat width;
@property(nonatomic, assign)CGFloat height;
@property(nonatomic, assign)CGFloat x;
@property(nonatomic, assign)CGFloat y;
@property(nonatomic, assign)CGFloat centerX;
@property(nonatomic, assign)CGFloat centerY;
/**
 *在分类中声明@property,只会生成方法的声明,不会生成方法的实现和带有_下划线的成员变量
 */
@end


text:
<Type Name="SourceModel+EntryType" FullName="Banshee.Sources.Gui.SourceModel+EntryType">
  <TypeSignature Language="C#" Value="public enum SourceModel.EntryType" />
  <TypeSignature Language="ILAsm" Value=".class nested public auto ansi sealed SourceModel/EntryType extends System.Enum" />
  <AssemblyInfo>
    <AssemblyName>Banshee.ThickClient</AssemblyName>
    <AssemblyVersion>2.4.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>System.Enum</BaseTypeName>
  </Base>
  <Docs>
    To be added.
    <remarks>To be added.</remarks>
  </Docs>
  <Members>
    <Member MemberName="Group">
      <MemberSignature Language="C#" Value="Group" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype Banshee.Sources.Gui.SourceModel/EntryType Group = int32(1)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Banshee.Sources.Gui.SourceModel+EntryType</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
    <Member MemberName="Source">
      <MemberSignature Language="C#" Value="Source" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype Banshee.Sources.Gui.SourceModel/EntryType Source = int32(0)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Banshee.Sources.Gui.SourceModel+EntryType</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
  </Members>
</Type>


text:
import { Injectable } from '@angular/core';
import { Headers, RequestOptions, Http, Response } from '@angular/http';

import { Workbasket } from '../model/workbasket';
import { Task } from '../model/task';
import { environment } from '../../environments/environment';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class RestConnectorService {

  constructor(private http: Http) { }

  getAllWorkBaskets(): Observable<Workbasket[]> {
    return this.http.get(environment.taskanaRestUrl + "/v1/workbaskets?requiredPermission=OPEN", this.createAuthorizationHeader())
      .map(res => res.json());
  }

  findTaskWithWorkbaskets(basketName: string): Observable<Task[]> {
    return this.http.get(environment.taskanaRestUrl + "/v1/tasks?workbasketid=" + basketName + "&state=READY&state=CLAIMED", this.createAuthorizationHeader())
      .map(res => res.json());
  }

  getTask(id: string): Observable<Task> {
    return this.http.get(environment.taskanaRestUrl + "/v1/tasks/" + id, this.createAuthorizationHeader())
      .map(res => res.json());
  }

  completeTask(id: string): Observable<Task> {
    return this.http.post(environment.taskanaRestUrl + "/v1/tasks/" + id + "/complete", "", this.createAuthorizationHeader())
      .map(res => res.json());
  }

  claimTask(id: string): Observable<Task> {
    return this.http.post(environment.taskanaRestUrl + "/v1/tasks/" + id + "/claim", "test", this.createAuthorizationHeader())
      .map(res => res.json());
  }

  transferTask(taskId: string, workbasketId: string) {
    return this.http.post(environment.taskanaRestUrl + "/v1/tasks/" + taskId + "/transfer/" + workbasketId, "", this.createAuthorizationHeader())
      .map(res => res.json());
  }

  private createAuthorizationHeader() {
    let headers: Headers = new Headers();
    headers.append("Authorization", "Basic TWF4OnRlc3Q=");

    return new RequestOptions({ headers: headers });
  }
}


text:
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/gfp.h>
#include <linux/mm.h>
#include <linux/swap.h>
#include <linux/smp.h>
#include <linux/highmem.h>
#include <linux/pagemap.h>
#include <linux/spinlock.h>
#include <linux/module.h>
#include <linux/quicklist.h>
#include <linux/rcupdate.h>
#include <linux/slab.h>

#include <asm/system.h>
#include <asm/pgtable.h>
#include <asm/pgalloc.h>
#include <asm/tlb.h>
#include <asm/tlbflush.h>
#include <asm/mmu_context.h>

#ifndef CONFIG_64BIT
#define ALLOC_ORDER	1
#define FRAG_MASK	0x0f
#else
#define ALLOC_ORDER	2
#define FRAG_MASK	0x03
#endif

unsigned long VMALLOC_START = VMALLOC_END - VMALLOC_SIZE;
EXPORT_SYMBOL(VMALLOC_START);

static int __init parse_vmalloc(char *arg)
{
	if (!arg)
		return -EINVAL;
	VMALLOC_START = (VMALLOC_END - memparse(arg, &arg)) & PAGE_MASK;
	return 0;
}
early_param("vmalloc", parse_vmalloc);

unsigned long *crst_table_alloc(struct mm_struct *mm)
{
	struct page *page = alloc_pages(GFP_KERNEL, ALLOC_ORDER);

	if (!page)
		return NULL;
	return (unsigned long *) page_to_phys(page);
}

void crst_table_free(struct mm_struct *mm, unsigned long *table)
{
	free_pages((unsigned long) table, ALLOC_ORDER);
}

#ifdef CONFIG_64BIT
int crst_table_upgrade(struct mm_struct *mm, unsigned long limit)
{
	unsigned long *table, *pgd;
	unsigned long entry;

	BUG_ON(limit > (1UL << 53));
repeat:
	table = crst_table_alloc(mm);
	if (!table)
		return -ENOMEM;
	spin_lock_bh(&mm->page_table_lock);
	if (mm->context.asce_limit < limit) {
		pgd = (unsigned long *) mm->pgd;
		if (mm->context.asce_limit <= (1UL << 31)) {
			entry = _REGION3_ENTRY_EMPTY;
			mm->context.asce_limit = 1UL << 42;
			mm->context.asce_bits = _ASCE_TABLE_LENGTH |
						_ASCE_USER_BITS |
						_ASCE_TYPE_REGION3;
		} else {
			entry = _REGION2_ENTRY_EMPTY;
			mm->context.asce_limit = 1UL << 53;
			mm->context.asce_bits = _ASCE_TABLE_LENGTH |
						_ASCE_USER_BITS |
						_ASCE_TYPE_REGION2;
		}
		crst_table_init(table, entry);
		pgd_populate(mm, (pgd_t *) table, (pud_t *) pgd);
		mm->pgd = (pgd_t *) table;
		mm->task_size = mm->context.asce_limit;
		table = NULL;
	}
	spin_unlock_bh(&mm->page_table_lock);
	if (table)
		crst_table_free(mm, table);
	if (mm->context.asce_limit < limit)
		goto repeat;
	return 0;
}

void crst_table_downgrade(struct mm_struct *mm, unsigned long limit)
{
	pgd_t *pgd;

	while (mm->context.asce_limit > limit) {
		pgd = mm->pgd;
		switch (pgd_val(*pgd) & _REGION_ENTRY_TYPE_MASK) {
		case _REGION_ENTRY_TYPE_R2:
			mm->context.asce_limit = 1UL << 42;
			mm->context.asce_bits = _ASCE_TABLE_LENGTH |
						_ASCE_USER_BITS |
						_ASCE_TYPE_REGION3;
			break;
		case _REGION_ENTRY_TYPE_R3:
			mm->context.asce_limit = 1UL << 31;
			mm->context.asce_bits = _ASCE_TABLE_LENGTH |
						_ASCE_USER_BITS |
						_ASCE_TYPE_SEGMENT;
			break;
		default:
			BUG();
		}
		mm->pgd = (pgd_t *) (pgd_val(*pgd) & _REGION_ENTRY_ORIGIN);
		mm->task_size = mm->context.asce_limit;
		crst_table_free(mm, (unsigned long *) pgd);
	}
}
#endif

#ifdef CONFIG_PGSTE

/**
 * gmap_alloc - allocate a guest address space
 * @mm: pointer to the parent mm_struct
 *
 * Returns a guest address space structure.
 */
struct gmap *gmap_alloc(struct mm_struct *mm)
{
	struct gmap *gmap;
	struct page *page;
	unsigned long *table;

	gmap = kzalloc(sizeof(struct gmap), GFP_KERNEL);
	if (!gmap)
		goto out;
	INIT_LIST_HEAD(&gmap->crst_list);
	gmap->mm = mm;
	page = alloc_pages(GFP_KERNEL, ALLOC_ORDER);
	if (!page)
		goto out_free;
	list_add(&page->lru, &gmap->crst_list);
	table = (unsigned long *) page_to_phys(page);
	crst_table_init(table, _REGION1_ENTRY_EMPTY);
	gmap->table = table;
	gmap->asce = _ASCE_TYPE_REGION1 | _ASCE_TABLE_LENGTH |
		     _ASCE_USER_BITS | __pa(table);
	list_add(&gmap->list, &mm->context.gmap_list);
	return gmap;

out_free:
	kfree(gmap);
out:
	return NULL;
}
EXPORT_SYMBOL_GPL(gmap_alloc);

static int gmap_unlink_segment(struct gmap *gmap, unsigned long *table)
{
	struct gmap_pgtable *mp;
	struct gmap_rmap *rmap;
	struct page *page;

	if (*table & _SEGMENT_ENTRY_INV)
		return 0;
	page = pfn_to_page(*table >> PAGE_SHIFT);
	mp = (struct gmap_pgtable *) page->index;
	list_for_each_entry(rmap, &mp->mapper, list) {
		if (rmap->entry != table)
			continue;
		list_del(&rmap->list);
		kfree(rmap);
		break;
	}
	*table = _SEGMENT_ENTRY_INV | _SEGMENT_ENTRY_RO | mp->vmaddr;
	return 1;
}

static void gmap_flush_tlb(struct gmap *gmap)
{
	if (MACHINE_HAS_IDTE)
		__tlb_flush_idte((unsigned long) gmap->table |
				 _ASCE_TYPE_REGION1);
	else
		__tlb_flush_global();
}

/**
 * gmap_free - free a guest address space
 * @gmap: pointer to the guest address space structure
 */
void gmap_free(struct gmap *gmap)
{
	struct page *page, *next;
	unsigned long *table;
	int i;

	/* Flush tlb. */
	if (MACHINE_HAS_IDTE)
		__tlb_flush_idte((unsigned long) gmap->table |
				 _ASCE_TYPE_REGION1);
	else
		__tlb_flush_global();

	/* Free all segment & region tables. */
	down_read(&gmap->mm->mmap_sem);
	spin_lock(&gmap->mm->page_table_lock);
	list_for_each_entry_safe(page, next, &gmap->crst_list, lru) {
		table = (unsigned long *) page_to_phys(page);
		if ((*table & _REGION_ENTRY_TYPE_MASK) == 0)
			/* Remove gmap rmap structures for segment table. */
			for (i = 0; i < PTRS_PER_PMD; i++, table++)
				gmap_unlink_segment(gmap, table);
		__free_pages(page, ALLOC_ORDER);
	}
	spin_unlock(&gmap->mm->page_table_lock);
	up_read(&gmap->mm->mmap_sem);
	list_del(&gmap->list);
	kfree(gmap);
}
EXPORT_SYMBOL_GPL(gmap_free);

/**
 * gmap_enable - switch primary space to the guest address space
 * @gmap: pointer to the guest address space structure
 */
void gmap_enable(struct gmap *gmap)
{
	S390_lowcore.gmap = (unsigned long) gmap;
}
EXPORT_SYMBOL_GPL(gmap_enable);

/**
 * gmap_disable - switch back to the standard primary address space
 * @gmap: pointer to the guest address space structure
 */
void gmap_disable(struct gmap *gmap)
{
	S390_lowcore.gmap = 0UL;
}
EXPORT_SYMBOL_GPL(gmap_disable);

/*
 * gmap_alloc_table is assumed to be called with mmap_sem held
 */
static int gmap_alloc_table(struct gmap *gmap,
			       unsigned long *table, unsigned long init)
{
	struct page *page;
	unsigned long *new;

	page = alloc_pages(GFP_KERNEL, ALLOC_ORDER);
	if (!page)
		return -ENOMEM;
	new = (unsigned long *) page_to_phys(page);
	crst_table_init(new, init);
	if (*table & _REGION_ENTRY_INV) {
		list_add(&page->lru, &gmap->crst_list);
		*table = (unsigned long) new | _REGION_ENTRY_LENGTH |
			(*table & _REGION_ENTRY_TYPE_MASK);
	} else
		__free_pages(page, ALLOC_ORDER);
	return 0;
}

/**
 * gmap_unmap_segment - unmap segment from the guest address space
 * @gmap: pointer to the guest address space structure
 * @addr: address in the guest address space
 * @len: length of the memory area to unmap
 *
 * Returns 0 if the unmap succeded, -EINVAL if not.
 */
int gmap_unmap_segment(struct gmap *gmap, unsigned long to, unsigned long len)
{
	unsigned long *table;
	unsigned long off;
	int flush;

	if ((to | len) & (PMD_SIZE - 1))
		return -EINVAL;
	if (len == 0 || to + len < to)
		return -EINVAL;

	flush = 0;
	down_read(&gmap->mm->mmap_sem);
	spin_lock(&gmap->mm->page_table_lock);
	for (off = 0; off < len; off += PMD_SIZE) {
		/* Walk the guest addr space page table */
		table = gmap->table + (((to + off) >> 53) & 0x7ff);
		if (*table & _REGION_ENTRY_INV)
			goto out;
		table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
		table = table + (((to + off) >> 42) & 0x7ff);
		if (*table & _REGION_ENTRY_INV)
			goto out;
		table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
		table = table + (((to + off) >> 31) & 0x7ff);
		if (*table & _REGION_ENTRY_INV)
			goto out;
		table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
		table = table + (((to + off) >> 20) & 0x7ff);

		/* Clear segment table entry in guest address space. */
		flush |= gmap_unlink_segment(gmap, table);
		*table = _SEGMENT_ENTRY_INV;
	}
out:
	spin_unlock(&gmap->mm->page_table_lock);
	up_read(&gmap->mm->mmap_sem);
	if (flush)
		gmap_flush_tlb(gmap);
	return 0;
}
EXPORT_SYMBOL_GPL(gmap_unmap_segment);

/**
 * gmap_mmap_segment - map a segment to the guest address space
 * @gmap: pointer to the guest address space structure
 * @from: source address in the parent address space
 * @to: target address in the guest address space
 *
 * Returns 0 if the mmap succeded, -EINVAL or -ENOMEM if not.
 */
int gmap_map_segment(struct gmap *gmap, unsigned long from,
		     unsigned long to, unsigned long len)
{
	unsigned long *table;
	unsigned long off;
	int flush;

	if ((from | to | len) & (PMD_SIZE - 1))
		return -EINVAL;
	if (len == 0 || from + len > PGDIR_SIZE ||
	    from + len < from || to + len < to)
		return -EINVAL;

	flush = 0;
	down_read(&gmap->mm->mmap_sem);
	spin_lock(&gmap->mm->page_table_lock);
	for (off = 0; off < len; off += PMD_SIZE) {
		/* Walk the gmap address space page table */
		table = gmap->table + (((to + off) >> 53) & 0x7ff);
		if ((*table & _REGION_ENTRY_INV) &&
		    gmap_alloc_table(gmap, table, _REGION2_ENTRY_EMPTY))
			goto out_unmap;
		table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
		table = table + (((to + off) >> 42) & 0x7ff);
		if ((*table & _REGION_ENTRY_INV) &&
		    gmap_alloc_table(gmap, table, _REGION3_ENTRY_EMPTY))
			goto out_unmap;
		table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
		table = table + (((to + off) >> 31) & 0x7ff);
		if ((*table & _REGION_ENTRY_INV) &&
		    gmap_alloc_table(gmap, table, _SEGMENT_ENTRY_EMPTY))
			goto out_unmap;
		table = (unsigned long *) (*table & _REGION_ENTRY_ORIGIN);
		table = table + (((to + off) >> 20) & 0x7ff);

		/* Store 'from' address in an invalid segment table entry. */
		flush |= gmap_unlink_segment(gmap, table);
		*table = _SEGMENT_ENTRY_INV | _SEGMENT_ENTRY_RO | (from + off);
	}
	spin_unlock(&gmap->mm->page_table_lock);
	up_read(&gmap->mm->mmap_sem);
	if (flush)
		gmap_flush_tlb(gmap);
	return 0;

out_unmap:
	spin_unlock(&gmap->mm->page_table_lock);
	up_read(&gmap->mm->mmap_sem);
	gmap_unmap_segment(gmap, to, len);
	return -ENOMEM;
}
EXPORT_SYMBOL_GPL(gmap_map_segment);

/*
 * this function is assumed to be called with mmap_sem held
 */
unsigned long __gmap_fault(unsigned long address, struct gmap *gmap)
{
	unsigned long *table, vmaddr, segment;
	struct mm_struct *mm;
	struct gmap_pgtable *mp;
	struct gmap_rmap *rmap;
	struct vm_area_struct *vma;
	struct page *page;
	pgd_t *pgd;
	pud_t *pud;
	pmd_t *pmd;

	current->thread.gmap_addr = address;
	mm = gmap->mm;
	/* Walk the gmap address space page table */
	table = gmap->table + ((address >> 53) & 0x7ff);
	if (unlikely(*table & _REGION_ENTRY_INV))
		return -EFAULT;
	table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
	table = table + ((address >> 42) & 0x7ff);
	if (unlikely(*table & _REGION_ENTRY_INV))
		return -EFAULT;
	table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
	table = table + ((address >> 31) & 0x7ff);
	if (unlikely(*table & _REGION_ENTRY_INV))
		return -EFAULT;
	table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
	table = table + ((address >> 20) & 0x7ff);

	/* Convert the gmap address to an mm address. */
	segment = *table;
	if (likely(!(segment & _SEGMENT_ENTRY_INV))) {
		page = pfn_to_page(segment >> PAGE_SHIFT);
		mp = (struct gmap_pgtable *) page->index;
		return mp->vmaddr | (address & ~PMD_MASK);
	} else if (segment & _SEGMENT_ENTRY_RO) {
		vmaddr = segment & _SEGMENT_ENTRY_ORIGIN;
		vma = find_vma(mm, vmaddr);
		if (!vma || vma->vm_start > vmaddr)
			return -EFAULT;

		/* Walk the parent mm page table */
		pgd = pgd_offset(mm, vmaddr);
		pud = pud_alloc(mm, pgd, vmaddr);
		if (!pud)
			return -ENOMEM;
		pmd = pmd_alloc(mm, pud, vmaddr);
		if (!pmd)
			return -ENOMEM;
		if (!pmd_present(*pmd) &&
		    __pte_alloc(mm, vma, pmd, vmaddr))
			return -ENOMEM;
		/* pmd now points to a valid segment table entry. */
		rmap = kmalloc(sizeof(*rmap), GFP_KERNEL|__GFP_REPEAT);
		if (!rmap)
			return -ENOMEM;
		/* Link gmap segment table entry location to page table. */
		page = pmd_page(*pmd);
		mp = (struct gmap_pgtable *) page->index;
		rmap->entry = table;
		spin_lock(&mm->page_table_lock);
		list_add(&rmap->list, &mp->mapper);
		spin_unlock(&mm->page_table_lock);
		/* Set gmap segment table entry to page table. */
		*table = pmd_val(*pmd) & PAGE_MASK;
		return vmaddr | (address & ~PMD_MASK);
	}
	return -EFAULT;
}

unsigned long gmap_fault(unsigned long address, struct gmap *gmap)
{
	unsigned long rc;

	down_read(&gmap->mm->mmap_sem);
	rc = __gmap_fault(address, gmap);
	up_read(&gmap->mm->mmap_sem);

	return rc;
}
EXPORT_SYMBOL_GPL(gmap_fault);

void gmap_discard(unsigned long from, unsigned long to, struct gmap *gmap)
{

	unsigned long *table, address, size;
	struct vm_area_struct *vma;
	struct gmap_pgtable *mp;
	struct page *page;

	down_read(&gmap->mm->mmap_sem);
	address = from;
	while (address < to) {
		/* Walk the gmap address space page table */
		table = gmap->table + ((address >> 53) & 0x7ff);
		if (unlikely(*table & _REGION_ENTRY_INV)) {
			address = (address + PMD_SIZE) & PMD_MASK;
			continue;
		}
		table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
		table = table + ((address >> 42) & 0x7ff);
		if (unlikely(*table & _REGION_ENTRY_INV)) {
			address = (address + PMD_SIZE) & PMD_MASK;
			continue;
		}
		table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
		table = table + ((address >> 31) & 0x7ff);
		if (unlikely(*table & _REGION_ENTRY_INV)) {
			address = (address + PMD_SIZE) & PMD_MASK;
			continue;
		}
		table = (unsigned long *)(*table & _REGION_ENTRY_ORIGIN);
		table = table + ((address >> 20) & 0x7ff);
		if (unlikely(*table & _SEGMENT_ENTRY_INV)) {
			address = (address + PMD_SIZE) & PMD_MASK;
			continue;
		}
		page = pfn_to_page(*table >> PAGE_SHIFT);
		mp = (struct gmap_pgtable *) page->index;
		vma = find_vma(gmap->mm, mp->vmaddr);
		size = min(to - address, PMD_SIZE - (address & ~PMD_MASK));
		zap_page_range(vma, mp->vmaddr | (address & ~PMD_MASK),
			       size, NULL);
		address = (address + PMD_SIZE) & PMD_MASK;
	}
	up_read(&gmap->mm->mmap_sem);
}
EXPORT_SYMBOL_GPL(gmap_discard);

void gmap_unmap_notifier(struct mm_struct *mm, unsigned long *table)
{
	struct gmap_rmap *rmap, *next;
	struct gmap_pgtable *mp;
	struct page *page;
	int flush;

	flush = 0;
	spin_lock(&mm->page_table_lock);
	page = pfn_to_page(__pa(table) >> PAGE_SHIFT);
	mp = (struct gmap_pgtable *) page->index;
	list_for_each_entry_safe(rmap, next, &mp->mapper, list) {
		*rmap->entry =
			_SEGMENT_ENTRY_INV | _SEGMENT_ENTRY_RO | mp->vmaddr;
		list_del(&rmap->list);
		kfree(rmap);
		flush = 1;
	}
	spin_unlock(&mm->page_table_lock);
	if (flush)
		__tlb_flush_global();
}

static inline unsigned long *page_table_alloc_pgste(struct mm_struct *mm,
						    unsigned long vmaddr)
{
	struct page *page;
	unsigned long *table;
	struct gmap_pgtable *mp;

	page = alloc_page(GFP_KERNEL|__GFP_REPEAT);
	if (!page)
		return NULL;
	mp = kmalloc(sizeof(*mp), GFP_KERNEL|__GFP_REPEAT);
	if (!mp) {
		__free_page(page);
		return NULL;
	}
	pgtable_page_ctor(page);
	mp->vmaddr = vmaddr & PMD_MASK;
	INIT_LIST_HEAD(&mp->mapper);
	page->index = (unsigned long) mp;
	atomic_set(&page->_mapcount, 3);
	table = (unsigned long *) page_to_phys(page);
	clear_table(table, _PAGE_TYPE_EMPTY, PAGE_SIZE/2);
	clear_table(table + PTRS_PER_PTE, 0, PAGE_SIZE/2);
	return table;
}

static inline void page_table_free_pgste(unsigned long *table)
{
	struct page *page;
	struct gmap_pgtable *mp;

	page = pfn_to_page(__pa(table) >> PAGE_SHIFT);
	mp = (struct gmap_pgtable *) page->index;
	BUG_ON(!list_empty(&mp->mapper));
	pgtable_page_ctor(page);
	atomic_set(&page->_mapcount, -1);
	kfree(mp);
	__free_page(page);
}

#else /* CONFIG_PGSTE */

static inline unsigned long *page_table_alloc_pgste(struct mm_struct *mm,
						    unsigned long vmaddr)
{
	return NULL;
}

static inline void page_table_free_pgste(unsigned long *table)
{
}

static inline void gmap_unmap_notifier(struct mm_struct *mm,
					  unsigned long *table)
{
}

#endif /* CONFIG_PGSTE */

static inline unsigned int atomic_xor_bits(atomic_t *v, unsigned int bits)
{
	unsigned int old, new;

	do {
		old = atomic_read(v);
		new = old ^ bits;
	} while (atomic_cmpxchg(v, old, new) != old);
	return new;
}

/*
 * page table entry allocation/free routines.
 */
unsigned long *page_table_alloc(struct mm_struct *mm, unsigned long vmaddr)
{
	struct page *page;
	unsigned long *table;
	unsigned int mask, bit;

	if (mm_has_pgste(mm))
		return page_table_alloc_pgste(mm, vmaddr);
	/* Allocate fragments of a 4K page as 1K/2K page table */
	spin_lock_bh(&mm->context.list_lock);
	mask = FRAG_MASK;
	if (!list_empty(&mm->context.pgtable_list)) {
		page = list_first_entry(&mm->context.pgtable_list,
					struct page, lru);
		table = (unsigned long *) page_to_phys(page);
		mask = atomic_read(&page->_mapcount);
		mask = mask | (mask >> 4);
	}
	if ((mask & FRAG_MASK) == FRAG_MASK) {
		spin_unlock_bh(&mm->context.list_lock);
		page = alloc_page(GFP_KERNEL|__GFP_REPEAT);
		if (!page)
			return NULL;
		pgtable_page_ctor(page);
		atomic_set(&page->_mapcount, 1);
		table = (unsigned long *) page_to_phys(page);
		clear_table(table, _PAGE_TYPE_EMPTY, PAGE_SIZE);
		spin_lock_bh(&mm->context.list_lock);
		list_add(&page->lru, &mm->context.pgtable_list);
	} else {
		for (bit = 1; mask & bit; bit <<= 1)
			table += PTRS_PER_PTE;
		mask = atomic_xor_bits(&page->_mapcount, bit);
		if ((mask & FRAG_MASK) == FRAG_MASK)
			list_del(&page->lru);
	}
	spin_unlock_bh(&mm->context.list_lock);
	return table;
}

void page_table_free(struct mm_struct *mm, unsigned long *table)
{
	struct page *page;
	unsigned int bit, mask;

	if (mm_has_pgste(mm)) {
		gmap_unmap_notifier(mm, table);
		return page_table_free_pgste(table);
	}
	/* Free 1K/2K page table fragment of a 4K page */
	page = pfn_to_page(__pa(table) >> PAGE_SHIFT);
	bit = 1 << ((__pa(table) & ~PAGE_MASK)/(PTRS_PER_PTE*sizeof(pte_t)));
	spin_lock_bh(&mm->context.list_lock);
	if ((atomic_read(&page->_mapcount) & FRAG_MASK) != FRAG_MASK)
		list_del(&page->lru);
	mask = atomic_xor_bits(&page->_mapcount, bit);
	if (mask & FRAG_MASK)
		list_add(&page->lru, &mm->context.pgtable_list);
	spin_unlock_bh(&mm->context.list_lock);
	if (mask == 0) {
		pgtable_page_dtor(page);
		atomic_set(&page->_mapcount, -1);
		__free_page(page);
	}
}

static void __page_table_free_rcu(void *table, unsigned bit)
{
	struct page *page;

	if (bit == FRAG_MASK)
		return page_table_free_pgste(table);
	/* Free 1K/2K page table fragment of a 4K page */
	page = pfn_to_page(__pa(table) >> PAGE_SHIFT);
	if (atomic_xor_bits(&page->_mapcount, bit) == 0) {
		pgtable_page_dtor(page);
		atomic_set(&page->_mapcount, -1);
		__free_page(page);
	}
}

void page_table_free_rcu(struct mmu_gather *tlb, unsigned long *table)
{
	struct mm_struct *mm;
	struct page *page;
	unsigned int bit, mask;

	mm = tlb->mm;
	if (mm_has_pgste(mm)) {
		gmap_unmap_notifier(mm, table);
		table = (unsigned long *) (__pa(table) | FRAG_MASK);
		tlb_remove_table(tlb, table);
		return;
	}
	bit = 1 << ((__pa(table) & ~PAGE_MASK) / (PTRS_PER_PTE*sizeof(pte_t)));
	page = pfn_to_page(__pa(table) >> PAGE_SHIFT);
	spin_lock_bh(&mm->context.list_lock);
	if ((atomic_read(&page->_mapcount) & FRAG_MASK) != FRAG_MASK)
		list_del(&page->lru);
	mask = atomic_xor_bits(&page->_mapcount, bit | (bit << 4));
	if (mask & FRAG_MASK)
		list_add_tail(&page->lru, &mm->context.pgtable_list);
	spin_unlock_bh(&mm->context.list_lock);
	table = (unsigned long *) (__pa(table) | (bit << 4));
	tlb_remove_table(tlb, table);
}

void __tlb_remove_table(void *_table)
{
	const unsigned long mask = (FRAG_MASK << 4) | FRAG_MASK;
	void *table = (void *)((unsigned long) _table & ~mask);
	unsigned type = (unsigned long) _table & mask;

	if (type)
		__page_table_free_rcu(table, type);
	else
		free_pages((unsigned long) table, ALLOC_ORDER);
}

static void tlb_remove_table_smp_sync(void *arg)
{
	/* Simply deliver the interrupt */
}

static void tlb_remove_table_one(void *table)
{
	/*
	 * This isn't an RCU grace period and hence the page-tables cannot be
	 * assumed to be actually RCU-freed.
	 *
	 * It is however sufficient for software page-table walkers that rely
	 * on IRQ disabling. See the comment near struct mmu_table_batch.
	 */
	smp_call_function(tlb_remove_table_smp_sync, NULL, 1);
	__tlb_remove_table(table);
}

static void tlb_remove_table_rcu(struct rcu_head *head)
{
	struct mmu_table_batch *batch;
	int i;

	batch = container_of(head, struct mmu_table_batch, rcu);

	for (i = 0; i < batch->nr; i++)
		__tlb_remove_table(batch->tables[i]);

	free_page((unsigned long)batch);
}

void tlb_table_flush(struct mmu_gather *tlb)
{
	struct mmu_table_batch **batch = &tlb->batch;

	if (*batch) {
		__tlb_flush_mm(tlb->mm);
		call_rcu_sched(&(*batch)->rcu, tlb_remove_table_rcu);
		*batch = NULL;
	}
}

void tlb_remove_table(struct mmu_gather *tlb, void *table)
{
	struct mmu_table_batch **batch = &tlb->batch;

	if (*batch == NULL) {
		*batch = (struct mmu_table_batch *)
			__get_free_page(GFP_NOWAIT | __GFP_NOWARN);
		if (*batch == NULL) {
			__tlb_flush_mm(tlb->mm);
			tlb_remove_table_one(table);
			return;
		}
		(*batch)->nr = 0;
	}
	(*batch)->tables[(*batch)->nr++] = table;
	if ((*batch)->nr == MAX_TABLE_BATCH)
		tlb_table_flush(tlb);
}

/*
 * switch on pgstes for its userspace process (for kvm)
 */
int s390_enable_sie(void)
{
	struct task_struct *tsk = current;
	struct mm_struct *mm, *old_mm;

	/* Do we have switched amode? If no, we cannot do sie */
	if (user_mode == HOME_SPACE_MODE)
		return -EINVAL;

	/* Do we have pgstes? if yes, we are done */
	if (mm_has_pgste(tsk->mm))
		return 0;

	/* lets check if we are allowed to replace the mm */
	task_lock(tsk);
	if (!tsk->mm || atomic_read(&tsk->mm->mm_users) > 1 ||
#ifdef CONFIG_AIO
	    !hlist_empty(&tsk->mm->ioctx_list) ||
#endif
	    tsk->mm != tsk->active_mm) {
		task_unlock(tsk);
		return -EINVAL;
	}
	task_unlock(tsk);

	/* we copy the mm and let dup_mm create the page tables with_pgstes */
	tsk->mm->context.alloc_pgste = 1;
	mm = dup_mm(tsk);
	tsk->mm->context.alloc_pgste = 0;
	if (!mm)
		return -ENOMEM;

	/* Now lets check again if something happened */
	task_lock(tsk);
	if (!tsk->mm || atomic_read(&tsk->mm->mm_users) > 1 ||
#ifdef CONFIG_AIO
	    !hlist_empty(&tsk->mm->ioctx_list) ||
#endif
	    tsk->mm != tsk->active_mm) {
		mmput(mm);
		task_unlock(tsk);
		return -EINVAL;
	}

	/* ok, we are alone. No ptrace, no threads, etc. */
	old_mm = tsk->mm;
	tsk->mm = tsk->active_mm = mm;
	preempt_disable();
	update_mm(mm, tsk);
	atomic_inc(&mm->context.attach_count);
	atomic_dec(&old_mm->context.attach_count);
	cpumask_set_cpu(smp_processor_id(), mm_cpumask(mm));
	preempt_enable();
	task_unlock(tsk);
	mmput(old_mm);
	return 0;
}
EXPORT_SYMBOL_GPL(s390_enable_sie);

#if defined(CONFIG_DEBUG_PAGEALLOC) && defined(CONFIG_HIBERNATION)
bool kernel_page_present(struct page *page)
{
	unsigned long addr;
	int cc;

	addr = page_to_phys(page);
	asm volatile(
		"	lra	%1,0(%1)\n"
		"	ipm	%0\n"
		"	srl	%0,28"
		: "=d" (cc), "+a" (addr) : : "cc");
	return cc == 0;
}
#endif /* CONFIG_HIBERNATION && CONFIG_DEBUG_PAGEALLOC */


text:
package lombok.javac.handlers;

import java.util.ArrayList;
import java.util.Collections;

import org.mangosdk.spi.ProviderFor;

import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.tree.JCTree.JCModifiers;
import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCTypeApply;
import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Name;

import lombok.AccessLevel;
import lombok.ConfigurationKeys;
import lombok.core.AST.Kind;
import lombok.core.AnnotationValues;
import lombok.core.HandlerPriority;
import lombok.experimental.Builder;
import lombok.experimental.NonFinal;
import lombok.javac.JavacAnnotationHandler;
import lombok.javac.JavacNode;
import lombok.javac.JavacTreeMaker;
import lombok.javac.handlers.HandleConstructor.SkipIfConstructorExists;
import static lombok.core.handlers.HandlerUtil.*;
import static lombok.javac.handlers.JavacHandlerUtil.*;
import static lombok.javac.Javac.*;
import static lombok.javac.JavacTreeMaker.TypeTag.*;

@ProviderFor(JavacAnnotationHandler.class)
@HandlerPriority(-1024) //-2^10; to ensure we've picked up @FieldDefault's changes (-2048) but @Value hasn't removed itself yet (-512), so that we can error on presence of it on the builder classes.
public class HandleBuilder extends JavacAnnotationHandler<Builder> {
	@Override public void handle(AnnotationValues<Builder> annotation, JCAnnotation ast, JavacNode annotationNode) {
		handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.BUILDER_FLAG_USAGE, "@Builder");

		Builder builderInstance = annotation.getInstance();
		String builderMethodName = builderInstance.builderMethodName();
		String buildMethodName = builderInstance.buildMethodName();
		String builderClassName = builderInstance.builderClassName();

		if (builderMethodName == null) builderMethodName = "builder";
		if (buildMethodName == null) buildMethodName = "build";
		if (builderClassName == null) builderClassName = "";

		if (!checkName("builderMethodName", builderMethodName, annotationNode)) return;
		if (!checkName("buildMethodName", buildMethodName, annotationNode)) return;
		if (!builderClassName.isEmpty()) {
			if (!checkName("builderClassName", builderClassName, annotationNode)) return;
		}

		deleteAnnotationIfNeccessary(annotationNode, Builder.class);
		deleteImportFromCompilationUnit(annotationNode, "lombok.experimental.Builder");

		JavacNode parent = annotationNode.up();

		java.util.List<JCExpression> typesOfParameters = new ArrayList<JCExpression>();
		java.util.List<Name> namesOfParameters = new ArrayList<Name>();
		JCExpression returnType;
		List<JCTypeParameter> typeParams = List.nil();
		List<JCExpression> thrownExceptions = List.nil();
		Name nameOfStaticBuilderMethod;
		JavacNode tdParent;

		JCMethodDecl fillParametersFrom = parent.get() instanceof JCMethodDecl ? ((JCMethodDecl) parent.get()) : null;

		if (parent.get() instanceof JCClassDecl) {
			tdParent = parent;
			JCClassDecl td = (JCClassDecl) tdParent.get();
			ListBuffer<JavacNode> allFields = new ListBuffer<JavacNode>();
			@SuppressWarnings("deprecation")
			boolean valuePresent = (hasAnnotation(lombok.Value.class, parent) || hasAnnotation(lombok.experimental.Value.class, parent));
			for (JavacNode fieldNode : HandleConstructor.findAllFields(tdParent)) {
				JCVariableDecl fd = (JCVariableDecl) fieldNode.get();
				// final fields with an initializer cannot be written to, so they can't be 'builderized'. Unfortunately presence of @Value makes
				// non-final fields final, but @Value's handler hasn't done this yet, so we have to do this math ourselves.
				// Value will only skip making a field final if it has an explicit @NonFinal annotation, so we check for that.
				if (fd.init != null && valuePresent && !hasAnnotation(NonFinal.class, fieldNode)) continue;
				namesOfParameters.add(removePrefixFromField(fieldNode));
				typesOfParameters.add(fd.vartype);
				allFields.append(fieldNode);
			}

			new HandleConstructor().generateConstructor(tdParent, AccessLevel.PACKAGE, List.<JCAnnotation>nil(), allFields.toList(), null, SkipIfConstructorExists.I_AM_BUILDER, null, annotationNode);

			returnType = namePlusTypeParamsToTypeReference(tdParent.getTreeMaker(), td.name, td.typarams);
			typeParams = td.typarams;
			thrownExceptions = List.nil();
			nameOfStaticBuilderMethod = null;
			if (builderClassName.isEmpty()) builderClassName = td.name.toString() + "Builder";
		} else if (fillParametersFrom != null && fillParametersFrom.getName().toString().equals("<init>")) {
			if (!fillParametersFrom.typarams.isEmpty()) {
				annotationNode.addError("@Builder is not supported on constructors with constructor type parameters.");
				return;
			}
			tdParent = parent.up();
			JCClassDecl td = (JCClassDecl) tdParent.get();
			returnType = namePlusTypeParamsToTypeReference(tdParent.getTreeMaker(), td.name, td.typarams);
			typeParams = td.typarams;
			thrownExceptions = fillParametersFrom.thrown;
			nameOfStaticBuilderMethod = null;
			if (builderClassName.isEmpty()) builderClassName = td.name.toString() + "Builder";
		} else if (fillParametersFrom != null) {
			tdParent = parent.up();
			JCClassDecl td = (JCClassDecl) tdParent.get();
			if ((fillParametersFrom.mods.flags & Flags.STATIC) == 0) {
				annotationNode.addError("@Builder is only supported on types, constructors, and static methods.");
				return;
			}
			returnType = fillParametersFrom.restype;
			typeParams = fillParametersFrom.typarams;
			thrownExceptions = fillParametersFrom.thrown;
			nameOfStaticBuilderMethod = fillParametersFrom.name;
			if (builderClassName.isEmpty()) {
				if (returnType instanceof JCTypeApply) {
					returnType = ((JCTypeApply) returnType).clazz;
				}
				if (returnType instanceof JCFieldAccess) {
					builderClassName = ((JCFieldAccess) returnType).name.toString() + "Builder";
				} else if (returnType instanceof JCIdent) {
					Name n = ((JCIdent) returnType).name;

					for (JCTypeParameter tp : typeParams) {
						if (tp.name.equals(n)) {
							annotationNode.addError("@Builder requires specifying 'builderClassName' if used on methods with a type parameter as return type.");
							return;
						}
					}
					builderClassName = n.toString() + "Builder";
				} else if (returnType instanceof JCPrimitiveTypeTree) {
					builderClassName = returnType.toString() + "Builder";
					if (Character.isLowerCase(builderClassName.charAt(0))) {
						builderClassName = Character.toTitleCase(builderClassName.charAt(0)) + builderClassName.substring(1);
					}

				} else {
					// This shouldn't happen.
					System.err.println("Lombok bug ID#20140614-1651: javac HandleBuilder: return type to name conversion failed: " + returnType.getClass());
					builderClassName = td.name.toString() + "Builder";
				}
			}
		} else {
			annotationNode.addError("@Builder is only supported on types, constructors, and static methods.");
			return;
		}

		if (fillParametersFrom != null) {
			for (JCVariableDecl param : fillParametersFrom.params) {
				namesOfParameters.add(param.name);
				typesOfParameters.add(param.vartype);
			}
		}

		JavacNode builderType = findInnerClass(tdParent, builderClassName);
		if (builderType == null) {
			builderType = makeBuilderClass(tdParent, builderClassName, typeParams, ast);
		} else {
			sanityCheckForMethodGeneratingAnnotationsOnBuilderClass(builderType, annotationNode);
		}
		java.util.List<JavacNode> fieldNodes = addFieldsToBuilder(builderType, namesOfParameters, typesOfParameters, ast);
		java.util.List<JCMethodDecl> newMethods = new ArrayList<JCMethodDecl>();
		for (JavacNode fieldNode : fieldNodes) {
			JCMethodDecl newMethod = makeSetterMethodForBuilder(builderType, fieldNode, annotationNode, builderInstance.fluent(), builderInstance.chain());
			if (newMethod != null) newMethods.add(newMethod);
		}

		if (constructorExists(builderType) == MemberExistsResult.NOT_EXISTS) {
			JCMethodDecl cd = HandleConstructor.createConstructor(AccessLevel.PACKAGE, List.<JCAnnotation>nil(), builderType, List.<JavacNode>nil(), null, annotationNode);
			if (cd != null) injectMethod(builderType, cd);
		}

		for (JCMethodDecl newMethod : newMethods) injectMethod(builderType, newMethod);

		if (methodExists(buildMethodName, builderType, -1) == MemberExistsResult.NOT_EXISTS) {
			JCMethodDecl md = generateBuildMethod(buildMethodName, nameOfStaticBuilderMethod, returnType, namesOfParameters, builderType, thrownExceptions);
			if (md != null) injectMethod(builderType, md);
		}

		if (methodExists("toString", builderType, 0) == MemberExistsResult.NOT_EXISTS) {
			JCMethodDecl md = HandleToString.createToString(builderType, fieldNodes, true, false, FieldAccess.ALWAYS_FIELD, ast);
			if (md != null) injectMethod(builderType, md);
		}

		if (methodExists(builderMethodName, tdParent, -1) == MemberExistsResult.NOT_EXISTS) {
			JCMethodDecl md = generateBuilderMethod(builderMethodName, builderClassName, tdParent, typeParams);
			if (md != null) injectMethod(tdParent, md);
		}
	}

	public JCMethodDecl generateBuildMethod(String name, Name staticName, JCExpression returnType, java.util.List<Name> fieldNames, JavacNode type, List<JCExpression> thrownExceptions) {
		JavacTreeMaker maker = type.getTreeMaker();

		JCExpression call;
		JCStatement statement;

		ListBuffer<JCExpression> args = new ListBuffer<JCExpression>();
		for (Name n : fieldNames) {
			args.append(maker.Ident(n));
		}

		if (staticName == null) {
			call = maker.NewClass(null, List.<JCExpression>nil(), returnType, args.toList(), null);
			statement = maker.Return(call);
		} else {
			ListBuffer<JCExpression> typeParams = new ListBuffer<JCExpression>();
			for (JCTypeParameter tp : ((JCClassDecl) type.get()).typarams) {
				typeParams.append(maker.Ident(tp.name));
			}

			JCExpression fn = maker.Select(maker.Ident(((JCClassDecl) type.up().get()).name), staticName);
			call = maker.Apply(typeParams.toList(), fn, args.toList());
			if (returnType instanceof JCPrimitiveTypeTree && CTC_VOID.equals(typeTag(returnType))) {
				statement = maker.Exec(call);
			} else {
				statement = maker.Return(call);
			}
		}

		JCBlock body = maker.Block(0, List.<JCStatement>of(statement));

		return maker.MethodDef(maker.Modifiers(Flags.PUBLIC), type.toName(name), returnType, List.<JCTypeParameter>nil(), List.<JCVariableDecl>nil(), thrownExceptions, body, null);
	}

	public JCMethodDecl generateBuilderMethod(String builderMethodName, String builderClassName, JavacNode type, List<JCTypeParameter> typeParams) {
		JavacTreeMaker maker = type.getTreeMaker();

		ListBuffer<JCExpression> typeArgs = new ListBuffer<JCExpression>();
		for (JCTypeParameter typeParam : typeParams) {
			typeArgs.append(maker.Ident(typeParam.name));
		}

		JCExpression call = maker.NewClass(null, List.<JCExpression>nil(), namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams), List.<JCExpression>nil(), null);
		JCStatement statement = maker.Return(call);

		JCBlock body = maker.Block(0, List.<JCStatement>of(statement));
		return maker.MethodDef(maker.Modifiers(Flags.STATIC | Flags.PUBLIC), type.toName(builderMethodName), namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams), copyTypeParams(maker, typeParams), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), body, null);
	}

	public java.util.List<JavacNode> addFieldsToBuilder(JavacNode builderType, java.util.List<Name> namesOfParameters, java.util.List<JCExpression> typesOfParameters, JCTree source) {
		int len = namesOfParameters.size();
		java.util.List<JavacNode> existing = new ArrayList<JavacNode>();
		for (JavacNode child : builderType.down()) {
			if (child.getKind() == Kind.FIELD) existing.add(child);
		}

		java.util.List<JavacNode>out = new ArrayList<JavacNode>();

		top:
		for (int i = len - 1; i >= 0; i--) {
			Name name = namesOfParameters.get(i);
			for (JavacNode exists : existing) {
				Name n = ((JCVariableDecl) exists.get()).name;
				if (n.equals(name)) {
					out.add(exists);
					continue top;
				}
			}
			JavacTreeMaker maker = builderType.getTreeMaker();
			JCModifiers mods = maker.Modifiers(Flags.PRIVATE);
			JCVariableDecl newField = maker.VarDef(mods, name, cloneType(maker, typesOfParameters.get(i), source, builderType.getContext()), null);
			out.add(injectField(builderType, newField));
		}

		Collections.reverse(out);
		return out;
	}

	public JCMethodDecl makeSetterMethodForBuilder(JavacNode builderType, JavacNode fieldNode, JavacNode source, boolean fluent, boolean chain) {
		Name fieldName = ((JCVariableDecl) fieldNode.get()).name;

		for (JavacNode child : builderType.down()) {
			if (child.getKind() != Kind.METHOD) continue;
			Name existingName = ((JCMethodDecl) child.get()).name;
			if (existingName.equals(fieldName)) return null;
		}

		boolean isBoolean = isBoolean(fieldNode);
		String setterName = fluent ? fieldNode.getName() : toSetterName(builderType.getAst(), null, fieldNode.getName(), isBoolean);

		JavacTreeMaker maker = builderType.getTreeMaker();
		return HandleSetter.createSetter(Flags.PUBLIC, fieldNode, maker, setterName, chain, source, List.<JCAnnotation>nil(), List.<JCAnnotation>nil());
	}

	public JavacNode findInnerClass(JavacNode parent, String name) {
		for (JavacNode child : parent.down()) {
			if (child.getKind() != Kind.TYPE) continue;
			JCClassDecl td = (JCClassDecl) child.get();
			if (td.name.contentEquals(name)) return child;
		}
		return null;
	}

	public JavacNode makeBuilderClass(JavacNode tdParent, String builderClassName, List<JCTypeParameter> typeParams, JCAnnotation ast) {
		JavacTreeMaker maker = tdParent.getTreeMaker();
		JCModifiers mods = maker.Modifiers(Flags.PUBLIC | Flags.STATIC);
		JCClassDecl builder = maker.ClassDef(mods, tdParent.toName(builderClassName), copyTypeParams(maker, typeParams), null, List.<JCExpression>nil(), List.<JCTree>nil());
		return injectType(tdParent, builder);
	}
}