text:
package net.ripe.db.whois.query.executor;

import net.ripe.db.whois.common.domain.CIString;
import net.ripe.db.whois.common.domain.ResponseObject;
import net.ripe.db.whois.common.rpsl.AttributeType;
import net.ripe.db.whois.common.source.IllegalSourceException;
import net.ripe.db.whois.common.source.Source;
import net.ripe.db.whois.common.source.SourceContext;
import net.ripe.db.whois.query.domain.MessageObject;
import net.ripe.db.whois.query.domain.QueryException;
import net.ripe.db.whois.query.domain.QueryMessages;
import net.ripe.db.whois.query.planner.RpslResponseDecorator;
import net.ripe.db.whois.query.query.Query;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;

import java.util.Collections;

import static net.ripe.db.whois.common.domain.CIString.ciSet;
import static net.ripe.db.whois.common.domain.CIString.ciString;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class SearchQueryExecutorTest {
    @Mock SourceContext sourceContext;
    @Mock RpslObjectSearcher rpslObjectSearcher;
    @Mock RpslResponseDecorator rpslResponseDecorator;
    @InjectMocks SearchQueryExecutor subject;

    @Before
    public void setUp() throws Exception {
        when(rpslObjectSearcher.search(any(Query.class))).thenReturn((Iterable)Collections.emptyList());
        when(rpslResponseDecorator.getResponse(any(Query.class), any(Iterable.class))).thenAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                return invocationOnMock.getArguments()[1];
            }
        });
    }

    @Test
    public void all_attributes_handled() {
        for (final AttributeType attributeType : AttributeType.implementedValues()) {
            assertTrue(subject.supports(Query.parse("-i " + attributeType.getName() + " query")));
        }
    }

    @Test(expected = QueryException.class)
    public void test_supports_no_attributes() {
        assertThat(subject.supports(Query.parse("-i")), is(false));
    }

    @Test
    public void test_supports_inverse_with_filter() {
        assertThat(subject.supports(Query.parse("-T inetnum -i mnt-by aardvark-mnt")), is(true));
    }

    @Test
    public void test_supports_inverse_recursive() {
        assertThat(subject.supports(Query.parse("-i mnt-by aardvark-mnt")), is(true));
    }

    @Test
    public void test_supports_inverse() {
        assertThat(subject.supports(Query.parse("-r -i mnt-by aardvark-mnt")), is(true));
    }

    @Test
    public void test_supports_inverse_multiple() {
        assertThat(subject.supports(Query.parse("-r -i mnt-by,mnt-ref aardvark-mnt")), is(true));
    }

    @Test
    public void test_supports_inverse_multiple_unknown() {
        assertThat(subject.supports(Query.parse("-r -i mnt-by,mnt-ref,mnt-lower aardvark-mnt")), is(true));
    }

    @Test
    public void unknown_source() {
        final Query query = Query.parse("-s UNKNOWN 10.0.0.0");
        doThrow(IllegalSourceException.class).when(sourceContext).setCurrent(Source.slave("UNKNOWN"));

        final CaptureResponseHandler responseHandler = new CaptureResponseHandler();
        subject.execute(query, responseHandler);
        verify(rpslObjectSearcher, never()).search(query);

        assertThat(responseHandler.getResponseObjects(), hasItems((ResponseObject) new MessageObject(QueryMessages.unknownSource("UNKNOWN").toString() + "\n")));
        assertThat(responseHandler.getResponseObjects(), hasSize(1));   // make sure that e.g. 'no results found' is not printed
    }

    @Test
    public void query_all_sources() {
        when(sourceContext.getAllSourceNames()).thenReturn(ciSet("APNIC-GRS", "ARIN-GRS"));

        final Query query = Query.parse("--all-sources 10.0.0.0");
        final CaptureResponseHandler responseHandler = new CaptureResponseHandler();
        subject.execute(query, responseHandler);

        verify(sourceContext).setCurrent(Source.slave("APNIC-GRS"));
        verify(sourceContext).setCurrent(Source.slave("ARIN-GRS"));
        verify(sourceContext, times(2)).removeCurrentSource();
        verify(rpslObjectSearcher, times(2)).search(query);
    }

    @Test
    public void query_sources() {
        final Query query = Query.parse("--sources APNIC-GRS,ARIN-GRS 10.0.0.0");

        final CaptureResponseHandler responseHandler = new CaptureResponseHandler();
        subject.execute(query, responseHandler);

        verify(sourceContext).setCurrent(Source.slave("APNIC-GRS"));
        verify(sourceContext).setCurrent(Source.slave("ARIN-GRS"));
        verify(sourceContext, times(2)).removeCurrentSource();
        verify(rpslObjectSearcher, times(2)).search(query);
    }

    @Test
    public void query_sources_and_additional() {
        when(sourceContext.getAllSourceNames()).thenReturn(ciSet("APNIC-GRS", "ARIN-GRS"));

        final Query query = Query.parse("--all-sources --sources RIPE 10.0.0.0");
        final CaptureResponseHandler responseHandler = new CaptureResponseHandler();
        subject.execute(query, responseHandler);

        verify(sourceContext).setCurrent(Source.slave("APNIC-GRS"));
        verify(sourceContext).setCurrent(Source.slave("ARIN-GRS"));
        verify(sourceContext).setCurrent(Source.slave("RIPE"));
        verify(sourceContext, times(3)).removeCurrentSource();
        verify(rpslObjectSearcher, times(3)).search(query);
    }

    @Test
    public void query_resources() {
        when(sourceContext.getGrsSourceNames()).thenReturn(ciSet("APNIC-GRS", "ARIN-GRS"));

        final Query query = Query.parse("--resource 10.0.0.0");
        final CaptureResponseHandler responseHandler = new CaptureResponseHandler();
        subject.execute(query, responseHandler);

        verify(sourceContext).setCurrent(Source.slave("APNIC-GRS"));
        verify(sourceContext).setCurrent(Source.slave("ARIN-GRS"));
        verify(sourceContext, times(2)).removeCurrentSource();
        verify(rpslObjectSearcher, times(2)).search(query);
    }

    @Test
    public void query_all_sources_filters_virtual_sources() {
        when(sourceContext.getAllSourceNames()).thenReturn(ciSet("RIPE", "RIPE-GRS", "APNIC-GRS", "ARIN-GRS"));
        when(sourceContext.isVirtual(any(CIString.class))).thenAnswer(new Answer<Boolean>() {
            @Override
            public Boolean answer(InvocationOnMock invocation) throws Throwable {
                final Object[] arguments = invocation.getArguments();
                return (ciString("RIPE-GRS").equals(arguments[0]));
            }
        });

        final Query query = Query.parse("--all-sources 10.0.0.0");
        final CaptureResponseHandler responseHandler = new CaptureResponseHandler();
        subject.execute(query, responseHandler);

        verify(sourceContext, never()).setCurrent(Source.slave("RIPE-GRS"));
        verify(sourceContext).setCurrent(Source.slave("APNIC-GRS"));
        verify(sourceContext).setCurrent(Source.slave("ARIN-GRS"));
        verify(sourceContext).setCurrent(Source.slave("RIPE"));
        verify(sourceContext, times(3)).removeCurrentSource();
        verify(rpslObjectSearcher, times(3)).search(query);
    }

    @Test
    public void query_no_source_specified() {
        when(sourceContext.getWhoisSlaveSource()).thenReturn(Source.slave("RIPE"));

        final Query query = Query.parse("10.0.0.0");
        final CaptureResponseHandler responseHandler = new CaptureResponseHandler();
        subject.execute(query, responseHandler);

        verify(sourceContext).setCurrent(Source.slave("RIPE"));
        verify(sourceContext).removeCurrentSource();
        verify(rpslObjectSearcher).search(query);
    }

    @Test
    public void no_results_found_gives_message() {
        final Query query = Query.parse("-s RIPE 10.0.0.0");

        final CaptureResponseHandler responseHandler = new CaptureResponseHandler();
        subject.execute(query, responseHandler);
        verify(rpslObjectSearcher).search(query);
        verify(rpslResponseDecorator).getResponse(eq(query), any(Iterable.class));

        assertThat(responseHandler.getResponseObjects(), contains((ResponseObject) new MessageObject(QueryMessages.noResults("RIPE").toString())));
    }

    @Test
    public void query_additional_sources() {
        when(sourceContext.getAdditionalSourceNames()).thenReturn(ciSet("APNIC-GRS", "ARIN-GRS"));
        when(sourceContext.getWhoisSlaveSource()).thenReturn(Source.slave("RIPE"));

        final Query query = Query.parse("10.0.0.0");
        final CaptureResponseHandler responseHandler = new CaptureResponseHandler();
        subject.execute(query, responseHandler);

        verify(sourceContext).setCurrent(Source.slave("RIPE"));
        verify(sourceContext).setCurrent(Source.slave("APNIC-GRS"));
        verify(sourceContext).setCurrent(Source.slave("ARIN-GRS"));
        verify(sourceContext, times(3)).removeCurrentSource();
        verify(rpslObjectSearcher, times(3)).search(query);
    }

    @Test
    public void query_sources_not_additional() {
        when(sourceContext.getAdditionalSourceNames()).thenReturn(ciSet("RIPE", "APNIC-GRS", "ARIN-GRS"));

        final Query query = Query.parse("--sources APNIC-GRS,ARIN-GRS 10.0.0.0");

        final CaptureResponseHandler responseHandler = new CaptureResponseHandler();
        subject.execute(query, responseHandler);

        verify(sourceContext).setCurrent(Source.slave("APNIC-GRS"));
        verify(sourceContext).setCurrent(Source.slave("ARIN-GRS"));
        verify(sourceContext, times(2)).removeCurrentSource();
        verify(rpslObjectSearcher, times(2)).search(query);
    }

}


text:
using System;
using Newtonsoft.Json;

namespace Vk.Api.Schema.Serialization.Converters
{

#pragma warning disable 1591

    internal class UnixDateTimeConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(DateTime);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var t = long.TryParse(reader.Value.ToString(), out long ms);
            return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ms);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
function Update-DbaInstance {
    <#
    .SYNOPSIS
        Invokes installation of SQL Server Service Packs and Cumulative Updates on local and remote servers.

    .DESCRIPTION
        Starts and automated process of updating SQL Server installation to a specific version defined in the parameters.
        The command will:

        * Search for SQL Server installations in a remote registry
        * Check if current settings are applicable to the current SQL Server versions
        * Search for a KB executable in a folder specified in -Path
        * Establish a PSRemote connection to the target machine if necessary
        * Extract KB to a temporary folder in a current user's profile
        * Run the installation from the temporary folder updating all instances on the computer at once
        * Remove temporary files
        * Restart the computer (if -Restart is specified)
        * Repeat for each consequent KB and computer

        The impact of this function is set to High, if you don't want to receive interactive prompts, set -Confirm to $false.
        Credentials are a required parameter for remote machines. Without specifying -Credential, the installation will fail due to lack of permissions.

        CredSSP is a recommended transport for running the updates remotely. Update-DbaInstance will attempt to reconfigure
        local and remote hosts to support CredSSP, which is why it is desirable to run this command in an elevated console at all times.
        CVE-2018-0886 security update is required for both local and remote hosts. If CredSSP connections are failing, make sure to
        apply recent security updates prior to doing anything else.

        Always backup databases and configurations prior to upgrade.

    .PARAMETER ComputerName
        Target computer with SQL instance or instances.

    .PARAMETER Credential
        Windows Credential with permission to log on to the remote server.
        Must be specified for any remote connection if update Repository is located on a network folder.

    .PARAMETER Type
        Type of the update: All | ServicePack | CumulativeUpdate.
        Default: All
        Use -Version to limit upgrade to a certain Major version of SQL Server.

    .PARAMETER KB
        Install a specific update or list of updates. Can be a number of a string KBXXXXXXX.

    .PARAMETER Version
        A target version of the installation you want to reach. If not specified, a latest available version would be used by default.
        Can be defined using the following general pattern: <MajorVersion><SPX><CUX>.
        Any part of the pattern can be omitted if needed:
        2008R2SP1 - will update SQL 2008R2 to SP1
        2016CU3 - will update SQL 2016 to CU3 of current Service Pack installed
        SP0CU3 - will update all existing SQL Server versions to RTM CU3 without installing any service packs
        SP1CU7 - will update all existing SQL Server versions to SP1 and then (after restart if -Restart is specified) to SP1CU7
        CU7 - will update all existing SQL Server versions to CU7 of current Service Pack installed

    .PARAMETER Path
        Path to the folder(s) with SQL Server patches downloaded. It will be scanned recursively for available patches.
        Path should be available from both server with SQL Server installation and client that runs the command.
        All file names should match the pattern used by Microsoft: SQLServer####*-KB###-*x##*.exe
        If a file is missing in the repository, the installation will fail.
        Consider setting the following configuration if you want to omit this parameter: `Set-DbatoolsConfig -Name Path.SQLServerUpdates -Value '\\path\to\updates'`

    .PARAMETER Restart
        Restart computer automatically after a successful installation of a patch and wait until it comes back online.
        Using this parameter is the only way to chain-install more than 1 patch on a computer, since every single patch will require a restart of said computer.

    .PARAMETER Continue
        Continues a failed installation attempt when specified. Will abort a previously failed installation otherwise.

    .PARAMETER Authentication
        Chooses an authentication protocol for remote connections.
        If the protocol fails to establish a connection

        Defaults:
        * CredSSP when -Credential is specified - due to the fact that repository Path is usually a network share and credentials need to be passed to the remote host
          to avoid the double-hop issue.
        * Default when -Credential is not specified. Will likely fail if a network path is specified.

    .PARAMETER InstanceName
        Only updates a specific instance(s).

    .PARAMETER Throttle
        Maximum number of computers updated in parallel. Once reached, the update operations will queue up.
        Default: 50

    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.

    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Install, Patching, SP, CU, Instance
        Author: Kirill Kravtsov (@nvarscar) https://nvarscar.wordpress.com/

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

        Requires Local Admin rights on destination computer(s).

    .EXAMPLE
        PS C:\> Update-DbaInstance -ComputerName SQL1 -Version SP3 -Path \\network\share

        Updates all applicable SQL Server installations on SQL1 to SP3.
        Binary files for the update will be searched among all files and folders recursively in \\network\share.
        Prompts for confirmation before the update.

    .EXAMPLE
        PS C:\> Update-DbaInstance -ComputerName SQL1, SQL2 -Restart -Path \\network\share -Confirm:$false

        Updates all applicable SQL Server installations on SQL1 and SQL2 with the most recent patch.
        It will install latest ServicePack, restart the computers, install latest Cumulative Update, and finally restart the computer once again.
        Binary files for the update will be searched among all files and folders recursively in \\network\share.
        Does not prompt for confirmation.

    .EXAMPLE
        PS C:\> Update-DbaInstance -ComputerName SQL1 -Version 2012 -Type ServicePack -Path \\network\share

        Updates SQL Server 2012 on SQL1 with the most recent ServicePack found in your patch repository.
        Binary files for the update will be searched among all files and folders recursively in \\network\share.
        Prompts for confirmation before the update.

    .EXAMPLE
        PS C:\> Update-DbaInstance -ComputerName SQL1 -KB 123456 -Restart -Path \\network\share -Confirm:$false

        Installs KB 123456 on SQL1 and restarts the computer.
        Binary files for the update will be searched among all files and folders recursively in \\network\share.
        Does not prompt for confirmation.

    .EXAMPLE
        PS C:\> Update-DbaInstance -ComputerName Server1 -Version SQL2012SP3, SQL2016SP2CU3 -Path \\network\share -Restart -Confirm:$false

        Updates SQL 2012 to SP3 and SQL 2016 to SP2CU3 on Server1. Each update will be followed by a restart.
        Binary files for the update will be searched among all files and folders recursively in \\network\share.
        Does not prompt for confirmation.

    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', DefaultParameterSetName = 'Version')]
    Param (
        [parameter(ValueFromPipeline, Position = 1)]
        [Alias("cn", "host", "Server")]
        [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
        [pscredential]$Credential,
        [Parameter(ParameterSetName = 'Version')]
        [ValidateNotNullOrEmpty()]
        [string[]]$Version,
        [Parameter(ParameterSetName = 'Version')]
        [ValidateSet('All', 'ServicePack', 'CumulativeUpdate')]
        [string[]]$Type = @('All'),
        [Parameter(Mandatory, ParameterSetName = 'KB')]
        [ValidateNotNullOrEmpty()]
        [string[]]$KB,
        [Alias("Instance")]
        [string]$InstanceName,
        [string[]]$Path = (Get-DbatoolsConfigValue -Name 'Path.SQLServerUpdates'),
        [switch]$Restart,
        [switch]$Continue,
        [ValidateNotNull()]
        [int]$Throttle = 50,
        [ValidateSet('Default', 'Basic', 'Negotiate', 'NegotiateWithImplicitCredential', 'Credssp', 'Digest', 'Kerberos')]
        [string]$Authentication = 'Credssp',
        [switch]$EnableException
    )
    begin {
        $notifiedCredentials = $false
        $notifiedUnsecure = $false
        #Validating parameters
        if ($PSCmdlet.ParameterSetName -eq 'Version') {
            foreach ($v in $Version) {
                if ($v -notmatch '^((SQL)?\d{4}(R2)?)?\s*(RTM|SP\d+)?\s*(CU\d+)?$') {
                    Stop-Function -Category InvalidArgument -Message "$Version is an incorrect Version value, please refer to Get-Help Update-DbaInstance -Parameter Version"
                    return
                }
            }
        } elseif ($PSCmdlet.ParameterSetName -eq 'KB') {
            $kbList = @()
            foreach ($kbItem in $KB) {
                if ($kbItem -match '^(KB)?(\d+)$') {
                    $kbList += $Matches[2]
                } else {
                    Stop-Function -Category InvalidArgument -Message "$kbItem is an incorrect KB value, please refer to Get-Help Update-DbaInstance -Parameter KB"
                    return
                }
            }
        }
        $actions = @()
        $actionTemplate = @{}
        if ($InstanceName) { $actionTemplate.InstanceName = $InstanceName }
        if ($Continue) { $actionTemplate.Continue = $Continue }
        #Putting together list of actions based on current ParameterSet
        if ($PSCmdlet.ParameterSetName -eq 'Version') {
            if ($Type -contains 'All') { $typeList = @('ServicePack', 'CumulativeUpdate') }
            else { $typeList = $Type | Sort-Object -Descending }
            foreach ($ver in $Version) {
                $currentAction = $actionTemplate.Clone()
                if ($ver -and $ver -match '^(SQL)?(\d{4}(R2)?)?\s*(RTM|SP)?(\d+)?(CU)?(\d+)?') {
                    $majorV, $spV, $cuV = $Matches[2, 5, 7]
                    Write-Message -Level Debug -Message "Parsed Version as Major $majorV SP $spV CU $cuV"
                    # Add appropriate fields to the splat
                    # Add version to every field
                    if ($null -ne $majorV) {
                        $currentAction += @{
                            MajorVersion = $majorV
                        }
                        # When version is the only thing that is specified, we want all the types added
                        if ($null -eq $spV -and $null -eq $cuV) {
                            foreach ($currentType in $typeList) {
                                $actions += $currentAction.Clone() + @{ Type = $currentType }
                            }
                        }
                    }
                    #when SP# is specified
                    if ($null -ne $spV) {
                        $currentAction += @{
                            ServicePack = $spV
                        }
                        # ignore SP0 and trigger only when SP is in Type
                        if ($spV -ne '0' -and 'ServicePack' -in $typeList) {
                            $actions += $currentAction.Clone()
                        }
                    }
                    # When CU# is specified, but ignore CU0 and trigger only when CU is in Type
                    if ($null -ne $cuV -and $cuV -ne '0' -and 'CumulativeUpdate' -in $typeList) {
                        $actions += $currentAction.Clone() + @{ CumulativeUpdate = $cuV }
                    }
                } else {
                    Stop-Function -Category InvalidArgument -Message "$ver is an incorrect Version value, please refer to Get-Help Update-DbaInstance -Parameter Version"
                    return
                }
            }
            # If no version specified, simply apply latest $currentType
            if (!$Version) {
                foreach ($currentType in $typeList) {
                    $currentAction = $actionTemplate.Clone() + @{
                        Type = $currentType
                    }
                    $actions += $currentAction
                }
            }
        } elseif ($PSCmdlet.ParameterSetName -eq 'KB') {
            foreach ($kbItem in $kbList) {
                $currentAction = $actionTemplate.Clone() + @{
                    KB = $kbItem
                }
                $actions += $currentAction
            }
        }
        # debug message
        foreach ($a in $actions) {
            Write-Message -Level Debug -Message "Added installation action $($a | ConvertTo-Json -Depth 1 -Compress)"
        }
        # defining how to process the final results
        $outputHandler = {
            $_ | Select-DefaultView -Property ComputerName, MajorVersion, TargetLevel, KB, Successful, Restarted, InstanceName, Installer, Notes
            if ($_.Successful -eq $false) {
                Write-Message -Level Warning -Message "Update failed: $($_.Notes -join ' | ')"
            }
        }
    }
    process {
        if (Test-FunctionInterrupt) { return }

        #Resolve all the provided names
        $resolvedComputers = @()
        $pathIsNetwork = $Path | Foreach-Object -Begin { $o = @() } -Process { $o += $_ -like '\\*'} -End { $o -contains $true }
        foreach ($computer in $ComputerName) {
            $null = Test-ElevationRequirement -ComputerName $computer -Continue
            if (!$computer.IsLocalHost -and -not $notifiedCredentials -and -not $Credential -and $pathIsNetwork) {
                Write-Message -Level Warning -Message "Explicit -Credential might be required when running agains remote hosts and -Path is a network folder"
                $notifiedCredentials = $true
            }
            if ($resolvedComputer = Resolve-DbaNetworkName -ComputerName $computer.ComputerName) {
                $resolvedComputers += $resolvedComputer.FullComputerName
            }
        }
        #Leave only unique computer names
        $resolvedComputers = $resolvedComputers | Sort-Object -Unique
        #Process planned actions and gather installation actions
        $installActions = @()
        :computers foreach ($resolvedName in $resolvedComputers) {
            $activity = "Preparing to update SQL Server on $resolvedName"
            ## Find the current version on the computer
            Write-ProgressHelper -ExcludePercent -Activity $activity -StepNumber 0 -Message "Gathering all SQL Server instance versions"
            try {
                $components = Get-SQLInstanceComponent -ComputerName $resolvedName -Credential $Credential
            } catch {
                Stop-Function -Message "Error while looking for SQL Server installations on $resolvedName" -Continue -ErrorRecord $_
            }
            if (!$components) {
                Stop-Function -Message "No SQL Server installations found on $resolvedName" -Continue
            }
            Write-Message -Level Debug -Message "Found $(($components | Measure-Object).Count) existing SQL Server instance components: $(($components | Foreach-Object { "$($_.InstanceName)($($_.InstanceType) $($_.Version.NameLevel))" }) -join ',')"
            # Filter for specific instance name
            if ($InstanceName) {
                $components = $components | Where-Object {$_.InstanceName -eq $InstanceName }
            }
            try {
                $restartNeeded = Test-PendingReboot -ComputerName $resolvedName -Credential $Credential
            } catch {
                Stop-Function -Message "Failed to get reboot status from $resolvedName" -Continue -ErrorRecord $_
            }
            if ($restartNeeded -and (-not $Restart -or ([DbaInstanceParameter]$resolvedName).IsLocalHost)) {
                #Exit the actions loop altogether - nothing can be installed here anyways
                Stop-Function -Message "$resolvedName is pending a reboot. Reboot the computer before proceeding." -Continue
            }
            $upgrades = @()
            :actions foreach ($currentAction in $actions) {
                # Attempt to configure CredSSP for the remote host when credentials are defined
                if ($Credential -and -not ([DbaInstanceParameter]$resolvedName).IsLocalHost -and $Authentication -eq 'Credssp') {
                    Write-Message -Level Verbose -Message "Attempting to configure CredSSP for remote connections"
                    Initialize-CredSSP -ComputerName $resolvedName -Credential $Credential -EnableException $false
                    # Verify remote connection and confirm using unsecure credentials
                    try {
                        $secureProtocol = Invoke-Command2 -ComputerName $resolvedName -Credential $Credential -Authentication $Authentication -ScriptBlock { $true } -Raw
                    } catch {
                        $secureProtocol = $false
                    }
                    # only ask once about using unsecure protocol
                    if (-not $secureProtocol -and -not $notifiedUnsecure) {
                        if ($PSCmdlet.ShouldProcess($resolvedName, "Primary protocol ($Authentication) failed, sending credentials via potentially unsecure protocol")) {
                            $notifiedUnsecure = $true
                        } else {
                            Stop-Function -Message "Failed to connect to $resolvedName through $Authentication protocol. No actions will be performed on that computer." -Continue -ContinueLabel computers
                        }
                    }
                }
                # Pass only relevant components
                if ($currentAction.MajorVersion) {
                    Write-Message -Level Debug -Message "Limiting components to version $($currentAction.MajorVersion)"
                    $selectedComponents = $components | Where-Object { $_.Version.NameLevel -contains $currentAction.MajorVersion }
                    $currentAction.Remove('MajorVersion')
                } else {
                    $selectedComponents = $components
                }
                Write-ProgressHelper -ExcludePercent -Activity $activity -Message "Looking for a KB file for a chosen version"
                Write-Message -Level Debug -Message "Looking for appropriate KB file on $resolvedName with following params: $($currentAction | ConvertTo-Json -Depth 1 -Compress)"
                # get upgrade details for each component
                $upgradeDetails = Get-SqlServerUpdate @currentAction -ComputerName $resolvedName -Credential $Credential -Component $selectedComponents
                if ($upgradeDetails.Successful -contains $false) {
                    #Exit the actions loop altogether - upgrade cannot be performed
                    $upgradeDetails
                    Stop-Function -Message "Update cannot be applied to $resolvedName | $($upgradeDetails.Notes -join ' | ')" -Continue -ContinueLabel computers
                }

                foreach ($detail in $upgradeDetails) {
                    # search for installer for each target upgrade
                    $kbLookupParams = @{
                        ComputerName   = $resolvedName
                        Credential     = $Credential
                        Authentication = $Authentication
                        Architecture   = $detail.Architecture
                        MajorVersion   = $detail.MajorVersion
                        Path           = $Path
                        KB             = $detail.KB
                    }
                    try {
                        $installer = Find-SqlServerUpdate @kbLookupParams
                    } catch {
                        Stop-Function -Message "Failed to enumerate files in -Path" -ErrorRecord $_ -Continue
                    }
                    if ($installer) {
                        $detail.Installer = $installer.FullName
                    } else {
                        Stop-Function -Message "Could not find installer for the SQL$($detail.MajorVersion) update KB$($detail.KB)" -Continue
                    }
                    # update components to mirror the updated version - will be used for multi-step upgrades
                    foreach ($component in $components) {
                        if ($component.Version.NameLevel -eq $detail.TargetVersion.NameLevel) {
                            $component.Version = $detail.TargetVersion
                        }
                    }
                    # finally, add the upgrade details to the upgrade list
                    $upgrades += $detail
                }
            }
            if ($upgrades) {
                Write-ProgressHelper -ExcludePercent -Activity $activity -Message "Preparing installation"
                $chosenVersions = ($upgrades | ForEach-Object { "$($_.MajorVersion) to $($_.TargetLevel) (KB$($_.KB))" }) -join ', '
                if ($PSCmdlet.ShouldProcess($resolvedName, "Update $chosenVersions")) {
                    $installActions += [pscustomobject]@{
                        ComputerName = $resolvedName
                        Actions      = $upgrades
                    }
                }
            }
            Write-Progress -Activity $activity -Completed
        }
        $explicitAuth = Test-Bound -Parameter Authentication
        # Declare the installation script
        $installScript = {
            $updateSplat = @{
                ComputerName    = $_.ComputerName
                Action          = $_.Actions
                Restart         = $Restart
                Credential      = $Credential
                EnableException = $EnableException
            }
            if ($explicitAuth) { $updateSplat.Authentication = $Authentication }
            Invoke-DbaAdvancedUpdate @updateSplat
        }
        # check how many computers we are looking at and decide upon parallelism
        if ($installActions.Count -eq 1) {
            $installActions | ForEach-Object -Process $installScript | ForEach-Object -Process $outputHandler
        } elseif ($installActions.Count -ge 2) {
            $installActions | Invoke-Parallel -ImportModules -ImportVariables -ScriptBlock $installScript -Throttle $Throttle | ForEach-Object -Process $outputHandler
        }
    }
}


text:
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;

namespace Inference.Parser
{
    #region TokenType

    public enum TokenType
    {
        T_IntLit,		        // Integer literal
        T_FltLit,			    // Floating-point literal
        T_StrLit,			    // String literal
        T_StrLit2,			    // String literal, type 2 (i.e. a different string delimiter character is used)
        T_Ident,			    // Identifier
        T_BoolIdent,		    // Boolean identifier, beginning with @ ; e.g. @id
        T_SkolemIdent,          // Skolem identifier (non-Boolean), beginning with $ ; e.g. $S1
        T_Variable,             // E.g. ?var
        T_Mult,			        // *
        T_Div,			        // /
        T_Plus,			        // +
        T_Minus,			    // -
        T_Equal,			    // =
        T_NotEqual,		        // /=
        T_Less,			        // <
        T_LessEqual,		    // <=
        T_Greater,			    // >
        T_GreaterEqual,		    // >=
        T_Semicolon,		    // ;
        T_Comma,			    // ,
        T_2OrBar,			    // ||
        T_2Ampersand,		    // &&
        T_LeftBracket,		    // (
        T_RightBracket,		    // )
        T_Assign,			    // :=
        T_Arrow,			    // ->
        T_Exclamation,          // !
        T_Apostrophe,           // '
        T_Octothorpe,           // #
        T_Dollar,               // $
        T_Dot,			        // .
        T_LeftSquareBracket,	// [
        T_RightSquareBracket,	// ]
        T_OrBar,			    // |
        T_Colon,                // : (for JSON and Prolog)
        T_LeftCurlyBrace,       // { (for JSON and Prolog)
        T_RightCurlyBrace,      // } (for JSON and Prolog)
        T_QuoteKeyword,         // quote
        T_QuestionMinus,
        T_ColonMinus,
        T_EqualLessThan,
        T_BackslashPlus,
        T_BackslashEqual,
        T_EqualEqual,
        T_BackslashEqualEqual,
        T_EqualColonEqual,
        T_EqualBackslashEqual,
        T_MinusMinusGreaterThan,
        T_EqualDotDot,
        T_Caret,                // ^
        T_EOF,			        // End of file (no errors detected)
        //T_EOF_Error,            // End of file (one or more errors detected)
        //T_APOST,			    /* ' */
        //T_2DOT,			    /* .. */
        //T_POWER,			    /* ** */
        //EndOfT,

        // Non-accept (intermediate) states
        S_Start,			    // Start state
        S_Error,
        S_StrLitOpen,
        S_StrLit2Open,
        S_IntLitDot,
        S_Question,             // Question mark
        S_Ampersand, 		    // &
        S_At,                   // @
        S_Dollar,               // $
        S_Backslash,
        S_EqualColon,
        S_EqualBackslash,
        S_MinusMinus,
        S_EqualDot
    }

    #endregion

    #region TokenizerTableKey

    public class TokenizerTableKey
    {
        public readonly TokenType state;
        public readonly char c;

        public TokenizerTableKey(TokenType stateParam, char cParam)
        {
            state = stateParam;
            c = cParam;
        }

        public override bool Equals(object obj)
        {

            if (object.ReferenceEquals(this, obj))
            {
                return true;
            }

            var otherKey = obj as TokenizerTableKey;

            return otherKey != null && state == otherKey.state && c == otherKey.c;
        }

        public override int GetHashCode()
        {
            return state.GetHashCode() * 257 + c.GetHashCode();
        }
    }

    #endregion

    #region Token

    public class Token
    {
        public readonly TokenType TokenType;
        public readonly object TokenValue;
        public readonly int Line;
        public readonly int Column;
        public readonly bool IsQuoted;

        public Token(TokenType tt, object tv, int line, int col, bool isQuoted = false)
        {
            TokenType = tt;
            TokenValue = tv;
            Line = line;
            Column = col;
            IsQuoted = isQuoted;
        }

        public Token CloneWithNewLineNumber(int line)
        {
            return new Token(TokenType, TokenValue, line, Column, IsQuoted);
        }
    }

    #endregion

    #region ITokenizer

    public interface ITokenizer
    {
        List<Token> Tokenize(string str);
    }

    #endregion

    #region TokenizerException

    public class TokenizerException : Exception
    {
        public readonly int Line;
        public readonly int Column;

        public TokenizerException(string message, int line, int col)
            : base(message)
        {
            Line = line;
            Column = col;
        }
    }

    #endregion

    #region TokenizerBase

    public abstract class TokenizerBase : ITokenizer
    {
        protected abstract void SetInputString(string str);

        protected abstract Token GetToken();

        public List<Token> Tokenize(string str)
        {
            var tokenList = new List<Token>();
            Token token = null;

            SetInputString(str);

            do
            {
                token = GetToken();
                tokenList.Add(token);
            }
            while (token.TokenType != TokenType.T_EOF);

            return tokenList;
        }
    }

    #endregion

    #region FSMTokenizer

    // A tokenizer based on a finite state machine.

    public class FSMTokenizer : TokenizerBase
    {
        protected readonly GrammarSelector gs;
        protected readonly HashSet<TokenType> acceptableTokens = new HashSet<TokenType>();
        private readonly Dictionary<TokenizerTableKey, TokenType> table = new Dictionary<TokenizerTableKey, TokenType>();
        private string m_str = null;   // The string to be tokenized.
        private readonly StringBuilder sbToken = new StringBuilder();
        //private bool was_err = false;   // Set to true if lexical error occurs
        private int line_num = 1;		// Current line number
	    private int col_num = 1;        // Current column number
        private int char_num = 0;       // Current index into m_str
        protected char cStringDelimiter = '"';  // This must be the delimiter for TokenType.T_StrLit
        protected readonly Dictionary<TokenType, char> dictInternalStringStateToDelimiter = new Dictionary<TokenType, char>();
        protected readonly Dictionary<TokenType, TokenType> dictInternalStringStateToCompletedState = new Dictionary<TokenType, TokenType>();
        protected bool removeComments = false;
        protected char cCommentDelimiter = '#';

        public FSMTokenizer(GrammarSelector gs)
        {
            this.gs = gs;

            dictInternalStringStateToDelimiter[TokenType.S_StrLitOpen] = cStringDelimiter;
            dictInternalStringStateToCompletedState[TokenType.S_StrLitOpen] = TokenType.T_StrLit;

            acceptableTokens.Add(TokenType.T_IntLit);
            acceptableTokens.Add(TokenType.T_FltLit);
            acceptableTokens.Add(TokenType.T_StrLit);
            acceptableTokens.Add(TokenType.T_Ident);
            acceptableTokens.Add(TokenType.T_Mult);
            acceptableTokens.Add(TokenType.T_Div);
            acceptableTokens.Add(TokenType.T_Plus);
            acceptableTokens.Add(TokenType.T_Minus);
            acceptableTokens.Add(TokenType.T_Equal);
            acceptableTokens.Add(TokenType.T_NotEqual);
            acceptableTokens.Add(TokenType.T_Less);
            //acceptableTokens.Add(TokenType.T_LessEqual); // In Prolog, it's =<, not <=
            acceptableTokens.Add(TokenType.T_Greater);
            acceptableTokens.Add(TokenType.T_GreaterEqual);
            acceptableTokens.Add(TokenType.T_Semicolon);
            acceptableTokens.Add(TokenType.T_Comma);
            acceptableTokens.Add(TokenType.T_LeftBracket);
            acceptableTokens.Add(TokenType.T_RightBracket);
            acceptableTokens.Add(TokenType.T_Arrow);
            acceptableTokens.Add(TokenType.T_EOF);

            AddTransition(TokenType.S_Start, 'A', TokenType.T_Ident);
            AddTransition(TokenType.S_Start, '0', TokenType.T_IntLit);
            AddTransition(TokenType.S_Start, cStringDelimiter, TokenType.S_StrLitOpen);
            AddTransition(TokenType.S_Start, '*', TokenType.T_Mult);
            AddTransition(TokenType.S_Start, '/', TokenType.T_Div);
            AddTransition(TokenType.S_Start, '+', TokenType.T_Plus);
            AddTransition(TokenType.S_Start, '-', TokenType.T_Minus);
            AddTransition(TokenType.S_Start, '=', TokenType.T_Equal);
            AddTransition(TokenType.S_Start, '<', TokenType.T_Less);
            AddTransition(TokenType.S_Start, '>', TokenType.T_Greater);
            AddTransition(TokenType.S_Start, ':', TokenType.T_Colon);
            AddTransition(TokenType.S_Start, ';', TokenType.T_Semicolon);
            AddTransition(TokenType.S_Start, ',', TokenType.T_Comma);
            AddTransition(TokenType.S_Start, '|', TokenType.T_OrBar);
            AddTransition(TokenType.S_Start, '(', TokenType.T_LeftBracket);
            AddTransition(TokenType.S_Start, ')', TokenType.T_RightBracket);
            AddTransition(TokenType.T_Ident, 'A', TokenType.T_Ident);
            AddTransition(TokenType.T_Ident, '0', TokenType.T_Ident);
            AddTransition(TokenType.T_Ident, '_', TokenType.T_Ident);
            AddTransition(TokenType.T_IntLit, '0', TokenType.T_IntLit);
            AddTransition(TokenType.T_IntLit, '.', TokenType.S_IntLitDot);
            AddTransition(TokenType.S_IntLitDot, '0', TokenType.T_FltLit);
            AddTransition(TokenType.T_FltLit, '0', TokenType.T_FltLit);
            AddTransition(TokenType.S_StrLitOpen, cStringDelimiter, TokenType.T_StrLit);
            AddTransition(TokenType.T_StrLit, cStringDelimiter, TokenType.S_StrLitOpen);
            AddTransition(TokenType.T_Minus, '0', TokenType.T_IntLit);
            AddTransition(TokenType.T_Minus, '>', TokenType.T_Arrow);
            AddTransition(TokenType.T_Greater, '=', TokenType.T_GreaterEqual);
        }

        protected override void SetInputString(string str)
        {
            m_str = str;
            line_num = 1;
            col_num = 1;
            char_num = 0;
        }

        protected void AddTransition(TokenType oldState, char c, TokenType newState)
        {
            var key = new TokenizerTableKey(oldState, c);

            if (table.ContainsKey(key))
            {
                throw new Exception(string.Format("Tokenizer.AddTransition() : The key [{0}, {1}] already exists in the transition table", oldState, c));
            }

            table[key] = newState;
        }

        private char GetChar()
        {

            if (m_str == null)
            {
                throw new Exception("Tokenizer.GetChar() : The input string is null.  SetInputString() must be called first.");
            }

            if (char_num >= 0 && char_num < m_str.Length)
            {
                return m_str[char_num];
            }

            return '\0';
        }

        private TokenType RecoverToken(List<TokenType> state_list)
        {

            for (var i = state_list.Count - 1; i > 0; i--)
            {

                if (acceptableTokens.Contains(state_list[i]))
                {
                    // Keep only the first i characters of token_str.
                    var newTokenStr = sbToken.ToString().Substring(0, i);

                    sbToken.Clear();
                    sbToken.Append(newTokenStr);
                    // We do not need to trim the end of the state_list.
	                return state_list[i];
	            }
            }

            return TokenType.S_Error;
        }

        protected string GetStrLitFromTokenStr(char cDelimiter)
        {
            var token_str = sbToken.ToString();

            if (string.IsNullOrEmpty(token_str) || token_str[0] != cDelimiter)
            {
                throw new Exception("Tokenizer.GetStrLitFromTokenStr() : Token string error");
            }

            var insideQuotes = true;
            var sb = new StringBuilder();

            for (var i = 1; i < token_str.Length; ++i)
            {
                var c = token_str[i];

                // This logic allows two consecutive string delimiters within the string to be interpreted as a single literal string delimiter.
                if (c != cDelimiter || !insideQuotes)
                {
                    sb.Append(c);
                    insideQuotes = true;
                }
                else
                {
                    insideQuotes = false;
                }
            }

            return sb.ToString();
        }

        protected virtual object ExtendedGetTokenValue(ref TokenType s, string token_str)
        {
            return null;
        }

        // Return the next valid token read from the specified file stream.
        // Read buffered characters before reading new characters from fp.

        protected override Token GetToken()
        {
            var state_list = new List<TokenType>();     // List of states corresponding to not-yet-accepted characters
            char c;                                     // A character read from get_char()
	        var start_col = col_num;		            // The column of the first char in a token
            var s = TokenType.S_Start;                  // Current state

            sbToken.Clear();
            state_list.Add(s);

            for ( ; ; ) 	// Loop until valid token read
            {
                char cSimplified;

                c = GetChar();

                if (char.IsLetter(c))
                {
                    cSimplified = 'A';
                }
                else if (char.IsDigit(c))
                {
                    cSimplified = '0';
                }
                else
                {
                    cSimplified = c;
                }

	            if (s != TokenType.S_Start  &&  ( c == '\0'  ||  c == '\n'  ||
                    (char.IsWhiteSpace(c) && !dictInternalStringStateToCompletedState.ContainsKey(s))))
                {

                    if (dictInternalStringStateToCompletedState.ContainsKey(s) && (c == '\0' || c == '\n'))   // Newline or EOF delimits string literal
                    {
                        s = dictInternalStringStateToCompletedState[s];
                    }

                    if (c == '\n')
                    {
                        ++char_num;
                    }

                    if (acceptableTokens.Contains(s))
                    {
		                // Valid token has been delimited by white space
		                break;
	                }
                    else
                    {
                        // Error - try to recover
		                s = TokenType.S_Error;
	                }
	            }

                TokenType newState;

                if (s == TokenType.S_Start && c == '\0')
                {
                    newState = TokenType.T_EOF;
                }
                else if (s == TokenType.S_Start && c == '\n')
                {
                    ++line_num;
                    col_num = 1;
                    start_col = 1;    // Don't buffer white space
                    newState = s; // TokenType.S_Start;
                }
                else if (s == TokenType.S_Start && char.IsWhiteSpace(c))
                {
                    ++start_col;    // Don't buffer white space
                    newState = s; // TokenType.S_Start;
                }
                else if (s == TokenType.S_Start && removeComments && c == cCommentDelimiter)
                {

                    for (; ; )
                    {
                        ++char_num;
                        c = GetChar();

                        if (c == '\0')
                        {
                            newState = TokenType.T_EOF;
                            break;
                        }
                        else if (c == '\n')
                        {
                            ++line_num;
                            col_num = 1;
                            start_col = 1;    // Don't buffer white space
                            newState = s; // TokenType.S_Start;
                            break;
                        }
                    }
                }
#if DEAD_CODE
	            else if (s == TokenType.S_StrLitOpen && c != cStringDelimiter)
                {
                    newState = s;
		        }
#else
                else if (dictInternalStringStateToDelimiter.ContainsKey(s) && c != dictInternalStringStateToDelimiter[s])
                {
                    newState = s;
                }
#endif
                else
                {
                    var key = new TokenizerTableKey(s, cSimplified);

                    if (table.ContainsKey(key))
                    {
                        newState = table[key];
                    }
                    else
                    {
                        newState = TokenType.S_Error;
                    }
                }

                s = newState;

	            if (s == TokenType.T_EOF)
                {
	                break;
	            }
                else if (s == TokenType.S_Error)
                {
                    s = RecoverToken(state_list);

                    if (s != TokenType.S_Error)
                    {
                        var rewindAmount = col_num - (start_col + sbToken.Length);

                        char_num -= rewindAmount;
                        col_num = start_col + sbToken.Length;
                        break;	// Valid token recovered
                    }

                    throw new TokenizerException(string.Format("Lexical error at line {0}, column {1}", line_num, start_col), line_num, start_col);
                    /*
                    Console.WriteLine("Discarding unmatched '{0}' at column {1}", m_str[start_col], start_col);
                    was_err = true;
                    strlit.Clear();
                    ++start_col;
                    col_num = start_col;
                    token_str.Clear();
                    s = TokenType.S_Start;		// Start over at next unmatched char
                    state_list.Clear();
                    state_list.Add(s);
                     */
                }
                else
                {
                    ++char_num;

                    if (c != '\n')
                    {
                        ++col_num;
                    }

                    if (s != TokenType.S_Start)
                    {
                        sbToken.Append(c);
                        state_list.Add(s);
                    }
                }
            }

            if (!acceptableTokens.Contains(s))
            {
                throw new TokenizerException(
                    string.Format("Internal error at line {0}, column {1}: Non-token {2} accepted", line_num, start_col, s),
                    line_num, start_col);
            }

            //Console.WriteLine("Token: {0} ; Line {1}; Column: {2}", sbToken.ToString(), line_num, start_col);

            var token_str = sbToken.ToString();
            object tokenValue;

            switch (s)
            {
                case TokenType.T_IntLit:
                    tokenValue = int.Parse(token_str);
                    break;

                case TokenType.T_FltLit:
                    tokenValue = double.Parse(token_str);
                    break;

                case TokenType.T_StrLit:
                    tokenValue = GetStrLitFromTokenStr(cStringDelimiter);
                    break;

                case TokenType.T_EOF:
                    tokenValue = "EOF";
                    break;

                default:
                    tokenValue = ExtendedGetTokenValue(ref s, token_str); // TODO: Pass s by reference so that the Prolog interpreter can change it in the case of single-quoted strings -> identifiers.

                    if (tokenValue == null)
                    {
                        tokenValue = token_str.ToString();
                    }

                    break;
            }

            var token = new Token(s, tokenValue, line_num, start_col);

            if (c == '\n')
            {
                ++line_num;
                col_num = 1;
            }

            return token;
        }
    }

    #endregion

    #region Tokenizer

    // The tokenizer for the Micro and Inference languages.

    public class Tokenizer : FSMTokenizer
    {
        public Tokenizer(GrammarSelector gs)
            : base(gs)
        {
            acceptableTokens.Add(TokenType.T_Assign);   // := is a Micro token.

            AddTransition(TokenType.T_Colon, '=', TokenType.T_Assign);

            if (gs == GrammarSelector.Inference)
            {
                acceptableTokens.Add(TokenType.T_BoolIdent);
                acceptableTokens.Add(TokenType.T_SkolemIdent);
                acceptableTokens.Add(TokenType.T_2OrBar);
                acceptableTokens.Add(TokenType.T_2Ampersand);
                acceptableTokens.Add(TokenType.T_Exclamation);
                acceptableTokens.Add(TokenType.T_Variable);
                acceptableTokens.Add(TokenType.T_LessEqual);

                AddTransition(TokenType.S_Start, '&', TokenType.S_Ampersand);
                AddTransition(TokenType.S_Start, '?', TokenType.S_Question);
                AddTransition(TokenType.S_Start, '!', TokenType.T_Exclamation);
                AddTransition(TokenType.S_Start, '$', TokenType.S_Dollar);
                AddTransition(TokenType.S_Dollar, 'A', TokenType.T_SkolemIdent);
                AddTransition(TokenType.T_SkolemIdent, 'A', TokenType.T_SkolemIdent);
                AddTransition(TokenType.T_SkolemIdent, '0', TokenType.T_SkolemIdent);
                AddTransition(TokenType.T_SkolemIdent, '_', TokenType.T_SkolemIdent);
                AddTransition(TokenType.T_Less, '=', TokenType.T_LessEqual);
                AddTransition(TokenType.S_Question, 'A', TokenType.T_Variable);
                AddTransition(TokenType.T_Variable, 'A', TokenType.T_Variable);
                AddTransition(TokenType.T_Variable, '0', TokenType.T_Variable);
                AddTransition(TokenType.T_Variable, '_', TokenType.T_Variable);
                AddTransition(TokenType.T_OrBar, '|', TokenType.T_2OrBar);
                AddTransition(TokenType.S_Ampersand, '&', TokenType.T_2Ampersand);
                AddTransition(TokenType.S_Start, '@', TokenType.S_At);
                AddTransition(TokenType.S_At, 'A', TokenType.T_BoolIdent);
                AddTransition(TokenType.T_BoolIdent, 'A', TokenType.T_BoolIdent);
                AddTransition(TokenType.T_BoolIdent, '0', TokenType.T_BoolIdent);
                AddTransition(TokenType.T_BoolIdent, '_', TokenType.T_BoolIdent);
            }
        }

        protected override object ExtendedGetTokenValue(ref TokenType s, string token_str)
        {

            if (gs != GrammarSelector.Inference)
            {
                return null;
            }

            switch (s)
            {
                case TokenType.T_BoolIdent:
                case TokenType.T_SkolemIdent:
                case TokenType.T_Variable:
                    return token_str.Substring(1);     // Omit the @ or $ or ? at the beginning.

                default:
                    return null;
            }
        }
    }

    #endregion

    #region Prolog2Tokenizer

    // The tokenizer for standard Prolog.
    // We need a finite state machine tokenizer to tokenize strings such as "=.." vs. "=" and ".".

    public class Prolog2Tokenizer : FSMTokenizer
    {
        private const char cStringDelimiter2 = '\'';

        public Prolog2Tokenizer()
            : base(GrammarSelector.Prolog2)
        {
            dictInternalStringStateToDelimiter[TokenType.S_StrLit2Open] = cStringDelimiter2;
            dictInternalStringStateToCompletedState[TokenType.S_StrLit2Open] = TokenType.T_StrLit2;

            removeComments = true;
            cCommentDelimiter = '%';

            acceptableTokens.Add(TokenType.T_StrLit2);
            acceptableTokens.Add(TokenType.T_Colon);
            acceptableTokens.Add(TokenType.T_QuestionMinus);
            acceptableTokens.Add(TokenType.T_ColonMinus);
            acceptableTokens.Add(TokenType.T_EqualLessThan);
            acceptableTokens.Add(TokenType.T_BackslashPlus);
            acceptableTokens.Add(TokenType.T_BackslashEqual);
            acceptableTokens.Add(TokenType.T_EqualEqual);
            acceptableTokens.Add(TokenType.T_BackslashEqualEqual);
            acceptableTokens.Add(TokenType.T_EqualColonEqual);
            acceptableTokens.Add(TokenType.T_EqualBackslashEqual);
            acceptableTokens.Add(TokenType.T_MinusMinusGreaterThan);
            acceptableTokens.Add(TokenType.T_EqualDotDot);
            acceptableTokens.Add(TokenType.T_LeftSquareBracket);
            acceptableTokens.Add(TokenType.T_RightSquareBracket);
            acceptableTokens.Add(TokenType.T_LeftCurlyBrace);
            acceptableTokens.Add(TokenType.T_RightCurlyBrace);
            acceptableTokens.Add(TokenType.T_OrBar);
            acceptableTokens.Add(TokenType.T_Dot);
            acceptableTokens.Add(TokenType.T_Exclamation);
            acceptableTokens.Add(TokenType.T_Caret);

            AddTransition(TokenType.S_Start, cStringDelimiter2, TokenType.S_StrLit2Open);
            AddTransition(TokenType.S_StrLit2Open, cStringDelimiter2, TokenType.T_StrLit2);
            AddTransition(TokenType.T_StrLit2, cStringDelimiter2, TokenType.S_StrLit2Open);
            AddTransition(TokenType.S_Start, '?', TokenType.S_Question);
            AddTransition(TokenType.S_Question, '-', TokenType.T_QuestionMinus);
            AddTransition(TokenType.T_Colon, '-', TokenType.T_ColonMinus);
            AddTransition(TokenType.T_Equal, '<', TokenType.T_EqualLessThan);
            AddTransition(TokenType.S_Start, '\\', TokenType.S_Backslash);
            AddTransition(TokenType.S_Backslash, '+', TokenType.T_BackslashPlus);
            AddTransition(TokenType.S_Backslash, '=', TokenType.T_BackslashEqual);
            AddTransition(TokenType.T_Equal, '=', TokenType.T_EqualEqual);
            AddTransition(TokenType.T_BackslashEqual, '=', TokenType.T_BackslashEqualEqual);
            AddTransition(TokenType.T_Equal, ':', TokenType.S_EqualColon);
            AddTransition(TokenType.S_EqualColon, '=', TokenType.T_EqualColonEqual);
            AddTransition(TokenType.T_Equal, '\\', TokenType.S_EqualBackslash);
            AddTransition(TokenType.S_EqualBackslash, '=', TokenType.T_EqualBackslashEqual);
            AddTransition(TokenType.T_Minus, '-', TokenType.S_MinusMinus);
            AddTransition(TokenType.S_MinusMinus, '>', TokenType.T_MinusMinusGreaterThan);
            AddTransition(TokenType.T_Equal, '.', TokenType.S_EqualDot);
            AddTransition(TokenType.S_EqualDot, '.', TokenType.T_EqualDotDot);
            AddTransition(TokenType.S_Start, '[', TokenType.T_LeftSquareBracket);
            AddTransition(TokenType.S_Start, ']', TokenType.T_RightSquareBracket);
            AddTransition(TokenType.S_Start, '{', TokenType.T_LeftCurlyBrace);
            AddTransition(TokenType.S_Start, '}', TokenType.T_RightCurlyBrace);
            AddTransition(TokenType.S_Start, '.', TokenType.T_Dot);
            AddTransition(TokenType.S_Start, '!', TokenType.T_Exclamation);
            AddTransition(TokenType.S_Start, '_', TokenType.T_Ident);       // For non-binding variables.
            AddTransition(TokenType.S_Start, '^', TokenType.T_Caret);
            //AddTransition(TokenType., '', TokenType.);
        }

        protected override object ExtendedGetTokenValue(ref TokenType s, string token_str)
        {

            switch (s)
            {
                case TokenType.T_StrLit2:
                    //s = TokenType.T_Ident;  // In standard Prolog, single-quoted strings are tokenized as identifiers (except that e.g. 'V' is a functor, not a variable).
                    return GetStrLitFromTokenStr('\'');

                default:
                    return null;
            }
        }
    }

    #endregion

    #region TokenizerFactory

    static public class TokenizerFactory
    {
        static public ITokenizer Create(GrammarSelector gs)
        {

            switch (gs)
            {
                case GrammarSelector.Micro:
                case GrammarSelector.Inference:
                    return new Tokenizer(gs);

                case GrammarSelector.InterpreterChapter1:
                case GrammarSelector.LISP:
                case GrammarSelector.APL:
                case GrammarSelector.Scheme:
                case GrammarSelector.SASL:
                case GrammarSelector.CLU:
                case GrammarSelector.Smalltalk:
                case GrammarSelector.Prolog:
                case GrammarSelector.JSON:
                    return new Inference.Interpreter.InterpreterTokenizer(gs);

                case GrammarSelector.Prolog2:
#if DEAD_CODE
                    return new Inference.Interpreter.InterpreterTokenizer(gs);
#else
                    return new Prolog2Tokenizer();
#endif

                default:
                    break;
            }

            throw new ArgumentException("TokenizerFactory.Create() : Unrecognized GrammarSelector: " + gs.ToString(), "gs");
        }
    }

    #endregion
}


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms").   Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.

/*---
es5id: 15.4.4.22-9-b-1
description: >
    Array.prototype.reduceRight returns initialvalue when Array is
    empty and initialValue is not present
includes: [runTestCase.js]
---*/

function testcase() {

  function callbackfn(prevVal, curVal, idx, obj)
  {
  }

  var arr = new Array(10);

  if(arr.reduceRight(callbackfn,5) === 5)
    return true;
 }
runTestCase(testcase);


text:
<?php
  /**
   *
   */
  class m_admin extends CI_Model
  {
      function scan_profil($query){
        return $this->db->query($query);
      }
      function insertData($table, $data){
        return $this->db->insert($table, $data);
      }

      function deleteData($table, $value){
        return $this->db->delete($table, $value);
      }
      function whereData($table, $where){
        $this->db->select('*');
        $this->db->where($where);
        $this->db->from($table);

        return $this->db->get()->result();
      }
      function cekData($table, $where){
        $this->db->select('*');
        return $this->db->get_where($table, $where);
      }
      function arrData($table,$select){
        $this->db->select($select);
        $this->db->from($table);

        return $this->db->get()->result_array();
      }

      function listData($table, $select){
        $this->db->select($select);
        $this->db->from($table);

        return $this->db->get()->result();
      }

	  function cariList($where){
        $this->db->select('*');
        $this->db->from('presensi');
		$this->db->where($where);

        return $this->db->get()->result();
		}
		function cariNilai($where){
        $this->db->select('*');
        $this->db->from('nilai');
		$this->db->where($where);

        return $this->db->get()->result();
		}
      function updateData($set, $value, $table){
        $this->db->where($set);
        return $this->db->update($table, $value);
      }

      //listPendaftar
      function tambahPendaftar($arrayData){
        return $this->db->insert('pendaftaran', $arrayData);
      }

      function getPendaftar(){
        return $this->db->get('pendaftaran');
      }

      function setVertifikasi($value){
        //seleksi sesuai noDaftar
        $this->db->where($value);
        $this->db->from('pendaftaran');

        return $this->db->get()->result();
      }

      function vertifikasi($arrData){
        return $this->db->insert('murid', $arrData);
      }

      function insertAkun($arrData){
        return $this->db->insert('akun_murid', $arrData);
      }

      //murid
      function listMurid(){
        $this->db->select('*');
        $this->db->from('murid');

        return $this->db->get()->result();
      }

      function updateMurid($nis, $value){
        $this->db->where('nis', $nis);
        return $this->db->update('murid', $value);
      }
      //artikel

      function getArtikel(){

        $this->db->select('judulPost, isiArtikel, linkGambar, kategori');
        $this->db->from('artikel');
        $this->db->order_by('id_post', 'desc');
        return $this->db->get();
      }

      //guru
      function listGuru(){
        $this->db->select('*');
        $this->db->from('guru');

        return $this->db->get()->result();
      }

  }

 ?>


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fontFamily="monospace"
    android:padding="@dimen/layoutMargin1"
    android:textSize="@dimen/textSize2">

</TextView>


text:
There is correlation between:

  * Number of push events prev month and number of push events in next month r=0.655
  * Number of push next month and number open opened issue prev motnh r=0.250

## No correlations

There isn't any correlation between:

  * current number of push events and next activity rating
  * current activity rating and next activity rating

## Activity in repository after 1 year
  * Month: 0 active: 234906
  * Month: 1 active: 60613
  * Month: 2 active: 30853
  * Month: 3 active: 20210
  * Month: 4 active: 14956
  * Month: 5 active: 11779
  * Month: 6 active: 9576
  * Month: 7 active: 8042
  * Month: 8 active: 6815
  * Month: 9 active: 5946
  * Month: 10 active: 5268
  * Month: 11 active: 4658
  * Month: 12 active: 4229


text:
Sign up

End Writer's Block

      <form class="form" name="form" ng-submit="register(form)" novalidate>

          Username

          <input type="text" name="username" class="form-control" ng-model="user.username"
                 required/>

            A username is required

          Email

          <input type="email" name="email" class="form-control" ng-model="user.email"
                 required
                 mongoose-error/>

            Doesn't look like a valid email.

            What's your email address?

            {{ errors.email }}

          Password

          <input type="password" name="password" class="form-control" ng-model="user.password"
                 ng-minlength="3"
                 required
                 mongoose-error/>

            Password must be at least 3 characters.

            {{ errors.password }}

          <button class="btn btn-inverse btn-lg btn-login" type="submit">
            Sign up
          </button>

            Login

      </form>

 Join a community of writers that push each other to write

 Submit your own writing and mark the places where you're stuck or need ideas

 Practice your own writing by helping others in the places where they're stuck

 Earn points by contributing. Defeat writer's block forever


text:
base_dir=`pwd`

RBENV_ROOT=$base_dir/.rbenv
export RBENV_ROOT

export PATH="$RBENV_ROOT/bin:$PATH"
eval "$(rbenv init -)"

rbenv rehash


text:
using System.Drawing;
using System.IO;
using Orchard.ContentManagement;
using Orchard.MediaLibrary.Models;

namespace Orchard.MediaLibrary.Factories {

    public class ImageFactorySelector : IMediaFactorySelector {
        private readonly IContentManager _contentManager;

        public ImageFactorySelector(IContentManager contentManager) {
            _contentManager = contentManager;
        }

        public MediaFactorySelectorResult GetMediaFactory(Stream stream, string mimeType) {
            if (!mimeType.StartsWith("image/")) {
                return null;
            }

            return new MediaFactorySelectorResult {
                Priority = -5,
                MediaFactory = new ImageFactory(_contentManager)
            };

        }
    }

    public class ImageFactory : IMediaFactory {
        private readonly IContentManager _contentManager;

        public ImageFactory(IContentManager contentManager) {
            _contentManager = contentManager;
        }

        public MediaPart CreateMedia(Stream stream, string path, string mimeType) {

            var part = _contentManager.New<MediaPart>("Image");

            part.MimeType = mimeType;
            part.Title = Path.GetFileNameWithoutExtension(path);

            var imagePart = part.As<ImagePart>();
            using (var image = Image.FromStream(stream)) {
                imagePart.Width = image.Width;
                imagePart.Height = image.Height;
            }

            return part;
        }
    }
}


text:
#ifndef CAF_ACTOR_CONFIG_HPP
#define CAF_ACTOR_CONFIG_HPP

#include <functional>

#include "caf/fwd.hpp"
#include "caf/input_range.hpp"
#include "caf/abstract_channel.hpp"

namespace caf {

class actor_config {
public:
  execution_unit* host;
  int flags;
  input_range<const group>* groups;
  std::function<behavior (local_actor*)> init_fun;

  explicit actor_config(execution_unit* ptr = nullptr)
      : host(ptr),
        flags(abstract_channel::is_abstract_actor_flag),
        groups(nullptr) {
    // nop
  }

  inline actor_config& add_flag(int x) {
    flags |= x;
    return *this;
  }
};

} // namespace caf

#endif // CAF_ACTOR_CONFIG_HPP


text:
namespace leveldb {

static std::string PrintContents(WriteBatch* b) {
  InternalKeyComparator cmp(BytewiseComparator());
  MemTable* mem = new MemTable(cmp);
  mem->Ref();
  std::string state;
  Status s = WriteBatchInternal::InsertInto(b, mem);
  int count = 0;
  Iterator* iter = mem->NewIterator();
  for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
    ParsedInternalKey ikey;
    ASSERT_TRUE(ParseInternalKey(iter->key(), &ikey));
    switch (ikey.type) {
      case kTypeValue:
        state.append("Put(");
        state.append(ikey.user_key.ToString());
        state.append(", ");
        state.append(iter->value().ToString());
        state.append(")");
        count++;
        break;
      case kTypeDeletion:
        state.append("Delete(");
        state.append(ikey.user_key.ToString());
        state.append(")");
        count++;
        break;
    }
    state.append("@");
    state.append(NumberToString(ikey.sequence));
  }
  delete iter;
  if (!s.ok()) {
    state.append("ParseError()");
  } else if (count != WriteBatchInternal::Count(b)) {
    state.append("CountMismatch()");
  }
  mem->Unref();
  return state;
}

class WriteBatchTest { };

TEST(WriteBatchTest, Empty) {
  WriteBatch batch;
  ASSERT_EQ("", PrintContents(&batch));
  ASSERT_EQ(0, WriteBatchInternal::Count(&batch));
}

TEST(WriteBatchTest, Multiple) {
  WriteBatch batch;
  batch.Put(Slice("foo"), Slice("bar"));
  batch.Delete(Slice("box"));
  batch.Put(Slice("baz"), Slice("boo"));
  WriteBatchInternal::SetSequence(&batch, 100);
  ASSERT_EQ(100, WriteBatchInternal::Sequence(&batch));
  ASSERT_EQ(3, WriteBatchInternal::Count(&batch));
  ASSERT_EQ("Put(baz, boo)@102"
            "Delete(box)@101"
            "Put(foo, bar)@100",
            PrintContents(&batch));
}

TEST(WriteBatchTest, Corruption) {
  WriteBatch batch;
  batch.Put(Slice("foo"), Slice("bar"));
  batch.Delete(Slice("box"));
  WriteBatchInternal::SetSequence(&batch, 200);
  Slice contents = WriteBatchInternal::Contents(&batch);
  WriteBatchInternal::SetContents(&batch,
                                  Slice(contents.data(),contents.size()-1));
  ASSERT_EQ("Put(foo, bar)@200"
            "ParseError()",
            PrintContents(&batch));
}

TEST(WriteBatchTest, Append) {
  WriteBatch b1, b2;
  WriteBatchInternal::SetSequence(&b1, 200);
  WriteBatchInternal::SetSequence(&b2, 300);
  WriteBatchInternal::Append(&b1, &b2);
  ASSERT_EQ("",
            PrintContents(&b1));
  b2.Put("a", "va");
  WriteBatchInternal::Append(&b1, &b2);
  ASSERT_EQ("Put(a, va)@200",
            PrintContents(&b1));
  b2.Clear();
  b2.Put("b", "vb");
  WriteBatchInternal::Append(&b1, &b2);
  ASSERT_EQ("Put(a, va)@200"
            "Put(b, vb)@201",
            PrintContents(&b1));
  b2.Delete("foo");
  WriteBatchInternal::Append(&b1, &b2);
  ASSERT_EQ("Put(a, va)@200"
            "Put(b, vb)@202"
            "Put(b, vb)@201"
            "Delete(foo)@203",
            PrintContents(&b1));
}

}  // namespace leveldb

#ifndef LEVELDB_PLATFORM_WINDOWS
int main(int argc, char** argv) {
  return leveldb::test::RunAllTests();
}
#endif


text:
package yoda.orm.generator

import com.typesafe.scalalogging.LazyLogging
import yoda.commons.{Accessor, Conf, Naming}
import yoda.orm.definitions.{NamingConvention, SchemaType}

import scala.collection.mutable
import scala.reflect.runtime.universe._

/**
 * @author Peerapat A on Sep 23, 2017
 */
private[generator] object ColumnParser extends LazyLogging
  with Accessor
  with Naming {

  var namingConvention: NamingConvention = NamingConvention(Conf.int("yoda.naming-convention", 1))

  private val cacheCols: mutable.Map[String, List[ColumnMeta]] = mutable.Map()

  def colNames[A: TypeTag]: List[ColumnMeta] = {
    val aname = s"${namingConvention.id}_${typeOf[A].toString}"

    cacheCols.getOrElse(aname, parseCols[A](aname))
  }

  def namingStategy(sym: MethodSymbol): String = namingStategy(sym.name.toString)

  def namingStategy(name: String): String = namingConvention match {
    case NamingConvention.CamelToSnakecase => camelToSnakecase(name)
    case _ => name
  }

  private def parseCols[A: TypeTag](aname: String): List[ColumnMeta] = {
    val list = methods[A]
      .map(sym => ColumnMeta(valName = sym.name.toString
        , schemaType = SchemaType.of(sym)
        , _schemaName = namingStategy(sym.name.toString)))

    cacheCols.put(aname, list)
    list
  }

}


text:
package zk

import (
	"fmt"
	"log"
	"path"
	"strings"
	"sync"
	"time"

	"github.com/samuel/go-zookeeper/zk"
)

const (
	coordinationVersion = "v1"
	defaultZKPort       = 2181
	maxCreateRetries    = 5
)

var defaultZkACL = zk.WorldACL(zk.PermAll)

// A Watcher manages a single connection to zookeeper, watching for changes to
// directories and managing ephemeral nodes. It lazily connects and reconnects
// to zookeeper, and tries its best to be resilient to failures, but defaults to
// silently not providing updates.
type Watcher struct {
	lock           sync.RWMutex
	zkServers      []string
	connectTimeout time.Duration
	sessionTimeout time.Duration
	prefix         string
	conn           *zk.Conn
	errs           chan error
	shutdown       chan bool

	hooksLock      sync.Mutex
	ephemeralNodes map[string]bool
	watchedNodes   map[string]watchedNode

	// How much flapping is allowed before we just die?
	flapLock     sync.Mutex
	flapMax      uint
	flapDuration time.Duration
	flaps        []time.Time
	flapNotify   chan bool
}

type watchedNode struct {
	updates      chan []string
	disconnected chan bool
	cancel       chan bool
}

// Connect connects to the zookeeper cluster specified by zkServers, and returns
// a Watcher. All future operations on the Watcher are rooted at the given
// prefix.
func Connect(zkServers []string, prefix string, connectTimeout, sessionTimeout time.Duration) (*Watcher, error) {
	w := &Watcher{
		zkServers:      zkServers,
		connectTimeout: connectTimeout,
		sessionTimeout: sessionTimeout,
		prefix:         path.Join(prefix, coordinationVersion),
		errs:           make(chan error, 1),
		shutdown:       make(chan bool),
		ephemeralNodes: make(map[string]bool),
		watchedNodes:   make(map[string]watchedNode),
	}

	err := w.reconnect()
	if err != nil {
		return nil, fmt.Errorf("Zookeeper error: %s", err)
	}

	go w.run()
	return w, nil
}

func (w *Watcher) reconnect() error {
	var conn *zk.Conn
	var err error

	for i, s := range w.zkServers {
		if strings.Index(s, ":") < 0 {
			w.zkServers[i] = fmt.Sprintf("%s:%d", s, defaultZKPort)
		}
	}

	w.lock.Lock()
	defer w.lock.Unlock()

	servers := strings.Join(w.zkServers, ",")
	log.Println("sequins ZK connecting to zookeeper at ", servers)
	conn, _, err = zk.Connect(w.zkServers, w.sessionTimeout)
	if err != nil {
		return err
	}

	if w.conn != nil {
		w.conn.Close()
	}
	w.conn = conn

	err = w.createAll(w.prefix)
	if err != nil {
		return fmt.Errorf("creating base path: %s", err)
	}

	// Every time we connect, reset watches and recreate ephemeral nodes.
	err = w.runHooks()
	if err != nil {
		return fmt.Errorf("zookeeper hooks error: %v", err)
	}

	return nil
}

// Must be called with `w.lock` locked for write.
func (w *Watcher) runHooks() error {
	w.hooksLock.Lock()
	defer w.hooksLock.Unlock()

	log.Println("sequins ZK recreating ephemeral nodes")
	for node := range w.ephemeralNodes {
		err := w.createEphemeral(node)
		if err != nil {
			return err
		}
	}

	log.Println("sequins ZK re-adding watches")
	for node, wn := range w.watchedNodes {
		err := w.watchChildren(node, wn)
		if err != nil {
			return err
		}
	}

	return nil
}

func (w *Watcher) notifyDisconnected() {
	for _, wn := range w.watchedNodes {
		select {
		case wn.disconnected <- true:
		default:
		}
	}
}

func (w *Watcher) cancelWatches() {
	w.hooksLock.Lock()
	defer w.hooksLock.Unlock()

	w.notifyDisconnected()

	for _, wn := range w.watchedNodes {
		wn.cancel <- true
	}
}

func (w *Watcher) SetFlapThreshold(max uint, duration time.Duration) chan bool {
	w.flapLock.Lock()
	defer w.flapLock.Unlock()

	w.flapMax = max
	w.flapDuration = duration
	w.flapNotify = make(chan bool)
	return w.flapNotify
}

// Update that we flapped, and check if we exceeded our threshold.
func (w *Watcher) isFlapping() bool {
	w.flapLock.Lock()
	defer w.flapLock.Unlock()

	if w.flapNotify == nil {
		return false
	}

	now := time.Now()

	var newFlaps []time.Time
	for _, flap := range w.flaps {
		if now.Sub(flap) < w.flapDuration {
			newFlaps = append(newFlaps, flap)
		}
	}
	newFlaps = append(newFlaps, now)
	w.flaps = newFlaps
	flapCount := uint(len(newFlaps))

	log.Printf("sequins ZK flap check: flaps=%d flapMax=%d flapDuration=%v\n", flapCount, w.flapMax, w.flapDuration)
	return flapCount > w.flapMax
}

// run runs the main loop. On any errors, it resets the connection.
func (w *Watcher) run() {
	first := true

Reconnect:
	for {
		if !first {
			if w.isFlapping() {
				w.lock.Lock()
				defer w.lock.Unlock()
				log.Println("sequins ZK flapping, shutting down watcher")
				w.flapNotify <- true
				w.shutdown = nil
				return
			}

			// Wait before trying to reconnect again.
			// Let's wait longer than the ZK client.
			wait := time.NewTimer(w.sessionTimeout * 2)
			select {
			case <-w.shutdown:
				break Reconnect
			case <-wait.C:
			}

			err := w.reconnect()
			if err != nil && w.conn.State() == zk.StateDisconnected {
				log.Println("sequins ZK error reconnecting to zookeeper:", err)
				continue Reconnect
			}
		} else {
			first = false
		}

		select {
		case <-w.shutdown:
			break Reconnect
		case err := <-w.errs:
			log.Println("sequins ZK disconnecting from zookeeper because of error:", err)
			w.cancelWatches()
			continue Reconnect
		}
	}

	w.cancelWatches()
}

func (w *Watcher) CreateIDAssignmentLock() *zk.Lock {
	node := path.Join(w.prefix, "id_assignment_lock")

	w.lock.RLock()
	defer w.lock.RUnlock()

	return zk.NewLock(w.conn, node, zk.WorldACL(zk.PermAll))
}

// CreateEphemeral creates an ephemeral node on the zookeeper cluster. Any
// needed parent nodes are also created, as permanent nodes. The ephemeral is
// then recreated any time the Watcher reconnects.
func (w *Watcher) CreateEphemeral(node string) {
	w.lock.RLock()
	defer w.lock.RUnlock()

	w.hooksLock.Lock()
	defer w.hooksLock.Unlock()

	node = path.Join(w.prefix, node)
	w.ephemeralNodes[node] = true
	err := w.createEphemeral(node)
	// It's fine if we're currently reconnecting to zookeeper, since `runHooks`
	// will create the node for us.
	if err != nil && err != zk.ErrClosing {
		sendErr("creating new ephmeral node", w.errs, err, node, "")
	}
}

// Must be called with `w.lock` locked (either for read or write).
func (w *Watcher) createEphemeral(node string) error {
	// Retry a few times, in case the node is removed in between the two following
	// steps.
	for i := 0; i < maxCreateRetries; i++ {
		_, err := w.conn.Create(node, []byte{}, zk.FlagEphemeral, defaultZkACL)
		if err == nil {
			return nil
		} else if err != zk.ErrNoNode && err != zk.ErrNodeExists {
			return err
		}

		// Create the parent nodes.
		parent, _ := path.Split(node)
		err = w.createAll(parent)
		if err != nil {
			return fmt.Errorf("create %s: %s", node, err)
		}
	}

	return fmt.Errorf("failed to create ephemeral znode %s after %d retries", node, maxCreateRetries)
}

// RemoveEphemeral removes the given ephemeral node from the zookeeper cluster.
// The node is then no longer recreated when the Watcher reconnects.
func (w *Watcher) RemoveEphemeral(node string) {
	w.lock.RLock()
	defer w.lock.RUnlock()

	w.hooksLock.Lock()
	defer w.hooksLock.Unlock()

	node = path.Join(w.prefix, node)
	if err := w.conn.Delete(node, -1); err != nil {
		log.Printf("sequins ZK failed to remove ephemeral znode %s", node)
	}
	delete(w.ephemeralNodes, node)
}

// WatchChildren sets up a watch on the given node, and returns two channels.
// The first is updated whenever the list of children for the node changes; the
// second, whenever the cluster is disconnected. The watch persists through
// reconnects. Before the watch is set, WatchChildren creates the node and any
// parents.
func (w *Watcher) WatchChildren(node string) (chan []string, chan bool) {
	w.lock.RLock()
	defer w.lock.RUnlock()

	w.hooksLock.Lock()
	defer w.hooksLock.Unlock()

	node = path.Join(w.prefix, node)
	updates := make(chan []string)
	disconnected := make(chan bool)
	cancel := make(chan bool)

	wn := watchedNode{updates: updates, disconnected: disconnected, cancel: cancel}
	w.watchedNodes[node] = wn
	err := w.watchChildren(node, wn)
	// It's fine if we're currently reconnecting to zookeeper, since `runHooks`
	// will set up the watch for us.
	if err != nil && err != zk.ErrClosing {
		sendErr("adding watch", w.errs, err, node, "")
		go func() {
			<-cancel
		}()
	}

	return updates, disconnected
}

// Must be called with `w.lock` locked (either for read or write).
func (w *Watcher) watchChildren(node string, wn watchedNode) error {
	children, _, events, err := w.childrenW(node)
	if err != nil {
		return err
	}

	go func() {
		// Use current timestamp in nanoseconds as the goroutine id for logging purpose
		id := time.Now().Nanosecond()
		sessionID := w.conn.SessionID()
		// Normally, a watchChildren loop closes just so it can be reestablished
		// once we're reconnected to zookeeper. In that case wn.cancel just gets an
		// update, rather than being closed. If wn.cancel is closed, then
		// reconnecting gets set to false below, and we also close wn.updates and
		// wn.disconnected on our way out.
		reconnecting := true
		defer func() {
			if !reconnecting {
				close(wn.updates)
				close(wn.disconnected)
			}
		}()

		for {
			select {
			case reconnecting = <-wn.cancel:
				return
			case wn.updates <- children:
			}

			select {
			case reconnecting = <-wn.cancel:
				return
			case ev := <-events:
				if ev.Err != nil {
					where := fmt.Sprintf("checking for watch results in goroutine %d with zk session %d",
						id, sessionID)
					sendErr(where, w.errs, ev.Err, ev.Path, ev.Server)
					<-wn.cancel
					return
				}
			}

			w.lock.RLock()
			children, _, events, err = w.childrenW(node)
			w.lock.RUnlock()

			if err != nil {
				where := fmt.Sprintf("re-adding watch in goroutine %d with zk session %d",
					id, w.conn.SessionID())
				sendErr(where, w.errs, err, node, "")
				reconnecting = <-wn.cancel
				return
			}
		}
	}()

	return nil
}

func (w *Watcher) childrenW(node string) (children []string, stat *zk.Stat, events <-chan zk.Event, err error) {
	// Retry a few times, in case the node is removed in between the two following
	// steps.
	for i := 0; i < maxCreateRetries; i++ {
		children, stat, events, err = w.conn.ChildrenW(node)
		if err != zk.ErrNoNode {
			return
		}

		// Create the node so we can watch it.
		err = w.createAll(node)
		if err != nil {
			err = fmt.Errorf("create %s: %s", node, err)
			return
		}
	}

	err = fmt.Errorf("failed to watch children on %s after %d retries", node, maxCreateRetries)
	return
}

// RemoveWatch removes a watch previously set by WatchChildren.
func (w *Watcher) RemoveWatch(node string) {
	w.hooksLock.Lock()
	defer w.hooksLock.Unlock()

	node = path.Join(w.prefix, node)
	if wn, ok := w.watchedNodes[node]; ok {
		delete(w.watchedNodes, node)
		close(wn.cancel)
		log.Printf("sequins ZK removing watch on znode %s", node)
	}
}

func (w *Watcher) createAll(node string) error {
	base, _ := path.Split(path.Clean(node))
	if base != "" && base != "/" {
		err := w.createAll(base)
		if err != nil {
			return err
		}
	}

	_, err := w.conn.Create(path.Clean(node), []byte{}, 0, defaultZkACL)
	if err != nil && err != zk.ErrNodeExists {
		return err
	}

	return nil
}

// TriggerCleanup walks the prefix and deletes any non-ephemeral, empty
// nodes under it. It ignores any errors encountered.
func (w *Watcher) TriggerCleanup() {
	w.lock.RLock()
	defer w.lock.RUnlock()

	log.Printf("sequins ZK cleaning up znodes in %s", w.prefix)
	w.cleanupTree(w.prefix)
	log.Printf("sequins ZK finished cleaning up znodes in %s", w.prefix)
}

func (w *Watcher) cleanupTree(node string) {
	children, stat, err := w.conn.Children(node)
	if err != nil {
		return
	} else if stat.EphemeralOwner != 0 {
		return
	} else if stat.Ctime > (time.Now().Unix() - 3600) * 1000 {
		// Skip the znodes created within last hour to avoid the race with creating
		// the znode path for new db versions.
		return
	}

	for _, child := range children {
		w.cleanupTree(path.Join(node, child))
	}

	// Do not even attempt to delete if this znode has children
	if len(children) != 0 {
		return
	}

	if err = w.conn.Delete(node, -1); err == nil {
		log.Printf("sequins ZK deleted znode %s", node)
	}
}

func (w *Watcher) Close() {
	w.lock.Lock()
	defer w.lock.Unlock()

	if w.shutdown != nil {
		w.shutdown <- true
	}
	w.conn.Close()
}

// sendErr sends the error over the channel, or discards it if the error is full.
func sendErr(where string, errs chan error, err error, path string, server string) {
	log.Printf("sequins ZK Zookeeper error while %s: err=%q, path=%q, server=%q", where, err, path, server)

	select {
	case errs <- err:
	default:
	}
}


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

package com.dyuproject.protostuff.parser;

import java.nio.ByteBuffer;
import java.util.LinkedHashMap;

/**
 * Base class for fields defined in a {@link Message}.
 *
 * @author David Yu
 * @created Dec 19, 2009
 */
public abstract class Field<T> extends AnnotationContainer implements Comparable<Field<?>>, HasName, HasOptions
{

    public enum Modifier
    {
        OPTIONAL,
        REQUIRED,
        REPEATED;

        public java.lang.String getName()
        {
            return name();
        }
    }

    java.lang.String name, defaultValueConstant;
    int number;
    Modifier modifier;
    boolean packable;
    T defaultValue;
    Message owner;
    final LinkedHashMap<java.lang.String,Object> standardOptions =
        new LinkedHashMap<java.lang.String,Object>();

    final LinkedHashMap<java.lang.String,Object> extraOptions =
            new LinkedHashMap<java.lang.String,Object>();

    public Field()
    {

    }

    public Field(boolean packable)
    {
        this.packable = packable;
    }

    public Proto getProto()
    {
        return owner == null ? null : owner.getProto();
    }

    public LinkedHashMap<java.lang.String,Object> getStandardOptions()
    {
        return standardOptions;
    }

    public LinkedHashMap<java.lang.String,Object> getExtraOptions()
    {
        return extraOptions;
    }

    public LinkedHashMap<java.lang.String,Object> getO()
    {
        return getOptions();
    }

    /**
     * Returns this options
     */
    public LinkedHashMap<java.lang.String,Object> getOptions()
    {
        return extraOptions;
    }

    /**
     * Returns the option defined by the {@code key}.
     */
    @SuppressWarnings("unchecked")
    public <V> V getOption(java.lang.String key)
    {
        return (V)extraOptions.get(key);
    }

    public void putStandardOption(java.lang.String key, Object value)
    {
        putExtraOption(key, value);
        standardOptions.put(key, value);
    }

    public void putExtraOption(java.lang.String key, Object value)
    {
        if(extraOptions.put(key, value) != null)
        {
            final Proto proto;
            final java.lang.String ofOwner;
            if(owner != null)
            {
                proto = owner.getProto();
                ofOwner = " of " + owner.getRelativeName();
            }
            else
            {
                proto = null;
                ofOwner = "";
            }

            throw err("The field " + name + ofOwner +
                    " contains a duplicate option: " + key, proto);
        }
    }

    /**
     * @return the name
     */
    public java.lang.String getName()
    {
        return name;
    }

    public java.lang.String getDefaultValueConstant()
    {
        return defaultValueConstant;
    }

    /**
     * @return the number
     */
    public int getNumber()
    {
        return number;
    }

    /**
     * @return the modifier
     */
    public Modifier getModifier()
    {
        return modifier;
    }

    /**
     * @return the packable
     */
    public boolean isPackable()
    {
        return packable;
    }

    /**
     * @return the defaultValue
     */
    public T getDefaultValue()
    {
        return defaultValue;
    }

    public boolean isRepeated()
    {
        return modifier == Modifier.REPEATED;
    }

    public boolean isRequired()
    {
        return modifier == Modifier.REQUIRED;
    }

    public boolean isOptional()
    {
        return modifier == Modifier.OPTIONAL;
    }

    public boolean isDefaultValueSet()
    {
        return getDefaultValue() != null;
    }

    public boolean isNumberField()
    {
        return Number.class.isAssignableFrom(getClass());
    }

    public boolean isEnumField()
    {
        return EnumField.class.isAssignableFrom(getClass());
    }

    public boolean isMessageField()
    {
        return MessageField.class.isAssignableFrom(getClass());
    }

    public boolean isBytesField()
    {
        return Bytes.class.isAssignableFrom(getClass());
    }

    public boolean isStringField()
    {
        return String.class.isAssignableFrom(getClass());
    }

    public boolean isBoolField()
    {
        return Bool.class.isAssignableFrom(getClass());
    }

    public boolean isDelimited()
    {
        return false;
    }

    public java.lang.String toString()
    {
        return new StringBuilder()
            .append('{')
            .append("type:").append(getClass().getSimpleName())
            .append(',').append("name:").append(name)
            .append(',').append("number:").append(number)
            .append(',').append("modifier:").append(modifier)
            .append(',').append("packable:").append(packable)
            .append(',').append("defaultValue:").append(defaultValue)
            .append('}')
            .toString();
    }

    public int compareTo(Field<?> f)
    {
        if(f.number==number)
        {
            throw err("The field: " + f.name + " cannot have the same number as " +
                    name, owner == null ? null : owner.getProto());
        }

        return f.number < number ? 1 : -1;
    }

    public abstract java.lang.String getJavaType();

    public java.lang.String getDefaultValueAsString()
    {
        return getDefaultValue().toString();
    }

    public Message getOwner()
    {
        return owner;
    }

    static abstract class Number<T> extends Field<T>
    {
        public Number()
        {
            super(true);
        }
    }

    public static class Int32 extends Number<Integer>
    {
        public java.lang.String getJavaType()
        {
            return "int";
        }
    }

    public static class UInt32 extends Number<Integer>
    {
        public java.lang.String getJavaType()
        {
            return "int";
        }
    }

    public static class SInt32 extends Number<Integer>
    {
        public java.lang.String getJavaType()
        {
            return "int";
        }
    }

    public static class Fixed32 extends Number<Integer>
    {
        public java.lang.String getJavaType()
        {
            return "int";
        }
    }

    public static class SFixed32 extends Number<Integer>
    {
        public java.lang.String getJavaType()
        {
            return "int";
        }
    }

    public static class Int64 extends Number<Long>
    {
        public java.lang.String getJavaType()
        {
            return "long";
        }
    }

    public static class UInt64 extends Number<Long>
    {
        public java.lang.String getJavaType()
        {
            return "long";
        }
    }

    public static class SInt64 extends Number<Long>
    {
        public java.lang.String getJavaType()
        {
            return "long";
        }
    }

    public static class Fixed64 extends Number<Long>
    {
        public java.lang.String getJavaType()
        {
            return "long";
        }
    }

    public static class SFixed64 extends Number<Long>
    {
        public java.lang.String getJavaType()
        {
            return "long";
        }
    }

    public static class Float extends Number<java.lang.Float>
    {
        public java.lang.String getJavaType()
        {
            return "float";
        }
    }

    public static class Double extends Number<java.lang.Double>
    {
        public java.lang.String getJavaType()
        {
            return "double";
        }
    }

    public static class Bool extends Field<Boolean>
    {
        public Bool()
        {
            super(true);
        }
        public java.lang.String getJavaType()
        {
            return "boolean";
        }
    }

    public static class String extends Field<java.lang.String>
    {
        public String()
        {
            super(false);
        }
        public java.lang.String getJavaType()
        {
            return "String";
        }
        public java.lang.String getDefaultValueAsString()
        {
            return TextFormat.escapeText(getDefaultValue());
        }
        public boolean isDelimited()
        {
            return true;
        }
    }

    public static class Bytes extends Field<byte[]>
    {
        public Bytes()
        {
            super(false);
        }
        public java.lang.String getJavaType()
        {
            return "ByteString";
        }
        public java.lang.String getDefaultValueAsString()
        {
            return TextFormat.escapeBytes(ByteBuffer.wrap(getDefaultValue())).toString();
        }
        public boolean isDelimited()
        {
            return true;
        }
    }

    public static class Reference extends Field<Object>
    {
        java.lang.String refName, packageName;
        HasFields hasFields;

        public Reference(java.lang.String packageName, java.lang.String refName,
                HasFields hasFields)
        {
            this.packageName = packageName;
            this.refName = refName;
            this.hasFields = hasFields;
        }

        public java.lang.String getRefName()
        {
            return refName;
        }

        public java.lang.String getPackageName()
        {
            return packageName;
        }

        public java.lang.String getJavaType()
        {
            return refName;
        }
    }

}


text:
define([
  'jquery',
  'underscore',
  'backbone',
  'text!templates/message/messageListTemplate.html'
], function($, _, Backbone, messageListTemplate){

  var MessageListView = Backbone.View.extend({
    el: $("#content"),

    render: function(){

      var that = this;
	  //..
      var data = {};
      var compiledTemplate = _.template( messageListTemplate, data );
      $("#content").html(compiledTemplate);
    }

  });

  return MessageListView;

});