text:
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.DotNet.Tools.Test.Utilities;
using Xunit;
using FluentAssertions;
using Microsoft.DotNet.TestFramework;
using Microsoft.DotNet.Cli.Utils;
using System.IO;
using System;
using System.Runtime.CompilerServices;
using System.Xml;

namespace Microsoft.DotNet.Cli.Test.Tests
{
    public class GivenDotnettestBuildsAndRunsTestfromCsproj : TestBase
    {
        [Fact]
        public void MSTestSingleTFM()
        {
            var testProjectDirectory = this.CopyAndRestoreVSTestDotNetCoreTestApp("3");

            // Call test
            CommandResult result = new DotnetTestCommand()
                                        .WithWorkingDirectory(testProjectDirectory)
                                        .ExecuteWithCapturedOutput(TestBase.ConsoleLoggerOutputNormal);

            // Verify
            if (!DotnetUnderTest.IsLocalized())
            {
                result.StdOut.Should().Contain("Total tests: 2. Passed: 1. Failed: 1. Skipped: 0.");
                result.StdOut.Should().Contain("Passed   VSTestPassTest");
                result.StdOut.Should().Contain("Failed   VSTestFailTest");
            }

            result.ExitCode.Should().Be(1);
        }

        [Fact]
        public void ItImplicitlyRestoresAProjectWhenTesting()
        {
            string testAppName = "VSTestCore";
            var testInstance = TestAssets.Get(testAppName)
                            .CreateInstance()
                            .WithSourceFiles();

            var testProjectDirectory = testInstance.Root.FullName;

            CommandResult result = new DotnetTestCommand()
                                        .WithWorkingDirectory(testProjectDirectory)
                                        .ExecuteWithCapturedOutput(TestBase.ConsoleLoggerOutputNormal);

            if (!DotnetUnderTest.IsLocalized())
            {
                result.StdOut.Should().Contain("Total tests: 2. Passed: 1. Failed: 1. Skipped: 0.");
                result.StdOut.Should().Contain("Passed   VSTestPassTest");
                result.StdOut.Should().Contain("Failed   VSTestFailTest");
            }

            result.ExitCode.Should().Be(1);
        }

        [Fact]
        public void ItDoesNotImplicitlyRestoreAProjectWhenTestingWithTheNoRestoreOption()
        {
            string testAppName = "VSTestCore";
            var testInstance = TestAssets.Get(testAppName)
                            .CreateInstance()
                            .WithSourceFiles();

            var testProjectDirectory = testInstance.Root.FullName;

            new DotnetTestCommand()
                .WithWorkingDirectory(testProjectDirectory)
                .ExecuteWithCapturedOutput($"{TestBase.ConsoleLoggerOutputNormal} --no-restore /p:IsTestProject=true")
                .Should().Fail()
                .And.HaveStdOutContaining("project.assets.json");
        }

        [Fact]
        public void ItDoesNotRunTestsIfThereIsNoIsTestProject()
        {
            string testAppName = "VSTestCore";
            var testInstance = TestAssets.Get(testAppName)
                            .CreateInstance()
                            .WithSourceFiles();

            var testProjectDirectory = testInstance.Root.FullName;

            new DotnetTestCommand()
                .WithWorkingDirectory(testProjectDirectory)
                .ExecuteWithCapturedOutput($"{TestBase.ConsoleLoggerOutputNormal} --no-restore")
                .Should().Pass()
                .And.HaveStdOutContaining("Skipping running test for project");
        }

        [Fact]
        public void XunitSingleTFM()
        {
            // Copy XunitCore project in output directory of project dotnet-vstest.Tests
            string testAppName = "XunitCore";
            var testInstance = TestAssets.Get(testAppName)
                            .CreateInstance("4")
                            .WithSourceFiles();

            var testProjectDirectory = testInstance.Root.FullName;

            // Restore project XunitCore
            new RestoreCommand()
                .WithWorkingDirectory(testProjectDirectory)
                .Execute()
                .Should()
                .Pass();

            // Call test
            CommandResult result = new DotnetTestCommand()
                                        .WithWorkingDirectory(testProjectDirectory)
                                        .ExecuteWithCapturedOutput(TestBase.ConsoleLoggerOutputNormal);

            // Verify
            if (!DotnetUnderTest.IsLocalized())
            {
                result.StdOut.Should().Contain("Total tests: 2. Passed: 1. Failed: 1. Skipped: 0.");
                result.StdOut.Should().Contain("Passed   TestNamespace.VSTestXunitTests.VSTestXunitPassTest");
                result.StdOut.Should().Contain("Failed   TestNamespace.VSTestXunitTests.VSTestXunitFailTest");
            }

            result.ExitCode.Should().Be(1);
        }

        [Fact]
        public void GivenAFailingTestItDisplaysFailureDetails()
        {
            var testInstance = TestAssets.Get("XunitCore")
                .CreateInstance()
                .WithSourceFiles();

            var result = new DotnetTestCommand()
                .WithWorkingDirectory(testInstance.Root.FullName)
                .ExecuteWithCapturedOutput();

            result.ExitCode.Should().Be(1);

            if (!DotnetUnderTest.IsLocalized())
            {
                result.StdOut.Should().Contain("Failed   TestNamespace.VSTestXunitTests.VSTestXunitFailTest");
                result.StdOut.Should().Contain("Assert.Equal() Failure");
                result.StdOut.Should().Contain("Total tests: 2. Passed: 1. Failed: 1. Skipped: 0.");
            }
        }

        [Fact]
        public void ItAcceptsMultipleLoggersAsCliArguments()
        {
            // Copy and restore VSTestCore project in output directory of project dotnet-vstest.Tests
            var testProjectDirectory = this.CopyAndRestoreVSTestDotNetCoreTestApp("10");

            string trxLoggerDirectory = Path.Combine(testProjectDirectory, "RD");

            // Delete trxLoggerDirectory if it exist
            if (Directory.Exists(trxLoggerDirectory))
            {
                Directory.Delete(trxLoggerDirectory, true);
            }

            // Call test with logger enable
            CommandResult result = new DotnetTestCommand()
                                       .WithWorkingDirectory(testProjectDirectory)
                                       .ExecuteWithCapturedOutput("--logger \"trx;logfilename=custom.trx\" --logger console;verbosity=normal -- RunConfiguration.ResultsDirectory=" + trxLoggerDirectory);

            // Verify
            if (!DotnetUnderTest.IsLocalized())
            {
                var trxFilePath = Path.Combine(trxLoggerDirectory, "custom.trx");
                Assert.True(File.Exists(trxFilePath));
                result.StdOut.Should().Contain(trxFilePath);
                result.StdOut.Should().Contain("Passed   VSTestPassTest");
                result.StdOut.Should().Contain("Failed   VSTestFailTest");
            }

            // Cleanup trxLoggerDirectory if it exist
            if (Directory.Exists(trxLoggerDirectory))
            {
                Directory.Delete(trxLoggerDirectory, true);
            }
        }

        [Fact]
        public void TestWillNotBuildTheProjectIfNoBuildArgsIsGiven()
        {
            // Copy and restore VSTestCore project in output directory of project dotnet-vstest.Tests
            var testProjectDirectory = this.CopyAndRestoreVSTestDotNetCoreTestApp("5");
            string configuration = Environment.GetEnvironmentVariable("CONFIGURATION") ?? "Debug";
            string expectedError = Path.Combine(testProjectDirectory, "bin",
                                   configuration, "netcoreapp3.0", "VSTestCore.dll");
            expectedError = "The test source file " + "\"" + expectedError + "\"" + " provided was not found.";

            // Call test
            CommandResult result = new DotnetTestCommand()
                                       .WithWorkingDirectory(testProjectDirectory)
                                       .ExecuteWithCapturedOutput("--no-build -v:m");

            // Verify
            if (!DotnetUnderTest.IsLocalized())
            {
                result.StdOut.Should().NotContain("Restore");
                result.StdErr.Should().Contain(expectedError);
            }

            result.ExitCode.Should().Be(1);
        }

        [Fact]
        public void TestWillCreateTrxLoggerInTheSpecifiedResultsDirectoryBySwitch()
        {
            // Copy and restore VSTestCore project in output directory of project dotnet-vstest.Tests
            var testProjectDirectory = this.CopyAndRestoreVSTestDotNetCoreTestApp("6");

            string trxLoggerDirectory = Path.Combine(testProjectDirectory, "TR", "x.y");

            // Delete trxLoggerDirectory if it exist
            if (Directory.Exists(trxLoggerDirectory))
            {
                Directory.Delete(trxLoggerDirectory, true);
            }

            // Call test with trx logger enabled and results directory explicitly specified.
            CommandResult result = new DotnetTestCommand()
                                       .WithWorkingDirectory(testProjectDirectory)
                                       .ExecuteWithCapturedOutput("--logger trx -r \"" + trxLoggerDirectory + "\"");

            // Verify
            String[] trxFiles = Directory.GetFiles(trxLoggerDirectory, "*.trx");
            Assert.Single(trxFiles);
            result.StdOut.Should().Contain(trxFiles[0]);

            // Cleanup trxLoggerDirectory if it exist
            if(Directory.Exists(trxLoggerDirectory))
            {
                Directory.Delete(trxLoggerDirectory, true);
            }
        }

        [Fact]
        public void ItCreatesTrxReportInTheSpecifiedResultsDirectoryByArgs()
        {
            // Copy and restore VSTestCore project in output directory of project dotnet-vstest.Tests
            var testProjectDirectory = this.CopyAndRestoreVSTestDotNetCoreTestApp("7");

            string trxLoggerDirectory = Path.Combine(testProjectDirectory, "RD");

            // Delete trxLoggerDirectory if it exist
            if (Directory.Exists(trxLoggerDirectory))
            {
                Directory.Delete(trxLoggerDirectory, true);
            }

            // Call test with logger enable
            CommandResult result = new DotnetTestCommand()
                                       .WithWorkingDirectory(testProjectDirectory)
                                       .ExecuteWithCapturedOutput("--logger \"trx;logfilename=custom.trx\" -- RunConfiguration.ResultsDirectory=" + trxLoggerDirectory);

            // Verify
            var trxFilePath = Path.Combine(trxLoggerDirectory, "custom.trx");
            Assert.True(File.Exists(trxFilePath));
            result.StdOut.Should().Contain(trxFilePath);

            // Cleanup trxLoggerDirectory if it exist
            if (Directory.Exists(trxLoggerDirectory))
            {
                Directory.Delete(trxLoggerDirectory, true);
            }
        }

        [Fact]
        public void ItBuildsAndTestsAppWhenRestoringToSpecificDirectory()
        {
            // Creating folder with name short name "RestoreTest" to avoid PathTooLongException
            var rootPath = TestAssets.Get("VSTestCore").CreateInstance("8").WithSourceFiles().Root.FullName;

            // Moving pkgs folder on top to avoid PathTooLongException
            string dir = @"..\..\..\..\pkgs";
            string fullPath = Path.GetFullPath(Path.Combine(rootPath, dir));

            string args = $"--packages \"{dir}\"";
            new RestoreCommand()
                .WithWorkingDirectory(rootPath)
                .Execute(args)
                .Should()
                .Pass();

            new BuildCommand()
                .WithWorkingDirectory(rootPath)
                .ExecuteWithCapturedOutput("--no-restore")
                .Should()
                .Pass()
                .And.NotHaveStdErr();

            CommandResult result = new DotnetTestCommand()
                                        .WithWorkingDirectory(rootPath)
                                        .ExecuteWithCapturedOutput($"{TestBase.ConsoleLoggerOutputNormal} --no-restore");

            if (!DotnetUnderTest.IsLocalized())
            {
                result.StdOut.Should().Contain("Total tests: 2. Passed: 1. Failed: 1. Skipped: 0.");
                result.StdOut.Should().Contain("Passed   VSTestPassTest");
                result.StdOut.Should().Contain("Failed   VSTestFailTest");
            }

            result.ExitCode.Should().Be(1);
        }

        [Fact]
        public void ItUsesVerbosityPassedToDefineVerbosityOfConsoleLoggerOfTheTests()
        {
            // Copy and restore VSTestCore project in output directory of project dotnet-vstest.Tests
            var testProjectDirectory = this.CopyAndRestoreVSTestDotNetCoreTestApp("9");

            // Call test
            CommandResult result = new DotnetTestCommand()
                                        .WithWorkingDirectory(testProjectDirectory)
                                        .ExecuteWithCapturedOutput("-v q");

            // Verify
            if (!DotnetUnderTest.IsLocalized())
            {
                result.StdOut.Should().Contain("Total tests: 2. Passed: 1. Failed: 1. Skipped: 0.");
                result.StdOut.Should().NotContain("Passed   TestNamespace.VSTestTests.VSTestPassTest");
                result.StdOut.Should().NotContain("Failed   TestNamespace.VSTestTests.VSTestFailTest");
            }

            result.ExitCode.Should().Be(1);
        }

        [Fact]
        public void ItTestsWithTheSpecifiedRuntimeOption()
        {
            var testInstance = TestAssets.Get("XunitCore")
                            .CreateInstance()
                            .WithSourceFiles();

            var rootPath = testInstance.Root.FullName;
            var rid = DotnetLegacyRuntimeIdentifiers.InferLegacyRestoreRuntimeIdentifier();

            new BuildCommand()
                .WithWorkingDirectory(rootPath)
                .ExecuteWithCapturedOutput($"--runtime {rid}")
                .Should()
                .Pass()
                .And.NotHaveStdErr();

            var result = new DotnetTestCommand()
                .WithWorkingDirectory(rootPath)
                .ExecuteWithCapturedOutput($"{TestBase.ConsoleLoggerOutputNormal} --no-build --runtime {rid}");

            result
                .Should()
                .NotHaveStdErrContaining("MSB1001")
                .And
                .HaveStdOutContaining(rid);

            if (!DotnetUnderTest.IsLocalized())
            {
                result
                    .Should()
                    .HaveStdOutContaining("Total tests: 2. Passed: 1. Failed: 1. Skipped: 0.")
                    .And
                    .HaveStdOutContaining("Passed   TestNamespace.VSTestXunitTests.VSTestXunitPassTest")
                    .And
                    .HaveStdOutContaining("Failed   TestNamespace.VSTestXunitTests.VSTestXunitFailTest");
            }

            result.ExitCode.Should().Be(1);
        }

        [WindowsOnlyFact]
        public void ItCreatesCoverageFileWhenCodeCoverageEnabledByRunsettings()
        {
            var testProjectDirectory = this.CopyAndRestoreVSTestDotNetCoreTestApp("11");

            string resultsDirectory = Path.Combine(testProjectDirectory, "RD");

            // Delete resultsDirectory if it exist
            if (Directory.Exists(resultsDirectory))
            {
                Directory.Delete(resultsDirectory, true);
            }

            var settingsPath =Path.Combine(AppContext.BaseDirectory, "CollectCodeCoverage.runsettings");

            // Call test
            CommandResult result = new DotnetTestCommand()
                                        .WithWorkingDirectory(testProjectDirectory)
                                        .ExecuteWithCapturedOutput(
                                            "--settings " + settingsPath
                                            + " --results-directory " + resultsDirectory);

            // Verify test results
            if (!DotnetUnderTest.IsLocalized())
            {
                result.StdOut.Should().Contain("Total tests: 2. Passed: 1. Failed: 1. Skipped: 0.");
            }

            // Verify coverage file.
            DirectoryInfo d = new DirectoryInfo(resultsDirectory);
            FileInfo[] coverageFileInfos = d.GetFiles("*.coverage", SearchOption.AllDirectories);
            Assert.Single(coverageFileInfos);

            result.ExitCode.Should().Be(1);
        }

        [WindowsOnlyFact]
        public void ItCreatesCoverageFileInResultsDirectory()
        {
            var testProjectDirectory = this.CopyAndRestoreVSTestDotNetCoreTestApp("12");

            string resultsDirectory = Path.Combine(testProjectDirectory, "RD");

            // Delete resultsDirectory if it exist
            if (Directory.Exists(resultsDirectory))
            {
                Directory.Delete(resultsDirectory, true);
            }

            // Call test
            CommandResult result = new DotnetTestCommand()
                                        .WithWorkingDirectory(testProjectDirectory)
                                        .ExecuteWithCapturedOutput(
                                            "--collect \"Code Coverage\" "
                                            + "--results-directory " + resultsDirectory);

            // Verify test results
            if (!DotnetUnderTest.IsLocalized())
            {
                result.StdOut.Should().Contain("Total tests: 2. Passed: 1. Failed: 1. Skipped: 0.");
            }

            // Verify coverage file.
            DirectoryInfo d = new DirectoryInfo(resultsDirectory);
            FileInfo[] coverageFileInfos = d.GetFiles("*.coverage", SearchOption.AllDirectories);
            Assert.Single(coverageFileInfos);

            result.ExitCode.Should().Be(1);
        }

        [UnixOnlyFact]
        public void ItShouldShowWarningMessageOnCollectCodeCoverage()
        {
            var testProjectDirectory = this.CopyAndRestoreVSTestDotNetCoreTestApp("13");

            // Call test
            CommandResult result = new DotnetTestCommand()
                                        .WithWorkingDirectory(testProjectDirectory)
                                        .ExecuteWithCapturedOutput(
                                            "--collect \"Code Coverage\" "
                                            + "--filter VSTestPassTest");

            // Verify test results
            if (!DotnetUnderTest.IsLocalized())
            {
                result.StdOut.Should().Contain("No code coverage data available. Code coverage is currently supported only on Windows.");
                result.StdOut.Should().Contain("Total tests: 1. Passed: 1. Failed: 0. Skipped: 0.");
                result.StdOut.Should().Contain("Test Run Successful.");
            }

            result.ExitCode.Should().Be(0);
        }

        private string CopyAndRestoreVSTestDotNetCoreTestApp([CallerMemberName] string callingMethod = "")
        {
            // Copy VSTestCore project in output directory of project dotnet-vstest.Tests
            string testAppName = "VSTestCore";
            var testInstance = TestAssets.Get(testAppName)
                            .CreateInstance(callingMethod)
                            .WithSourceFiles();

            var testProjectDirectory = testInstance.Root.FullName;

            // Restore project VSTestCore
            new RestoreCommand()
                .WithWorkingDirectory(testProjectDirectory)
                .Execute()
                .Should()
                .Pass();

            return testProjectDirectory;
        }
    }
}


text:
module Intel.SGX.Types where

import Text.Printf
import qualified Data.ByteString.Lazy as L
import Data.Word (Word64, Word32, Word16, Word8)

data SECS = SECS {
  secsSize                    :: Word64        -- Size of enclave in bytes; must be power of 2
  , secsBaseAddr              :: Word64        -- Enclave Base Linear Address must be naturally aligned to size
  , secsSSAFrameSize          :: Word32        -- Size of one SSA frame in pages (including XSAVE, pad, GPR, and conditionally MISC).
  , secsMiscSelect            :: MiscSelect    -- See MiscSecelct data type
  , secsReserved_byte24_47    :: L.ByteString  -- Reserved bytes. Set to zero
  , secsAttr                  :: Attributes    -- See Attributes data type
  , secsMrEnclave             :: L.ByteString  -- 256-bit SHA256 hash
  , secsReserved_byte96_127   :: L.ByteString  -- Reserved bytes. Set to zero
  , secsMrSigner              :: L.ByteString  -- 256-bit SHA256 hash of signer public key *after* enclave sig was verified
  , secsReserved_byte160_255  :: L.ByteString  -- Reserved bytes. Set to zero
  , secsISVProdId             :: Word16        -- Product ID of enclave
  , secsISVSVN                :: Word16        -- Security version number (SVN) of the enclave
  , secsReserved_byte260_4095 :: L.ByteString  -- 3836 bytes of wasted space
  }

data MiscSelect = MiscSelect {
  miscExInfo             :: Bool   -- Report information about page fault and general protection exception that occurred inside an enclave
  , miscReserved_bit1_32 :: Word32 -- Wasted space
  } deriving (Eq)

data Attributes = Attributes {
  attrInit                :: Bool -- if the enclave has been initialized by EINIT
  , attrDebug             :: Bool -- If 1, the enclave permit debugger to read and write enclave data
  , attrMode64Bit         :: Bool -- Enclave runs in 64-bit mode
  , attrReserved_bit3     :: Bool -- Must be zero
  , attrProvisionKey      :: Bool -- Provisioning Key is available from EGETKEY
  , attrEinitTokenKey     :: Bool -- EINIT token key is available from EGETKEY
  , attrReserved_bit6_63  :: L.ByteString -- Reserved. Set to zero.
  , attrXFRM              :: XFRM -- See XFRM data type
  }deriving(Eq, Show)

data XFRM = XFRM {
  xfrmEnabled  :: Bool
  , xfrmXCR0  :: Word64    -- Valid value of XCR0
  , xfrmHasXSave :: Bool -- Does the CPU has XSAVE instruction
  } deriving(Eq, Show)

data PageInfo = PageInfo {
  pgEnclaveLinAddr  :: Word64        -- Enclave linear address.
  , pgSourceAddr    :: Word64        -- Effective address of the page where contents are located.
  , pgSecInfo       :: Word64        -- Effective address of the SECINFO or PCMD
  , pgSecs          :: Word64        -- Effective address of EPC slot that currently contains the SECS
  }

data SecInfo = SecInfo {
  siFlags       :: SecInfoFlags
  }

data SecInfoFlags = SecInfoFlags {
  sifIsRead               :: Bool
  , sifIsWrite            :: Bool
  , sifIsExecute          :: Bool
  , sifIsPending          :: Bool
  , sifIsModified         :: Bool
  , sifHasPermRestriction :: Bool
  , sifReserved_bit6_7    :: Word8
  , sifPageType           :: PageType
  , sifReserved_bit16_64  :: Word64
  }

data PageType = PT_SECS
              | PT_TCS
              | PT_REG
              | PT_VA
              | PT_TRIM
              deriving (Show, Eq)

instance Enum PageType where
  toEnum 0 = PT_SECS
  toEnum 1 = PT_TCS
  toEnum 2 = PT_REG
  toEnum 3 = PT_VA
  toEnum 4 = PT_TRIM
  toEnum _ = undefined

  fromEnum PT_SECS = 0
  fromEnum PT_TCS  = 1
  fromEnum PT_REG  = 2
  fromEnum PT_VA   = 3
  fromEnum PT_TRIM = 4

data PCMD = PCMD {
  pcmdSecInfo               :: SecInfo
  , pcmdEnclaveId           :: Word64
  , pcmdReserved_byte72_111 :: L.ByteString
  , pcmdMac                 :: L.ByteString   -- 16-Bytes
  }

data SigStruct = SigStruct{
  ssHeader1                :: SigStructHeader      -- 16 bytes. Signed
  , ssVendor               :: SigStructVendor      -- 4  bytes. Signed
  , ssBuildDate            :: SigStructDate        -- 4  bytes. Signed
  , ssHeader2              :: SigStructHeader      -- 16 bytes. Signed
  , ssSwDefined            :: Word32               -- 4  bytes. Signed
  , ssReserved_byte44_127  :: L.ByteString         -- 84 bytes of zero. Signed
  , ssModulus              :: Integer              -- 384 bytes. Not signed
  , ssExponent             :: Word32               -- 4  bytes. Not signed
  , ssSignature            :: Integer              -- 384 bytes. Not signed
  , ssMiscSelect           :: MiscSelect           -- 4  bytes. Signed
  , ssMiscMask             :: MiscSelect           -- 4  bytes. Signed
  , ssReserved_byte908_927 :: L.ByteString         -- 20 bytes of zero. Signed
  , ssAttributes           :: Attributes           -- 16 bytes. Signed
  , ssAttributesMask       :: Attributes           -- 16 bytes. Signed
  , ssEnclaveHash          :: L.ByteString         -- 32 bytes of SHA256 of enclave. Signed
  , ssReserved_byte992_1023 :: L.ByteString        -- 32 bytes of zero. Signed
  , ssIsvProdId           :: Word16                -- 2  bytes. Signed
  , ssIsvSvn              :: Word16                -- 2  bytes. Signed
  , ssReserved_byte1028_1039 :: L.ByteString       -- 12 bytes of zero. Not signed
  , ssQ1                     :: Integer            -- 384 bytes of Q1
  , ssQ2                     :: Integer            -- 284 bytes of Q2
  }

data EInitToken = EInitToken {
  eitDebug                   :: Bool               -- 4 Bytes. MACed
  , eitReserved_byte4_47     :: L.ByteString       -- 44 Bytes of Zero. MACed
  , eitAttributes            :: Attributes         -- 16 Bytes. MACed
  , eitMrEnclave             :: L.ByteString       -- 32 Bytes. MACed
  , eitReserved_byte96_127   :: L.ByteString       -- 32 Bytes of Zero. MACed
  , eitMtSigner              :: L.ByteString       -- 32 Bytes. MACed
  , eitReserved_byte160_191  :: L.ByteString       -- 32 Bytes. MACed.
  , eitCpuSvnLe              :: CPUSVN             -- 16 Bytes. Not MACed
  , eitIsvProdIdLe           :: Word16             -- 2  Bytes. Not MACed
  , eitIsvSvnLe              :: Word16             -- 2  Bytes. Not MACed
  , eitReserved_byte212_235  :: L.ByteString       -- Reserved. Not MACed
  , eitMaskedMiscSelectLe    :: Word32             -- Returned by the Launch Enclave
  , eitMaskedAttributes      :: Attributes         -- Returned by the Launch Enclave
  , eitKeyId                 :: L.ByteString       -- 32-bytes of KeyID protection. Not MACed
  , eitMAC                   :: L.ByteString       -- 16 bytes of final MAC.
  }

data SigStructHeader = SSHeader{
  ssHeaderValue :: Integer
  }

ssHeaderVal1 :: SigStructHeader
ssHeaderVal1 = SSHeader 0x06000000E10000000000010000000000

ssHeaderVal2 :: SigStructHeader
ssHeaderVal2 = SSHeader 0x01010000600000006000000001000000

data SigStructVendor = SSVendorIntel
                     | SSVendorOther
                     deriving (Show, Eq)

instance Enum SigStructVendor where
  toEnum 0x8086 = SSVendorIntel
  toEnum 0x0    = SSVendorOther
  toEnum _      = undefined

  fromEnum SSVendorIntel = 0x8086
  fromEnum SSVendorOther = 0x0

data SigStructDate = SSDate {
  ssYear      :: Year
  ,  ssMonth  :: Month
  ,  ssDay    :: Day
  } deriving (Show, Eq)

data Year = Year {
  y1 :: Word8
  , y2 :: Word8
  , y3 :: Word8
  , y4 :: Word8
  } deriving (Eq)

instance Show Year where
  show (Year a1 a2 a3 a4) =
    printf "%.1x%.1x%.1x%.1x" a1 a2 a3 a4

data Month = Jan | Feb | Mar | Apr
           | May | Jun | Jul | Aug
           | Sep | Oct | Nov | Dec
           deriving( Show, Eq)

data Day = Day Word8 deriving (Eq)

instance Enum Day where
  succ (Day x) = Day $ if x == 31
                       then 0
                       else succ x
  pred (Day x) = Day $ if x == 0
                       then 31
                       else pred x
  toEnum  = Day . fromIntegral
  fromEnum (Day x) = fromIntegral x

instance Show Day where
  show (Day d) = show d

data TCS = TCS {
  tcsReserved_byte0_7        :: Word64
  , tcsFlags                 :: TCSFlags
  , tcsOSSA                  :: Word64
  , tcsCSSA                  :: Word32
  , tcsNSSA                  :: Word32
  , tcsOentry                :: Word64
  , tcsAep                   :: Word64
  , tcsOFSBasSgx             :: Word64
  , tcsOGSBasSgx             :: Word64
  , tcsFSLimit               :: Word32
  , tcsGSLimit               :: Word32
  , tcsReserved_byte72_4095  :: L.ByteString
  }

data TCSFlags = TCSFlags {
  tcsFlagsDebugOptIn          :: Bool
  , tcsFlagsReserved_bit1_63 :: Word64
  }

data SSAFrame = SSAFrame {
  ssaXsave    :: L.ByteString
  , ssaPad    :: L.ByteString
  , ssaMisc   :: L.ByteString
  , ssaGprSgx :: L.ByteString
  }

data GPRSGX = GPRSGX {
  gprRAX :: Word64
  , gprRCX    :: Word64
  , gprRDX    :: Word64
  , gprRBX    :: Word64
  , gprRSP    :: Word64
  , gprRBP    :: Word64
  , gprRSI    :: Word64
  , gprRDI    :: Word64
  , gprR8     :: Word64
  , gprR9     :: Word64
  , gprR10    :: Word64
  , gprR11    :: Word64
  , gprR12    :: Word64
  , gprR13    :: Word64
  , gprR14    :: Word64
  , gprR15    :: Word64
  , gprRFLAGS :: Word64
  , gprRIP    :: Word64
  , gprURSP   :: Word64
  , gprURBP   :: Word64
  , gprExitInfo :: ExitInfo
  , gprReserved_byte164_167 :: Word32
  , gprFsBase :: Word64
  , gprGsBase :: Word64
  }

data ExitInfo = ExitInfo {
  eiVector              :: ExcptVector
  , eiType              :: ExitInfoType
  , eiReserved_bit11_30 :: Word32
  , eiValid             :: Bool
  }

data ExitInfoType = ExitTypeHwExcept |
                    ExitTypeSwExcept

instance Enum ExitInfoType where
  fromEnum ExitTypeHwExcept = 0x3
  fromEnum ExitTypeSwExcept = 0x6

  toEnum 0x3 = ExitTypeHwExcept
  toEnum 0x6 = ExitTypeSwExcept
  toEnum _   = undefined

data ExcptVector = DividerExcpt
                 | DebugExcpt
                 | BreakpointExcpt
                 | BoundRangeExceedExcpt
                 | InvalidOpCodeExcpt
                 | GeneralProtectionExcpt
                 | PageFaultExcpt
                 | FPUErrorExcept
                 | AlignmentCheckExcept
                 | SIMDException
                 deriving (Show, Eq)

instance Enum ExcptVector where
  fromEnum DividerExcpt           = 0
  fromEnum DebugExcpt             = 1
  fromEnum BreakpointExcpt        = 3
  fromEnum BoundRangeExceedExcpt  = 5
  fromEnum InvalidOpCodeExcpt     = 6
  fromEnum GeneralProtectionExcpt = 13
  fromEnum PageFaultExcpt         = 14
  fromEnum FPUErrorExcept         = 16
  fromEnum AlignmentCheckExcept   = 17
  fromEnum SIMDException          = 19

  toEnum 0 = DividerExcpt
  toEnum 1 = DebugExcpt
  toEnum 3 = BreakpointExcpt
  toEnum 5 = BoundRangeExceedExcpt
  toEnum 6 = InvalidOpCodeExcpt
  toEnum 13 = GeneralProtectionExcpt
  toEnum 14 = PageFaultExcpt
  toEnum 16 = FPUErrorExcept
  toEnum 17 = AlignmentCheckExcept
  toEnum 19 = SIMDException
  toEnum _  = undefined

data Report = Report {
  repCpuSvn                 :: CPUSVN         -- 16 Bytes
  , repMiscSelect           :: MiscSelect     -- 4 Bytes
  , repReserved_byte20_47   :: L.ByteString   -- reseved 28 bytes of Zero
  , repAttributes           :: Attributes     -- 16 bytes
  , repMrEnclave            :: L.ByteString   -- 32 bytes
  , repReserved_byte96_127  :: L.ByteString   -- 32 bytes of zero
  , repMrSigner             :: L.ByteString   -- 32 bytes of signger
  , repReserved_byte160_255 :: L.ByteString   -- 32 bytes of zero
  , repIsvProdId            :: Word16         -- 2 bytes
  , repIsvSvn               :: Word16         -- 2 bytes
  , repReserved_byte260_319 :: L.ByteString   -- 60 bytes of zero
  , repReportData           :: L.ByteString   -- 64 bytes of report data
  , repKeyId                :: L.ByteString   -- 32-bytes of key id
  , repMAC                  :: L.ByteString   -- 16-bytes of Mac
  }

data CPUSVN = CPUSVN {
  cpuSvnValue :: L.ByteString
  }

data TargetInfo = TargetInfo {
  tiTargetMrEnclave       :: L.ByteString        -- 32 bytes of MrEnclave
  , tiAttributes          :: Attributes          -- 16 bytes of attributes
  , tiReserved_byte48_51  :: Word32              -- 4 bytes reserved
  , tiMiscSelect          :: MiscSelect          -- 4 bytes of MiscSelect
  , tiReserved_byte56_511 :: L.ByteString        -- Reserved to zero
  }

data KeyRequest = KeyRequest {
  krKeyName               :: KeyName              -- 2 bytes
  , krKeyPolicy           :: KeyPolicy            -- 2 bytes
  , krIsvSvn              :: Word16               -- 2 bytes
  , krReserved_byte6_7    :: Word16               -- 2 bytes
  , krCpuSvn              :: CPUSVN               -- 16 bytes
  , krAttributeMask       :: Attributes           -- 16 bytes
  , krKeyId               :: L.ByteString         -- 32 bytes
  , krMiscMask            :: MiscSelect           -- 4 bytes
  , krReserved_byte76_511 :: L.ByteString         -- 436 bytes of zero
  }

data KeyName = EINIT_TOKEN_KEY
             | PROVISION_KEY
             | PROVISION_SEAL_KEY
             | REPORT_KEY
             | SEAL_KEY
             deriving (Show, Eq)

instance Enum KeyName where
  toEnum 0 = EINIT_TOKEN_KEY
  toEnum 1 = PROVISION_KEY
  toEnum 2 = PROVISION_SEAL_KEY
  toEnum 3 = REPORT_KEY
  toEnum 4 = SEAL_KEY
  toEnum _ = undefined

  fromEnum EINIT_TOKEN_KEY     = 0
  fromEnum PROVISION_KEY       = 1
  fromEnum PROVISION_SEAL_KEY  = 2
  fromEnum REPORT_KEY          = 3
  fromEnum SEAL_KEY            = 4

data KeyPolicy = KeyPolicy {
  kpIsMrEnclave :: Bool
  , kpIsMrSigner :: Bool
  , kpReserved_bit2_15 :: Word16
  }

redpajama_set_name: RedPajamaGithub


text:
package com.wisely.highlight_spring4.ch2.event;

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class DemoListener implements ApplicationListener<DemoEvent> {

	public void onApplicationEvent(DemoEvent event) {

		String msg = event.getMsg();

		System.out.println("ÎÒ(bean-demoListener)½ÓÊܵ½ÁËbean-demoPublisher·¢²¼µÄÏûÏ¢:"
				+ msg);

	}

}


text:
package TeamTwoHTMLEditor.OutlineEditorKit;

import javax.swing.text.*;
import java.awt.*;

public class OutlineDocument extends DefaultStyledDocument {
    public static String TAG_ELEMENT = "tag_element";
    public static String TAG_ROW_START_ELEMENT = "tag_row_start_element";
    public static String TAG_ROW_END_ELEMENT = "tag_row_end_element";

    public static SimpleAttributeSet BRACKET_ATTRIBUTES = new SimpleAttributeSet();
    public static SimpleAttributeSet TAGNAME_ATTRIBUTES = new SimpleAttributeSet();
    public static SimpleAttributeSet ATTRIBUTENAME_ATTRIBUTES = new SimpleAttributeSet();
    public static SimpleAttributeSet ATTRIBUTEVALUE_ATTRIBUTES = new SimpleAttributeSet();
    public static SimpleAttributeSet PLAIN_ATTRIBUTES = new SimpleAttributeSet();
    public static SimpleAttributeSet COMMENT_ATTRIBUTES = new SimpleAttributeSet();

    static {
        StyleConstants.setBold(TAGNAME_ATTRIBUTES, true);
        StyleConstants.setForeground(TAGNAME_ATTRIBUTES, Color.BLUE);

        StyleConstants.setBold(ATTRIBUTENAME_ATTRIBUTES, true);

        StyleConstants.setItalic(ATTRIBUTEVALUE_ATTRIBUTES, true);
        StyleConstants.setForeground(ATTRIBUTEVALUE_ATTRIBUTES, Color.GREEN.darker());

        StyleConstants.setFontSize(PLAIN_ATTRIBUTES, StyleConstants.getFontSize(PLAIN_ATTRIBUTES) - 1);
        StyleConstants.setForeground(PLAIN_ATTRIBUTES, Color.DARK_GRAY);

        StyleConstants.setFontSize(COMMENT_ATTRIBUTES, StyleConstants.getFontSize(COMMENT_ATTRIBUTES) - 1);
        StyleConstants.setForeground(COMMENT_ATTRIBUTES, Color.GRAY);
        StyleConstants.setItalic(COMMENT_ATTRIBUTES, true);
    }

    private boolean isUserChanges = true;

    public OutlineDocument() {

    }

    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        if (!isUserChanges()) {
            super.insertString(offs, str, a);
        }
    }

    public void remove(int offs, int len) throws BadLocationException {
        if (!isUserChanges()) {
            super.remove(offs, len);
        }
    }

    public boolean isUserChanges() {
        return isUserChanges;
    }

    public void setUserChanges(boolean userChanges) {
        isUserChanges = userChanges;
    }

    protected void insert(int offset, ElementSpec[] data) throws BadLocationException {
        super.insert(offset, data);
    }

}


text:
name: closure-warnings/lint-checks
---

## Summary


text: ..\..\nuget push Keiser.MvxPlugins.Sockets.1.0.5.nupkg


text:
from .output import pretty_draw
from .misc import constant, dataframe_value_mapping
import networkx as nx
import pandas as pd
import numpy as np
from .formats import bif_parser
import os.path
from itertools import repeat, combinations
from .factor import TableFactor, DictValueMapping

def descendants(G, x):
    """
    Set of all descendants of node in a graph, not including itself.
    :param G: target graph
    :param x: target node
    :return: set of descendants
    """
    return set(nx.dfs_preorder_nodes(G, x)) - {x}

def ancestors(G, x):
    """
    Set of all ancestors of node in a graph, not including itself.
    :param G: target graph
    :param x: target node
    :return: set of ancestors
    """
    G_reversed = G.reverse()
    return descendants(G_reversed, x)

def are_equal_graphs(G1, G2):
    """
    Check graph equality (equal node names, and equal edges between them).
    :param G1: first graph
    :param G2: second graph
    :return: are they equal
    """
    if set(G1.nodes()) != set(G2.nodes()):
        return False
    return all(map(lambda x: G1.has_edge(*x), G2.edges())) and all(map(lambda x: G2.has_edge(*x), G1.edges()))

class ErdosRenyiDGMGen:
    def __init__(self, n=10, p=0.5, factor_gen=None):
        self.n = n if hasattr(n, 'rvs') else constant(n)
        self.p = p if hasattr(p, 'rvs') else constant(p)
        self.factor_gen = factor_gen

    def __call__(self):
        result = DGM(nx.gnp_random_graph(self.n.rvs(), self.p.rvs()))
        for node, node_data in result.nodes(data=True):
            node_data['cpd'] = self.factor_gen(result.nodes(), ([node] + result.predecessors(node)))
            node_data['cpd'].normalize(node, copy=False)
        return result

class TreeDGMGen:
    def __init__(self, n=10, factor_gen=None):
        self.n = n if hasattr(n, 'rvs') else constant(n)
        self.factor_gen = factor_gen

    def __call__(self):
        def random_tree(n=10):
            assert n >= 1
            nodes = [0]
            result = nx.DiGraph()
            result.add_nodes_from(list(range(n)))
            counter = 1
            n -= 1
            while n >= 1:
                node = nodes.pop()
                n_children = np.random.randint(1, n + 1)
                nodes += [i for i in range(counter, counter + n_children)]
                result.add_edges_from(zip(repeat(node), range(counter, counter + n_children)))
                counter += n_children
                n -= n_children
            return result

        result = DGM(random_tree(n=self.n.rvs()))
        for node, node_data in result.nodes(data=True):
            node_data['cpd'] = self.factor_gen(result.nodes(), ([node] + result.predecessors(node)))
            node_data['cpd'].normalize(node, copy=False)
        return result

class DGM(nx.DiGraph):
    def __init__(self, *args, **kwargs):
        super(DGM, self).__init__()
        if len(args) == 1:
            self.add_nodes_from(args[0].nodes(data=True))
            self.add_edges_from(args[0].edges(data=True))

        if 'value_mapping' in kwargs:
            self.value_mapping = kwargs['value_mapping']
        else:
            self.value_mapping = None

    def add_argument(self, argument):
        for factor in self.factors:
            factor.add_argument(argument, copy=False)
        return self

    def fit(self, data, *args, **kwargs):
        value_mapping = DictValueMapping().fit(data)
        kwargs['disable_value_mapping'] = True
        data = value_mapping.transform(data)
        for node, node_data in self.nodes(data=True):
            if 'cpd' not in node_data:
                raise Exception('cpd not specified for node %s' % str(node))
            elif isinstance(node_data['cpd'], type):
                node_data['cpd'] = node_data['cpd'](self.nodes(), ([node] + self.predecessors(node)))
            node_data['cpd'].fit(data, *args, **kwargs)
            node_data['cpd'].normalize(node, copy=False)
            node_data['cpd'].value_mapping = value_mapping
        return self

    def rvs(self, size=1):
        result = pd.DataFrame(data={}, index=list(range(size)))
        for node in nx.topological_sort(self):
            cpd = self.cpd(node)
            result[node] = cpd.rvs(size=size, observed=result)[node]
        return result

    @property
    def factors(self):
        for node, node_data in self.nodes(data=True):
            yield node_data['cpd']

    def cpd(self, var):
        return self.node[var]['cpd'].normalize(var)

    def factor(self, var):
        return self.node[var]['cpd']

    def draw(self):
        return pretty_draw(self)

    def values(self, var):
        return list(self.node[var]['cpd'].value_mapping[var].keys())

    @staticmethod
    def read(filename):
        name, ext = os.path.splitext(filename)
        return getattr(DGM, '_read_' + ext[1:])(filename)

    @staticmethod
    def _read_bif(filename):
        with open(filename, 'r') as f:
            text = f.read()
        parsed = bif_parser.parse(text)

        result = DGM()
        arguments = [var['name'] for var in parsed['variables']]

        values = {}

        for variable in parsed['variables']:
            name = variable['name']
            result.add_node(name, attr_dict=variable['properties'], n_values=variable['n_values'])
            values[name] = variable['values_list']

        value_mapping = {key: {value: i for i, value in enumerate(lst)} for key, lst in values.items()}
        value_mapping = DictValueMapping(value_mapping)

        for distribution in parsed['distributions']:
            node = distribution['variables'][0]
            parents = distribution['variables'][1:]
            scope = distribution['variables']
            result.add_edges_from(zip(parents, repeat(node)))
            factor = TableFactor(arguments=arguments, scope=distribution['variables'])

            table_shape = tuple(result.node[var]['n_values'] for var in scope) + (1,) * (len(arguments) - len(scope))
            extended_scope = scope + [var for var in arguments if var not in scope]
            axes_order = [extended_scope.index(arg) for arg in arguments]
            if distribution['table'] is not None:
                factor.table = distribution['table']
                factor.table.resize(np.prod(table_shape))
                factor.table = factor.table.reshape(table_shape)
                factor.table = np.transpose(factor.table, axes=axes_order)
            else:
                factor.table = np.zeros(table_shape)
                for args, prob in distribution['probability'].items():
                    for i, p in enumerate(prob):
                        current_args = (i,) + tuple(values[var].index(arg) for var, arg in zip(parents, args)) \
                                       + (0,) * (len(arguments) - len(scope))
                        factor.table[current_args] = p
                factor.table = np.transpose(factor.table, axes=axes_order)

            factor.value_mapping = value_mapping
            result.node[node]['cpd'] = factor

        result.value_mapping = value_mapping
        return result

    @property
    def is_moral(self):
        """
        A graph is moral if it has no immoralities.
        :param self: target graph
        :return: is target graph moral
        """
        return len(list(self.immoralities)) == 0

    @property
    def immoralities(G):
        """
        Iterate over all immoralities in a graph.
        :param G: target graph
        :return: iterator over immoralities in form (node, parent1, parent2)
        """
        return filter(lambda v: (not G.has_edge(v[1], v[2])) and (not G.has_edge(v[2], v[1])), G.v_structures)

    @property
    def v_structures(G):
        """
        Iterate over all v-structures in a graph.
        :param G: target graph
        :return: iterator over v-structures in form (node, parent1, parent2)
        """
        for x in G.nodes():
            for p1, p2 in combinations(G.predecessors(x), r=2):
                yield x, p1, p2

    def reachable(self, source, observed):
        """
        Finds a set of reachable (in the sense of d-separation) nodes in graph.
        :param self: target graph
        :param source: source node name
        :param observed: a sequence of observed nodes
        :return: a set of reachable nodes
        """
        V = nx.number_of_nodes(self)
        A = set(sum([list(nx.dfs_preorder_nodes(self.reverse(), z)) for z in observed], []))
        Z = observed
        L = [(source, 'up')]
        V = set()
        result = set()
        while len(L) > 0:
            x, d = L.pop()
            if (x, d) in V:
                continue
            if x not in Z:
                result.add((x, d))
            V.add((x, d))
            if d == 'up' and x not in Z:
                for y in self.predecessors_iter(x):
                    L.append((y, 'up'))
                for y in self.successors_iter(x):
                    L.append((y, 'down'))
            elif d == 'down':
                if x in A:
                    for y in self.predecessors_iter(x):
                        L.append((y, 'up'))
                if x not in Z:
                    for y in self.successors_iter(x):
                        L.append((y, 'down'))
        result = set([x[0] for x in result])
        return result - {source}

    def is_covered(self, edge):
        """
        Checks if the edge is covered.
        :param self: graph
        :param edge: edge to check
        :return: is edge covered
        """
        x, y = edge
        return set(self.predecessors_iter(y)) - set(self.predecessors_iter(x)) == {x}

    def is_I_map(self, other):
        """
        Is self an I-map of other?
        """
        for x in self.nodes():
            pa = set(self.predecessors(x))
            non_descendants = set(self.nodes()) - descendants(self, x) - {x}
            if set.intersection(other.reachable(x, pa), non_descendants - pa):
                return False
        return True

    def is_I_equivalent(self, other):
        """
        Check if two graphs are I-equivalent
        :param self: first graph
        :param other: second graph
        :return: are the graphs I-equivalent
        """

        # same undirected skeleton
        if not are_equal_graphs(self.to_undirected(), other.to_undirected()):
            return False

        # same immoralities
        for x in self.nodes():
            for p1, p2 in set.union(set(combinations(self.predecessors(x), r=2)),
                                    set(combinations(other.predecessors(x), r=2))):
                if self.has_edge(p1, p2) or self.has_edge(p2, p1):
                    continue
                if other.has_edge(p1, x) and other.has_edge(p2, x):
                    continue
                return False

        # everything OK
        return True


text:
package mo_image

import "encoding/json"

type Exif struct {
	Raw              json.RawMessage
	DateTimeOriginal string `json:"date_time_original" path:"DateTimeOriginal"`
	DateTime         string `json:"date_time" path:"DateTime"`
	Make             string `json:"make" path:"Make"`
	Model            string `json:"model" path:"Model"`
}


text:
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../orov-behaviors/orov-behavior.html">
<dom-module id="orov-headingHold">

  <template>

{{__('Hdg')}}

{{_formatHeading(targetHeading)}}

  </template>

</dom-module>


text:
import string
srcRoot = "../.."
incFileName = srcRoot + "/scintilla/include/Scintilla.h"
docFileName = srcRoot + "/scintilla/doc/ScintillaDoc.html"
identCharacters = "_" + string.letters + string.digits

# Convert all punctuation characters except '_' into spaces.
def depunctuate(s):
	d = ""
	for ch in s:
		if ch in identCharacters:
			d = d + ch
		else:
			d = d + " "
	return d

symbols = {}
incFile = open(incFileName, "rt")
for line in incFile.readlines():
	if line.startswith("#define"):
		identifier = line.split()[1]
		symbols[identifier] = 0
incFile.close()

docFile = open(docFileName, "rt")
for line in docFile.readlines():
	for word in depunctuate(line).split():
		if word in symbols.keys():
			symbols[word] = 1
docFile.close()

identifiersSorted = symbols.keys()
identifiersSorted.sort()
for identifier in identifiersSorted:
	if not symbols[identifier]:
		print identifier


text:
//
//  NSFileProviderService.h
//  FileProvider
//
//  Copyright © 2017 Apple Inc. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <FileProvider/NSFileProviderDefines.h>
#import <FileProvider/NSFileProviderExtension.h>
#import <FileProvider/NSFileProviderItem.h>

NS_ASSUME_NONNULL_BEGIN

@class NSXPCListenerEndpoint;

API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(macos, watchos, tvos)
@protocol NSFileProviderServiceSource

/**
 The service name that uniquely identifies the service (using reverse domain
 name notation for you service name is recommended).
 */
@property (readonly, copy, nonatomic) NSFileProviderServiceName serviceName;

/**
 Return an endpoint object to allow the client application to connect to the
 file provider.
 The endpoint is retrieved from an anonymous @c NSXPCListener that the file
 provider creates. The file provider is in charge of accepting incoming
 @c NSXPCConnection's via @c -[NSXPCListenerDelegate listener:shouldAcceptNewConnection:],
 and setting up properties on the new connection, like its exported object and
 interfaces (that both the file provider and the client application have agreed
 on).
 */
- (nullable NSXPCListenerEndpoint *)makeListenerEndpointAndReturnError:(NSError **)error;

@end

/**
 A file provider can override the method in this category to return service
 sources that provide custom communication channels to client applications.
 The service sources must be tied to the item identified by @c itemIdentifier.
 Client applications can retrieve the list of supported services by calling
 @c -[NSFileManager getFileProviderServicesForItemAtURL:] for a specific item URL.
 */
@interface NSFileProviderExtension (NSFileProviderService)

- (nullable NSArray <id <NSFileProviderServiceSource>> *)supportedServiceSourcesForItemIdentifier:(NSFileProviderItemIdentifier)itemIdentifier error:(NSError **)error NS_SWIFT_NAME(supportedServiceSources(for:)) API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(macos, watchos, tvos);

@end

NS_ASSUME_NONNULL_END


text:
"""
Copyright 2014-2016 University of Illinois

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.

file: markupInfo/models.py

Author: Jon Gunderson

"""

from __future__ import absolute_import
import datetime
import sys
import os
import string

from django.db import models
from reports.models import WebsiteReport
from pageResults.models import PageResult

class WebsiteMarkup(models.Model):
    id = models.AutoField(primary_key=True)
    ws_report = models.ForeignKey(WebsiteReport, on_delete=models.CASCADE, related_name="mi_ws_report")

    hidden_count = models.IntegerField(default=0)
    offscreen_count = models.IntegerField(default=0)
    total_count = models.IntegerField(default=0)

    frame_count = models.IntegerField(default=0)
    iframe_count = models.IntegerField(default=0)

class WebsiteMarkupGroup(models.Model):
    id = models.AutoField(primary_key=True)
    ws_markup = models.ForeignKey(WebsiteMarkup, on_delete=models.CASCADE, related_name="ws_markups")

    name = models.CharField("Group Name", max_length=24)
    count = models.IntegerField(default=0)

class WebsiteMarkupItem(models.Model):
    id = models.AutoField(primary_key=True)
    ws_markup_group = models.ForeignKey(WebsiteMarkupGroup, on_delete=models.CASCADE, related_name="ws_markup_groups")

    element = models.CharField("Element", max_length=24)
    attribute = models.CharField("Attribute", max_length=24)
    event = models.CharField("Event", max_length=24)
    count = models.IntegerField(default=0)

class PageMarkup(models.Model):
    id = models.AutoField(primary_key=True)
    page_result = models.ForeignKey(PageResult, on_delete=models.CASCADE, related_name="mi_page_markups")

    hidden_count = models.IntegerField(default=0)
    offscreen_count = models.IntegerField(default=0)
    total_count = models.IntegerField(default=0)

    frame_count = models.IntegerField(default=0)
    iframe_count = models.IntegerField(default=0)

class PageMarkupGroup(models.Model):
    id = models.AutoField(primary_key=True)
    page_markup = models.ForeignKey(PageMarkup, on_delete=models.CASCADE, related_name="page_markups")

    name = models.CharField("Group Name", max_length=24)
    count = models.IntegerField(default=0)

    ws_markup_group = models.ForeignKey(WebsiteMarkupGroup, related_name="page_ws_markup_groups",
                                        on_delete=models.CASCADE)

class PageMarkupItem(models.Model):
    id = models.AutoField(primary_key=True)
    page_markup_group = models.ForeignKey(PageMarkupGroup, on_delete=models.CASCADE, related_name="page_markup_groups")

    element = models.CharField("Element", max_length=24)
    attribute = models.CharField("Attribute", max_length=24)
    event = models.CharField("Event", max_length=24)
    count = models.IntegerField(default=0)

    ws_markup_item = models.ForeignKey(WebsiteMarkupItem, on_delete=models.CASCADE, related_name="page_ws_markup_items")

class MIpageSummary(models.Model):
    id = models.AutoField(primary_key=True)

    page_result = models.ForeignKey(PageResult, on_delete=models.CASCADE, related_name="mi_page_summary")

    all_element_count = models.IntegerField(default=0)
    all_hidden_count = models.IntegerField(default=0)
    all_offscreen_count = models.IntegerField(default=0)

    frame_count = models.IntegerField(default=0)
    iframe_count = models.IntegerField(default=0)

    class Meta:
        verbose_name = "Page Markup: Summary"
        verbose_name_plural = "Page Markup: Summary"

class MIpageImages(models.Model):
    id = models.AutoField(primary_key=True)

    page_result = models.ForeignKey(PageResult, on_delete=models.CASCADE, related_name="mi_page_images")

    all_images_count = models.IntegerField(default=0)
    img_count = models.IntegerField(default=0)
    canvas_count = models.IntegerField(default=0)
    svg_count = models.IntegerField(default=0)
    figure_count = models.IntegerField(default=0)
    figcaption_count = models.IntegerField(default=0)

    alt_attribute_count = models.IntegerField(default=0)
    longdesc_attribute_count = models.IntegerField(default=0)

    class Meta:
        verbose_name = "Page Markup: Image"
        verbose_name_plural = "Page Markup: Images"

class MIpageHeadings(models.Model):
    id = models.AutoField(primary_key=True)

    page_result = models.ForeignKey(PageResult, on_delete=models.CASCADE, related_name="mi_page_headgings")

    all_headings_count = models.IntegerField(default=0)
    h1_count = models.IntegerField(default=0)
    h2_count = models.IntegerField(default=0)
    h3_count = models.IntegerField(default=0)
    h4_count = models.IntegerField(default=0)
    h5_count = models.IntegerField(default=0)
    h6_count = models.IntegerField(default=0)

    class Meta:
        verbose_name = "Page Markup: Heading (H1-H6)"
        verbose_name_plural = "Page Markup: Headings (H1-H6)"

class MIpageSections(models.Model):
    id = models.AutoField(primary_key=True)

    page_result = models.ForeignKey(PageResult, on_delete=models.CASCADE, related_name="mi_page_sections")

    all_sections_count = models.IntegerField(default=0)
    address_count = models.IntegerField(default=0)
    article_count = models.IntegerField(default=0)
    aside_count = models.IntegerField(default=0)
    details_count = models.IntegerField(default=0)
    dialog_count = models.IntegerField(default=0)
    footer_count = models.IntegerField(default=0)
    header_count = models.IntegerField(default=0)
    main_count = models.IntegerField(default=0)
    nav_count = models.IntegerField(default=0)
    section_count = models.IntegerField(default=0)
    summary_count = models.IntegerField(default=0)

    class Meta:
        verbose_name = "Page Markup: HTML5 Section"
        verbose_name_plural = "Page Markup: HTML5 Sections"

class MIpageLists(models.Model):
    id = models.AutoField(primary_key=True)

    page_result = models.ForeignKey(PageResult, on_delete=models.CASCADE, related_name="mi_page_lists")

    all_lists_count = models.IntegerField(default=0)
    ul_count = models.IntegerField(default=0)
    ol_count = models.IntegerField(default=0)
    li_count = models.IntegerField(default=0)

    dl_count = models.IntegerField(default=0)
    dt_count = models.IntegerField(default=0)
    dd_count = models.IntegerField(default=0)

    class Meta:
        verbose_name = "Page Markup: List"
        verbose_name_plural = "Page Markup: Lists"

class MIpageLinks(models.Model):
    id = models.AutoField(primary_key=True)

    page_result = models.ForeignKey(PageResult, on_delete=models.CASCADE, related_name="mi_page_links")

    all_links_count = models.IntegerField(default=0)

    a_count = models.IntegerField(default=0)
    area_count = models.IntegerField(default=0)

    class Meta:
        verbose_name = "Page Markup: Link"
        verbose_name_plural = "Page Markup: Links"

class MIpageTables(models.Model):
    id = models.AutoField(primary_key=True)

    page_result = models.ForeignKey(PageResult, on_delete=models.CASCADE, related_name="mi_page_tables")

    all_tables_count = models.IntegerField(default=0)

    table_count = models.IntegerField(default=0)
    th_count = models.IntegerField(default=0)
    td_count = models.IntegerField(default=0)
    caption_count = models.IntegerField(default=0)

    summary_attribute_count = models.IntegerField(default=0)
    scope_attribute_count = models.IntegerField(default=0)
    headers_attribute_count = models.IntegerField(default=0)

    class Meta:
        verbose_name = "Page Markup: Table"
        verbose_name_plural = "Page Markup: Tables"

class MIpageForms(models.Model):
    id = models.AutoField(primary_key=True)

    page_result = models.ForeignKey(PageResult, on_delete=models.CASCADE, related_name="mi_page_controls")

    all_forms_count = models.IntegerField(default=0)

    input_button_count = models.IntegerField(default=0)
    input_checkbox_count = models.IntegerField(default=0)
    input_color_count = models.IntegerField(default=0)
    input_date_count = models.IntegerField(default=0)
    input_datetime_count = models.IntegerField(default=0)
    input_email_count = models.IntegerField(default=0)
    input_file_count = models.IntegerField(default=0)
    input_image_count = models.IntegerField(default=0)
    input_month_count = models.IntegerField(default=0)
    input_number_count = models.IntegerField(default=0)
    input_password_count = models.IntegerField(default=0)
    input_radio_count = models.IntegerField(default=0)
    input_range_count = models.IntegerField(default=0)
    input_reset_count = models.IntegerField(default=0)
    input_search_count = models.IntegerField(default=0)
    input_submit_count = models.IntegerField(default=0)
    input_tel_count = models.IntegerField(default=0)
    input_text_count = models.IntegerField(default=0)
    input_time_count = models.IntegerField(default=0)
    input_url_count = models.IntegerField(default=0)
    input_week_count = models.IntegerField(default=0)

    autofocus_attribute_count = models.IntegerField(default=0)
    placeholder_attribute_count = models.IntegerField(default=0)
    pattern_attribute_count = models.IntegerField(default=0)
    required_attribute_count = models.IntegerField(default=0)

    output_count = models.IntegerField(default=0)
    progress_count = models.IntegerField(default=0)
    meter_count = models.IntegerField(default=0)

    fieldset_count = models.IntegerField(default=0)
    label_count = models.IntegerField(default=0)
    legend_count = models.IntegerField(default=0)
    title_attribute_count = models.IntegerField(default=0)

    button_count = models.IntegerField(default=0)
    select_count = models.IntegerField(default=0)
    textarea_count = models.IntegerField(default=0)

    class Meta:
        verbose_name = "Page Markup: Form Controls"
        verbose_name_plural = "Page Markup: Form Controls"

class MIpageMedia(models.Model):
    id = models.AutoField(primary_key=True)

    page_result = models.ForeignKey(PageResult, on_delete=models.CASCADE, related_name="mi_page_media")

    all_media_count = models.IntegerField(default=0)
    audio_count = models.IntegerField(default=0)
    embed_count = models.IntegerField(default=0)
    object_count = models.IntegerField(default=0)
    video_count = models.IntegerField(default=0)
    track_count = models.IntegerField(default=0)
    source_count = models.IntegerField(default=0)

    class Meta:
        verbose_name = "Page Markup: Media"
        verbose_name_plural = "Page Markup: Media"

class MIpageLandmarks(models.Model):
    id = models.AutoField(primary_key=True)

    page_result = models.ForeignKey(PageResult, on_delete=models.CASCADE, related_name="mi_page_landmarks")

    all_landmarks_count = models.IntegerField(default=0)
    role_application_count = models.IntegerField(default=0)
    role_banner_count = models.IntegerField(default=0)
    role_complementary_count = models.IntegerField(default=0)
    role_contentinfo_count = models.IntegerField(default=0)
    role_form_count = models.IntegerField(default=0)
    role_main_count = models.IntegerField(default=0)
    role_navigation_count = models.IntegerField(default=0)
    role_region_count = models.IntegerField(default=0)
    role_search_count = models.IntegerField(default=0)

    class Meta:
        verbose_name = "Page Markup: Landmark"
        verbose_name_plural = "Page Markup: Landmarks"

class MIpageStructures(models.Model):
    id = models.AutoField(primary_key=True)

    page_result = models.ForeignKey(PageResult, on_delete=models.CASCADE, related_name="mi_page_structures")

    all_structures_count = models.IntegerField(default=0)
    role_article_count = models.IntegerField(default=0)
    role_directory_count = models.IntegerField(default=0)
    role_document_count = models.IntegerField(default=0)
    role_heading_count = models.IntegerField(default=0)
    role_math_count = models.IntegerField(default=0)
    role_note_count = models.IntegerField(default=0)
    role_presentation_count = models.IntegerField(default=0)

    class Meta:
        verbose_name = "Page Markup: ARIA Structure"
        verbose_name_plural = "Page Markup: ARIA Structures"

class MIpageWidgets(models.Model):
    id = models.AutoField(primary_key=True)

    page_result = models.ForeignKey(PageResult, on_delete=models.CASCADE, related_name="mi_page_widgets")

    all_widgets_count = models.IntegerField(default=0)
    role_button_count = models.IntegerField(default=0)
    role_link_count = models.IntegerField(default=0)

    aria_describedby_count = models.IntegerField(default=0)
    aria_describedat_count = models.IntegerField(default=0)

    aria_labelledby_count = models.IntegerField(default=0)
    aria_label_count = models.IntegerField(default=0)

    aria_owns_count = models.IntegerField(default=0)
    aria_activedescendant_count = models.IntegerField(default=0)
    aria_flowto_count = models.IntegerField(default=0)
    aria_controls_count = models.IntegerField(default=0)
    aria_hidden_count = models.IntegerField(default=0)

    class Meta:
        verbose_name = "Page Markup: ARIA Widget"
        verbose_name_plural = "Page Markup: ARIA Widgets"

class MIpageLives(models.Model):
    id = models.AutoField(primary_key=True)

    page_result = models.ForeignKey(PageResult, on_delete=models.CASCADE, related_name="mi_page_lives")

    all_lives_count = models.IntegerField(default=0)

    aria_live_count = models.IntegerField(default=0)

    role_alert_count = models.IntegerField(default=0)
    role_status_count = models.IntegerField(default=0)
    role_log_count = models.IntegerField(default=0)

    class Meta:
        verbose_name = "Page Markup: ARIA Live Region"
        verbose_name_plural = "Page Markup: ARIA Live Regions"

class MIpageEvents(models.Model):
    id = models.AutoField(primary_key=True)

    page_result = models.ForeignKey(PageResult, on_delete=models.CASCADE, related_name="mi_page_events")

    all_events_count = models.IntegerField(default=0)

    load_event_count = models.IntegerField(default=0)

    blur_event_count = models.IntegerField(default=0)
    focus_event_count = models.IntegerField(default=0)

    change_event_count = models.IntegerField(default=0)

    drag_events_count = models.IntegerField(default=0)

    click_event_count = models.IntegerField(default=0)
    double_click_event_count = models.IntegerField(default=0)

    keyboard_events_count = models.IntegerField(default=0)

    mouse_events_count = models.IntegerField(default=0)

    touch_events_count = models.IntegerField(default=0)

    pointer_events_count = models.IntegerField(default=0)

    class Meta:
        verbose_name = "Page Markup: Events"
        verbose_name_plural = "Page Markup: Events"


text:
<?php

namespace Sonata\CoreBundle\Tests\Form\Type;

use Sonata\CoreBundle\Form\Type\ImmutableArrayType;

use Symfony\Component\Form\Test\TypeTestCase;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ImmutableArrayTypeTest extends TypeTestCase
{
    public function testGetDefaultOptions()
    {
        $type = new ImmutableArrayType();

        $this->assertEquals('sonata_type_immutable_array', $type->getName());
        $this->assertEquals('form', $type->getParent());

        $resolver = new OptionsResolver();
        $type->setDefaultOptions($resolver);

        $options = $resolver->resolve();

        $expected = array(
            'keys' => array()
        );

        $this->assertEquals($expected, $options);
    }

    public function testCallback()
    {
        $type = new ImmutableArrayType();

        $builder = $this->getMock('Symfony\Component\Form\Test\FormBuilderInterface');
        $builder->expects($this->once())->method('add')->with(
            $this->callback(function($name) {
                return $name == 'ttl';
            }),
            $this->callback(function($name) {
                return $name == 'text';
            }),
            $this->callback(function($name) {
                return $name == array(1 => 1);
            })
        );

        $self = $this;
        $optionsCallback = function ($builder, $name, $type, $extra) use ($self) {
            $self->assertEquals(array('foo', 'bar'), $extra);
            $self->assertEquals($name, 'ttl');
            $self->assertEquals($type, 'text');
            $self->assertInstanceOf('Symfony\Component\Form\Test\FormBuilderInterface', $builder);

            return array('1' => '1');
        };

        $options = array(
            'keys' => array(
                array('ttl', 'text', $optionsCallback, 'foo', 'bar')
            )
        );

        $type->buildForm($builder, $options);
    }
}


text:
    package net.java.sip.communicator.impl.sysactivity;

import android.content.*;
import org.jitsi.android.*;
import org.jitsi.service.osgi.*;
import net.java.sip.communicator.service.sysactivity.event.*;
import net.java.sip.communicator.util.*;

/**
 * Listens for broadcasts from ConnectivityManager to get notified
 * for network changes.
 *
 * @author Damian Minkov
 */
public class ConnectivityManagerListenerImpl
    extends BroadcastReceiver
    implements SystemActivityManager
{
    /**
     * The action name we will receive broadcasts for to get informed
     * for connectivity changes.
     */
    private static final String CONNECTIVITY_CHANGE_ACTION =
        "android.net.conn.CONNECTIVITY_CHANGE";

    /**
     * The only instance of this impl.
     */
    private static ConnectivityManagerListenerImpl connectivityManagerListenerImpl;

    /**
     * Whether we are working.
     */
    private boolean connected = false;

    /**
     * Gets the instance of <tt>ConnectivityManagerListenerImpl</tt>.
     * @return the ConnectivityManagerListenerImpl.
     */
    public static ConnectivityManagerListenerImpl getInstance()
    {
        if(connectivityManagerListenerImpl == null)
            connectivityManagerListenerImpl =
                new ConnectivityManagerListenerImpl();

        return connectivityManagerListenerImpl;
    }

    /**
     * Starts
     */
    public void start()
    {
        Context context = JitsiApplication.getGlobalContext();
        context.registerReceiver(this,
            new IntentFilter(CONNECTIVITY_CHANGE_ACTION));

        connected = true;
    }

    /**
     * Stops.
     */
    public void stop()
    {
        Context context = JitsiApplication.getGlobalContext();
        context.unregisterReceiver(this);

        connected = false;
    }

    /**
     * Whether the underlying implementation is currently connected and
     * working.
     * @return whether we are connected and working.
     */
    public boolean isConnected()
    {
        return connected;
    }

    /**
     * Receiving broadcast for network change.
     * @param context the context.
     * @param intent the intent for the broadcast.
     */
    public void onReceive(Context context, Intent intent)
    {
        if(intent.getAction().equals(CONNECTIVITY_CHANGE_ACTION))
        {
            SystemActivityEvent evt = new SystemActivityEvent(
                SysActivityActivator.getSystemActivityService(),
                SystemActivityEvent.EVENT_NETWORK_CHANGE);

            SysActivityActivator.getSystemActivityService()
                .fireSystemActivityEvent(evt);
        }
    }
}


text:
package io;

import java.io.Console;

public class ConsoleTest {
	public static void main(String[] args) {
		Console console = null;
		// Retorna uma referencia ao terminal que foi utilizado para iniciar o
		// programa, se for usado uma IDE ou sub-processo é retornado null
		console = System.console();

		String user = console.readLine("Entre com seu usuario: "); // Imprime a
																	// mensagem
																	// e le a
																	// resposta
																	// de
																	// entrada
		char[] pass = console.readPassword("Entre com sua senha: "); // Imprime
																		// a
																		// mensagem
																		// e le
																		// a
																		// resposta
																		// de
																		// entrada,
																		// porém
																		// não
																		// mostra
																		// no
																		// console

		System.out.println("Bem-vindo " + user + " com senha " + String.valueOf(pass));
	}

}


text:
// These parts have to stay in a separate assembly info, since fake re-creates AssemblyInfo.cs on each build
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("F2F.ReactiveNavigation.UnitTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]  // necessary for FakeItEasy to create fakes of internal interfaces


text:
/*!
 * vue-i18n v4.8.0
 * (c) 2016 kazuya kawaguchi
 * Released under the MIT License.
 */
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  typeof define === 'function' && define.amd ? define(factory) :
  (global.VueI18n = factory());
}(this, function () { 'use strict';

  var babelHelpers = {};
  babelHelpers.typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
    return typeof obj;
  } : function (obj) {
    return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
  };
  babelHelpers;

  /**
   * warn
   *
   * @param {String} msg
   * @param {Error} [err]
   *
   */

  function warn(msg, err) {
    if (window.console) {
      console.warn('[vue-i18n] ' + msg);
      if (err) {
        console.warn(err.stack);
      }
    }
  }

  function Asset (Vue, langVM) {
    /**
     * Register or retrieve a global locale definition.
     *
     * @param {String} id
     * @param {Object | Function | Promise} definition
     * @param {Function} cb
     */

    Vue.locale = function (id, definition, cb) {
      if (definition === undefined) {
        // gettter
        return langVM.locales[id];
      } else {
        // setter
        if (definition === null) {
          langVM.locales[id] = undefined;
          delete langVM.locales[id];
        } else {
          setLocale(id, definition, function (locale) {
            if (locale) {
              langVM.locales[id] = locale;
            } else {
              warn('failed set `' + id + '` locale');
            }
            cb && cb();
          });
        }
      }
    };
  }

  function setLocale(id, definition, cb) {
    var _this = this;

    if ((typeof definition === 'undefined' ? 'undefined' : babelHelpers.typeof(definition)) === 'object') {
      // sync
      cb(definition);
    } else {
      (function () {
        var future = definition.call(_this);
        if (typeof future === 'function') {
          if (future.resolved) {
            // cached
            cb(future.resolved);
          } else if (future.requested) {
            // pool callbacks
            future.pendingCallbacks.push(cb);
          } else {
            (function () {
              future.requested = true;
              var cbs = future.pendingCallbacks = [cb];
              future(function (locale) {
                // resolve
                future.resolved = locale;
                for (var i = 0, l = cbs.length; i < l; i++) {
                  cbs[i](locale);
                }
              }, function () {
                // reject
                cb();
              });
            })();
          }
        } else if (isPromise(future)) {
          // promise
          future.then(function (locale) {
            // resolve
            cb(locale);
          }, function () {
            // reject
            cb();
          }).catch(function (err) {
            console.error(err);
            cb();
          });
        }
      })();
    }
  }

  /**
   * Forgiving check for a promise
   *
   * @param {Object} p
   * @return {Boolean}
   */

  function isPromise(p) {
    return p && typeof p.then === 'function';
  }

  function Override (Vue, langVM, version) {
    function update(vm) {
      if (version > 1) {
        vm.$forceUpdate();
      } else {
        var i = vm._watchers.length;
        while (i--) {
          vm._watchers[i].update(true); // shallow updates
        }
      }
    }

    // override _init
    var init = Vue.prototype._init;
    Vue.prototype._init = function (options) {
      var _this = this;

      init.call(this, options);

      if (!this.$parent) {
        // root
        this.$lang = langVM;
        this._langUnwatch = this.$lang.$watch('$data', function (val, old) {
          update(_this);
        }, { deep: true });
      }
    };

    // override _destroy
    var destroy = Vue.prototype._destroy;
    Vue.prototype._destroy = function () {
      if (!this.$parent && this._langUnwatch) {
        this._langUnwatch();
        this._langUnwatch = null;
        this.$lang = null;
      }

      destroy.apply(this, arguments);
    };
  }

  /**
   * Observer
   */

  var Watcher = void 0;
  /**
   * getWatcher
   *
   * @param {Vue} vm
   * @return {Watcher}
   */

  function getWatcher(vm) {
    if (!Watcher) {
      var unwatch = vm.$watch('__watcher__', function (a) {});
      Watcher = vm._watchers[0].constructor;
      unwatch();
    }
    return Watcher;
  }

  var Dep = void 0;
  /**
   * getDep
   *
   * @param {Vue} vm
   * @return {Dep}
   */

  function getDep(vm) {
    if (!Dep && vm && vm._data && vm._data.__ob__ && vm._data.__ob__.dep) {
      Dep = vm._data.__ob__.dep.constructor;
    }
    return Dep;
  }

  var fallback = void 0; // fallback lang
  var missingHandler = null; // missing handler
  var i18nFormatter = null; // custom formatter

  function Config (Vue, langVM, lang) {
    var bind = Vue.util.bind;

    var Watcher = getWatcher(langVM);
    var Dep = getDep(langVM);

    function makeComputedGetter(getter, owner) {
      var watcher = new Watcher(owner, getter, null, {
        lazy: true
      });

      return function computedGetter() {
        watcher.dirty && watcher.evaluate();
        Dep && Dep.target && watcher.depend();
        return watcher.value;
      };
    }

    // define Vue.config.lang configration
    Object.defineProperty(Vue.config, 'lang', {
      enumerable: true,
      configurable: true,
      get: makeComputedGetter(function () {
        return langVM.lang;
      }, langVM),
      set: bind(function (val) {
        langVM.lang = val;
      }, langVM)
    });

    // define Vue.config.fallbackLang configration
    fallback = lang;
    Object.defineProperty(Vue.config, 'fallbackLang', {
      enumerable: true,
      configurable: true,
      get: function get() {
        return fallback;
      },
      set: function set(val) {
        fallback = val;
      }
    });

    // define Vue.config.missingHandler configration
    Object.defineProperty(Vue.config, 'missingHandler', {
      enumerable: true,
      configurable: true,
      get: function get() {
        return missingHandler;
      },
      set: function set(val) {
        missingHandler = val;
      }
    });

    // define Vue.config.i18Formatter configration
    Object.defineProperty(Vue.config, 'i18nFormatter', {
      enumerable: true,
      configurable: true,
      get: function get() {
        return i18nFormatter;
      },
      set: function set(val) {
        i18nFormatter = val;
      }
    });
  }

  /**
   * utilites
   */

  /**
   * isNil
   *
   * @param {*} val
   * @return Boolean
   */
  function isNil(val) {
    return val === null || val === undefined;
  }

  /**
   *  String format template
   *  - Inspired:
   *    https://github.com/Matt-Esch/string-template/index.js
   */

  var RE_NARGS = /(%|)\{([0-9a-zA-Z_]+)\}/g;

  function Format (Vue) {
    var hasOwn = Vue.util.hasOwn;

    /**
     * template
     *
     * @param {String} string
     * @param {Array} ...args
     * @return {String}
     */

    function template(string) {
      for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }

      if (args.length === 1 && babelHelpers.typeof(args[0]) === 'object') {
        args = args[0];
      } else {
        args = {};
      }

      if (!args || !args.hasOwnProperty) {
        args = {};
      }

      return string.replace(RE_NARGS, function (match, prefix, i, index) {
        var result = void 0;

        if (string[index - 1] === '{' && string[index + match.length] === '}') {
          return i;
        } else {
          result = hasOwn(args, i) ? args[i] : match;
          if (isNil(result)) {
            return '';
          }

          return result;
        }
      });
    }

    return template;
  }

  /**
   *  Path paerser
   *  - Inspired:
   *    Vue.js Path parser
   */

  // cache
  var pathCache = Object.create(null);

  // actions
  var APPEND = 0;
  var PUSH = 1;
  var INC_SUB_PATH_DEPTH = 2;
  var PUSH_SUB_PATH = 3;

  // states
  var BEFORE_PATH = 0;
  var IN_PATH = 1;
  var BEFORE_IDENT = 2;
  var IN_IDENT = 3;
  var IN_SUB_PATH = 4;
  var IN_SINGLE_QUOTE = 5;
  var IN_DOUBLE_QUOTE = 6;
  var AFTER_PATH = 7;
  var ERROR = 8;

  var pathStateMachine = [];

  pathStateMachine[BEFORE_PATH] = {
    'ws': [BEFORE_PATH],
    'ident': [IN_IDENT, APPEND],
    '[': [IN_SUB_PATH],
    'eof': [AFTER_PATH]
  };

  pathStateMachine[IN_PATH] = {
    'ws': [IN_PATH],
    '.': [BEFORE_IDENT],
    '[': [IN_SUB_PATH],
    'eof': [AFTER_PATH]
  };

  pathStateMachine[BEFORE_IDENT] = {
    'ws': [BEFORE_IDENT],
    'ident': [IN_IDENT, APPEND]
  };

  pathStateMachine[IN_IDENT] = {
    'ident': [IN_IDENT, APPEND],
    '0': [IN_IDENT, APPEND],
    'number': [IN_IDENT, APPEND],
    'ws': [IN_PATH, PUSH],
    '.': [BEFORE_IDENT, PUSH],
    '[': [IN_SUB_PATH, PUSH],
    'eof': [AFTER_PATH, PUSH]
  };

  pathStateMachine[IN_SUB_PATH] = {
    "'": [IN_SINGLE_QUOTE, APPEND],
    '"': [IN_DOUBLE_QUOTE, APPEND],
    '[': [IN_SUB_PATH, INC_SUB_PATH_DEPTH],
    ']': [IN_PATH, PUSH_SUB_PATH],
    'eof': ERROR,
    'else': [IN_SUB_PATH, APPEND]
  };

  pathStateMachine[IN_SINGLE_QUOTE] = {
    "'": [IN_SUB_PATH, APPEND],
    'eof': ERROR,
    'else': [IN_SINGLE_QUOTE, APPEND]
  };

  pathStateMachine[IN_DOUBLE_QUOTE] = {
    '"': [IN_SUB_PATH, APPEND],
    'eof': ERROR,
    'else': [IN_DOUBLE_QUOTE, APPEND]
  };

  /**
   * Check if an expression is a literal value.
   *
   * @param {String} exp
   * @return {Boolean}
   */

  var literalValueRE = /^\s?(true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
  function isLiteral(exp) {
    return literalValueRE.test(exp);
  }

  /**
   * Strip quotes from a string
   *
   * @param {String} str
   * @return {String | false}
   */

  function stripQuotes(str) {
    var a = str.charCodeAt(0);
    var b = str.charCodeAt(str.length - 1);
    return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
  }

  /**
   * Determine the type of a character in a keypath.
   *
   * @param {Char} ch
   * @return {String} type
   */

  function getPathCharType(ch) {
    if (ch === undefined) {
      return 'eof';
    }

    var code = ch.charCodeAt(0);

    switch (code) {
      case 0x5B: // [
      case 0x5D: // ]
      case 0x2E: // .
      case 0x22: // "
      case 0x27: // '
      case 0x30:
        // 0
        return ch;

      case 0x5F: // _
      case 0x24: // $
      case 0x2D:
        // -
        return 'ident';

      case 0x20: // Space
      case 0x09: // Tab
      case 0x0A: // Newline
      case 0x0D: // Return
      case 0xA0: // No-break space
      case 0xFEFF: // Byte Order Mark
      case 0x2028: // Line Separator
      case 0x2029:
        // Paragraph Separator
        return 'ws';
    }

    // a-z, A-Z
    if (code >= 0x61 && code <= 0x7A || code >= 0x41 && code <= 0x5A) {
      return 'ident';
    }

    // 1-9
    if (code >= 0x31 && code <= 0x39) {
      return 'number';
    }

    return 'else';
  }

  /**
   * Format a subPath, return its plain form if it is
   * a literal string or number. Otherwise prepend the
   * dynamic indicator (*).
   *
   * @param {String} path
   * @return {String}
   */

  function formatSubPath(path) {
    var trimmed = path.trim();
    // invalid leading 0
    if (path.charAt(0) === '0' && isNaN(path)) {
      return false;
    }

    return isLiteral(trimmed) ? stripQuotes(trimmed) : '*' + trimmed;
  }

  /**
   * Parse a string path into an array of segments
   *
   * @param {String} path
   * @return {Array|undefined}
   */

  function parse(path) {
    var keys = [];
    var index = -1;
    var mode = BEFORE_PATH;
    var subPathDepth = 0;
    var c = void 0,
        newChar = void 0,
        key = void 0,
        type = void 0,
        transition = void 0,
        action = void 0,
        typeMap = void 0;

    var actions = [];

    actions[PUSH] = function () {
      if (key !== undefined) {
        keys.push(key);
        key = undefined;
      }
    };

    actions[APPEND] = function () {
      if (key === undefined) {
        key = newChar;
      } else {
        key += newChar;
      }
    };

    actions[INC_SUB_PATH_DEPTH] = function () {
      actions[APPEND]();
      subPathDepth++;
    };

    actions[PUSH_SUB_PATH] = function () {
      if (subPathDepth > 0) {
        subPathDepth--;
        mode = IN_SUB_PATH;
        actions[APPEND]();
      } else {
        subPathDepth = 0;
        key = formatSubPath(key);
        if (key === false) {
          return false;
        } else {
          actions[PUSH]();
        }
      }
    };

    function maybeUnescapeQuote() {
      var nextChar = path[index + 1];
      if (mode === IN_SINGLE_QUOTE && nextChar === "'" || mode === IN_DOUBLE_QUOTE && nextChar === '"') {
        index++;
        newChar = '\\' + nextChar;
        actions[APPEND]();
        return true;
      }
    }

    while (mode != null) {
      index++;
      c = path[index];

      if (c === '\\' && maybeUnescapeQuote()) {
        continue;
      }

      type = getPathCharType(c);
      typeMap = pathStateMachine[mode];
      transition = typeMap[type] || typeMap['else'] || ERROR;

      if (transition === ERROR) {
        return; // parse error
      }

      mode = transition[0];
      action = actions[transition[1]];
      if (action) {
        newChar = transition[2];
        newChar = newChar === undefined ? c : newChar;
        if (action() === false) {
          return;
        }
      }

      if (mode === AFTER_PATH) {
        keys.raw = path;
        return keys;
      }
    }
  }

  /**
   * External parse that check for a cache hit first
   *
   * @param {String} path
   * @return {Array|undefined}
   */

  function parsePath(path) {
    var hit = pathCache[path];
    if (!hit) {
      hit = parse(path);
      if (hit) {
        pathCache[path] = hit;
      }
    }
    return hit;
  }

  function Path (Vue) {
    var _Vue$util = Vue.util;
    var isObject = _Vue$util.isObject;
    var isPlainObject = _Vue$util.isPlainObject;
    var hasOwn = _Vue$util.hasOwn;

    function empty(target) {
      if (target === null || target === undefined) {
        return true;
      }

      if (Array.isArray(target)) {
        if (target.length > 0) {
          return false;
        }
        if (target.length === 0) {
          return true;
        }
      } else if (isPlainObject(target)) {
        /* eslint-disable prefer-const */
        for (var key in target) {
          if (hasOwn(target, key)) {
            return false;
          }
        }
        /* eslint-enable prefer-const */
      }

      return true;
    }

    /**
     * Get value from path string
     *
     * @param {Object} obj
     * @param {String} path
     * @return value
     */

    function getValue(obj, path) {
      if (!isObject(obj)) {
        return null;
      }

      var paths = parsePath(path);
      if (empty(paths)) {
        return null;
      }

      var length = paths.length;
      var ret = null;
      var last = obj;
      var i = 0;
      while (i < length) {
        var value = last[paths[i]];
        if (value === undefined) {
          last = null;
          break;
        }
        last = value;
        i++;
      }

      ret = last;
      return ret;
    }

    return getValue;
  }

  /**
   * extend
   *
   * @param {Vue} Vue
   * @return {Vue}
   */

  function Extend (Vue) {
    var _Vue$util = Vue.util;
    var isObject = _Vue$util.isObject;
    var bind = _Vue$util.bind;

    var format = Format(Vue);
    var getValue = Path(Vue);

    function parseArgs() {
      for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      var lang = Vue.config.lang;
      var fallback = Vue.config.fallbackLang;

      if (args.length === 1) {
        if (isObject(args[0]) || Array.isArray(args[0])) {
          args = args[0];
        } else if (typeof args[0] === 'string') {
          lang = args[0];
        }
      } else if (args.length === 2) {
        if (typeof args[0] === 'string') {
          lang = args[0];
        }
        if (isObject(args[1]) || Array.isArray(args[1])) {
          args = args[1];
        }
      }

      return { lang: lang, fallback: fallback, params: args };
    }

    function interpolate(locale, key, args) {
      if (!locale) {
        return null;
      }

      var val = getValue(locale, key);
      if (Array.isArray(val)) {
        return val;
      }
      if (isNil(val)) {
        val = locale[key];
      }
      if (isNil(val)) {
        return null;
      }
      if (typeof val !== 'string') {
        warn("Value of key '" + key + "' is not a string!");return null;
      }

      // Check for the existance of links within the translated string
      if (val.indexOf('@:') >= 0) {
        // Match all the links within the local
        // We are going to replace each of
        // them with its translation
        var matches = val.match(/(@:[\w|.]+)/g);
        for (var idx in matches) {
          var link = matches[idx];
          // Remove the leading @:
          var linkPlaceholder = link.substr(2);
          // Translate the link
          var translatedstring = interpolate(locale, linkPlaceholder, args);
          // Replace the link with the translated string
          val = val.replace(link, translatedstring);
        }
      }

      return !args ? val : Vue.config.i18nFormatter ? Vue.config.i18nFormatter.apply(null, [val].concat(args)) : format(val, args);
    }

    function translate(getter, lang, fallback, key, params) {
      var res = null;
      res = interpolate(getter(lang), key, params);
      if (!isNil(res)) {
        return res;
      }

      res = interpolate(getter(fallback), key, params);
      if (!isNil(res)) {
        if ('development' !== 'production') {
          warn('Fall back to translate the keypath "' + key + '" with "' + fallback + '" language.');
        }
        return res;
      } else {
        return null;
      }
    }

    function warnDefault(lang, key, vm, result) {
      if (!isNil(result)) {
        return result;
      }
      if (Vue.config.missingHandler) {
        Vue.config.missingHandler.apply(null, [lang, key, vm]);
      } else {
        if ('development' !== 'production') {
          warn('Cannot translate the value of keypath "' + key + '". ' + 'Use the value of keypath as default');
        }
      }
      return key;
    }

    function getAssetLocale(lang) {
      return Vue.locale(lang);
    }

    function getComponentLocale(lang) {
      return this.$options.locales[lang];
    }

    function getOldChoiceIndexFixed(choice) {
      return choice ? choice > 1 ? 1 : 0 : 1;
    }

    function getChoiceIndex(choice, choicesLength) {
      choice = Math.abs(choice);

      if (choicesLength === 2) {
        return getOldChoiceIndexFixed(choice);
      }

      return choice ? Math.min(choice, 2) : 0;
    }

    function fetchChoice(locale, choice) {
      if (!locale && typeof locale !== 'string') {
        return null;
      }
      var choices = locale.split('|');

      choice = getChoiceIndex(choice, choices.length);
      if (!choices[choice]) {
        return locale;
      }
      return choices[choice].trim();
    }

    /**
     * Vue.t
     *
     * @param {String} key
     * @param {Array} ...args
     * @return {String}
     */

    Vue.t = function (key) {
      for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        args[_key2 - 1] = arguments[_key2];
      }

      if (!key) {
        return '';
      }

      var _parseArgs = parseArgs.apply(undefined, args);

      var lang = _parseArgs.lang;
      var fallback = _parseArgs.fallback;
      var params = _parseArgs.params;

      return warnDefault(lang, key, null, translate(getAssetLocale, lang, fallback, key, params));
    };

    /**
     * Vue.tc
     *
     * @param {String} key
     * @param {number|undefined} choice
     * @param {Array} ...args
     * @return {String}
     */

    Vue.tc = function (key, choice) {
      for (var _len3 = arguments.length, args = Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
        args[_key3 - 2] = arguments[_key3];
      }

      return fetchChoice(Vue.t.apply(Vue, [key].concat(args)), choice);
    };

    /**
     * $t
     *
     * @param {String} key
     * @param {Array} ...args
     * @return {String}
     */

    Vue.prototype.$t = function (key) {
      if (!key) {
        return '';
      }

      for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
        args[_key4 - 1] = arguments[_key4];
      }

      var _parseArgs2 = parseArgs.apply(undefined, args);

      var lang = _parseArgs2.lang;
      var fallback = _parseArgs2.fallback;
      var params = _parseArgs2.params;

      var res = null;
      if (this.$options.locales) {
        res = translate(bind(getComponentLocale, this), lang, fallback, key, params);
        if (res) {
          return res;
        }
      }
      return warnDefault(lang, key, this, translate(getAssetLocale, lang, fallback, key, params));
    };

    /**
     * $tc
     *
     * @param {String} key
     * @param {number|undefined} choice
     * @param {Array} ...args
     * @return {String}
     */

    Vue.prototype.$tc = function (key, choice) {
      if (typeof choice !== 'number' && typeof choice !== 'undefined') {
        return key;
      }

      for (var _len5 = arguments.length, args = Array(_len5 > 2 ? _len5 - 2 : 0), _key5 = 2; _key5 < _len5; _key5++) {
        args[_key5 - 2] = arguments[_key5];
      }

      return fetchChoice(this.$t.apply(this, [key].concat(args)), choice);
    };

    return Vue;
  }

  var langVM = void 0; // singleton

  /**
   * plugin
   *
   * @param {Object} Vue
   * @param {Object} opts
   */

  function plugin(Vue) {
    var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

    var version = Vue.version && Number(Vue.version.split('.')[0]) || -1;

    if ('development' !== 'production' && plugin.installed) {
      warn('already installed.');
      return;
    }

    if ('development' !== 'production' && version < 1) {
      warn('vue-i18n (' + plugin.version + ') need to use vue version 1.0 or later (vue version: ' + Vue.version + ').');
      return;
    }

    var lang = 'en';
    setupLangVM(Vue, lang);

    Asset(Vue, langVM);
    Override(Vue, langVM, version);
    Config(Vue, langVM, lang);
    Extend(Vue);
  }

  function setupLangVM(Vue, lang) {
    var silent = Vue.config.silent;
    Vue.config.silent = true;
    if (!langVM) {
      langVM = new Vue({ data: { lang: lang, locales: {} } });
    }
    Vue.config.silent = silent;
  }

  plugin.version = '4.8.0';

  if (typeof window !== 'undefined' && window.Vue) {
    window.Vue.use(plugin);
  }

  return plugin;

}));