text:
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;

namespace System.IO.Compression
{
    public static partial class ZipFile
    {
        ///
        /// Opens a ZipArchive on the specified path for reading. The specified file is opened with FileMode.Open.
        ///
        ///
        /// <exception cref="ArgumentException">archiveFileName is a zero-length string, contains only whitespace, or contains one
        ///                                     or more invalid characters as defined by InvalidPathChars.</exception>
        /// <exception cref="ArgumentNullException">archiveFileName is null.</exception>
        /// <exception cref="PathTooLongException">The specified archiveFileName exceeds the system-defined maximum length.
        ///                                        For example, on Windows-based platforms, paths must be less than 248 characters,
        ///                                        and file names must be less than 260 characters.</exception>
        /// <exception cref="DirectoryNotFoundException">The specified archiveFileName is invalid, (for example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An unspecified I/O error occurred while opening the file.</exception>
        /// <exception cref="UnauthorizedAccessException">archiveFileName specified a directory.
        ///                                               -OR- The caller does not have the required permission.</exception>
        /// <exception cref="FileNotFoundException">The file specified in archiveFileName was not found.</exception>
        /// <exception cref="NotSupportedException">archiveFileName is in an invalid format. </exception>
        /// <exception cref="InvalidDataException">The specified file could not be interpreted as a Zip file.</exception>
        ///
        /// <param name="archiveFileName">A string specifying the path on the filesystem to open the archive on. The path is permitted
        /// to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory.</param>
        public static ZipArchive OpenRead(string archiveFileName) => Open(archiveFileName, ZipArchiveMode.Read);

        ///
        /// Opens a ZipArchive on the specified archiveFileName in the specified ZipArchiveMode mode.
        ///
        ///
        /// <exception cref="ArgumentException">archiveFileName is a zero-length string, contains only whitespace,
        ///                                     or contains one or more invalid characters as defined by InvalidPathChars.</exception>
        /// <exception cref="ArgumentNullException">path is null.</exception>
        /// <exception cref="PathTooLongException">The specified archiveFileName exceeds the system-defined maximum length.
        ///                                        For example, on Windows-based platforms, paths must be less than 248 characters,
        ///                                        and file names must be less than 260 characters.</exception>
        /// <exception cref="DirectoryNotFoundException">The specified archiveFileName is invalid, (for example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An unspecified I/O error occurred while opening the file.</exception>
        /// <exception cref="UnauthorizedAccessException">archiveFileName specified a directory.
        ///                                               -OR- The caller does not have the required permission.</exception>
        /// <exception cref="ArgumentOutOfRangeException">mode specified an invalid value.</exception>
        /// <exception cref="FileNotFoundException">The file specified in archiveFileName was not found. </exception>
        /// <exception cref="NotSupportedException">archiveFileName is in an invalid format.</exception>
        /// <exception cref="InvalidDataException">The specified file could not be interpreted as a Zip file.
        ///                                        -OR- mode is Update and an entry is missing from the archive or
        ///                                        is corrupt and cannot be read.
        ///                                        -OR- mode is Update and an entry is too large to fit into memory.</exception>
        ///
        /// <param name="archiveFileName">A string specifying the path on the filesystem to open the archive on.
        /// The path is permitted to specify relative or absolute path information.
        /// Relative path information is interpreted as relative to the current working directory.</param>
        /// <param name="mode">See the description of the ZipArchiveMode enum.
        /// If Read is specified, the file is opened with System.IO.FileMode.Open, and will throw
        /// a FileNotFoundException if the file does not exist.
        /// If Create is specified, the file is opened with System.IO.FileMode.CreateNew, and will throw
        /// a System.IO.IOException if the file already exists.
        /// If Update is specified, the file is opened with System.IO.FileMode.OpenOrCreate.
        /// If the file exists and is a Zip file, its entries will become accessible, and may be modified, and new entries may be created.
        /// If the file exists and is not a Zip file, a ZipArchiveException will be thrown.
        /// If the file exists and is empty or does not exist, a new Zip file will be created.
        /// Note that creating a Zip file with the ZipArchiveMode.Create mode is more efficient when creating a new Zip file.</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]  // See comment in the body.
        public static ZipArchive Open(string archiveFileName, ZipArchiveMode mode) => Open(archiveFileName, mode, entryNameEncoding: null);

        ///
        /// Opens a ZipArchive on the specified archiveFileName in the specified ZipArchiveMode mode.
        ///
        ///
        /// <exception cref="ArgumentException">archiveFileName is a zero-length string, contains only whitespace,
        ///                                     or contains one or more invalid characters as defined by InvalidPathChars.</exception>
        /// <exception cref="ArgumentNullException">path is null.</exception>
        /// <exception cref="PathTooLongException">The specified archiveFileName exceeds the system-defined maximum length.
        ///                                        For example, on Windows-based platforms, paths must be less than 248 characters,
        ///                                        and file names must be less than 260 characters.</exception>
        /// <exception cref="DirectoryNotFoundException">The specified archiveFileName is invalid, (for example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An unspecified I/O error occurred while opening the file.</exception>
        /// <exception cref="UnauthorizedAccessException">archiveFileName specified a directory.
        ///                                               -OR- The caller does not have the required permission.</exception>
        /// <exception cref="ArgumentOutOfRangeException">mode specified an invalid value.</exception>
        /// <exception cref="FileNotFoundException">The file specified in archiveFileName was not found. </exception>
        /// <exception cref="NotSupportedException">archiveFileName is in an invalid format.</exception>
        /// <exception cref="InvalidDataException">The specified file could not be interpreted as a Zip file.
        ///                                        -OR- mode is Update and an entry is missing from the archive or
        ///                                        is corrupt and cannot be read.
        ///                                        -OR- mode is Update and an entry is too large to fit into memory.</exception>
        ///
        /// <param name="archiveFileName">A string specifying the path on the filesystem to open the archive on.
        /// The path is permitted to specify relative or absolute path information.
        /// Relative path information is interpreted as relative to the current working directory.</param>
        /// <param name="mode">See the description of the ZipArchiveMode enum.
        /// If Read is specified, the file is opened with System.IO.FileMode.Open, and will throw
        /// a FileNotFoundException if the file does not exist.
        /// If Create is specified, the file is opened with System.IO.FileMode.CreateNew, and will throw
        /// a System.IO.IOException if the file already exists.
        /// If Update is specified, the file is opened with System.IO.FileMode.OpenOrCreate.
        /// If the file exists and is a Zip file, its entries will become accessible, and may be modified, and new entries may be created.
        /// If the file exists and is not a Zip file, a ZipArchiveException will be thrown.
        /// If the file exists and is empty or does not exist, a new Zip file will be created.
        /// Note that creating a Zip file with the ZipArchiveMode.Create mode is more efficient when creating a new Zip file.</param>
        /// <param name="entryNameEncoding">The encoding to use when reading or writing entry names in this ZipArchive.
        ///         ///     <para>NOTE: Specifying this parameter to values other than <c>null</c> is discouraged.
        ///         However, this may be necessary for interoperability with ZIP archive tools and libraries that do not correctly support
        ///         UTF-8 encoding for entry names.

        ///         This value is used as follows:</para>
        ///     <para>Reading (opening) ZIP archive files:</para>
        ///     <para>If <c>entryNameEncoding</c> is not specified (<c>== null</c>):</para>
        ///     <list>
        ///         <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is not set,
        ///         use the current system default code page (<c>Encoding.Default</c>) in order to decode the entry name.</item>
        ///         <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is set,
        ///         use UTF-8 (<c>Encoding.UTF8</c>) in order to decode the entry name.</item>
        ///     </list>
        ///     <para>If <c>entryNameEncoding</c> is specified (<c>!= null</c>):</para>
        ///     <list>
        ///         <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is not set,
        ///         use the specified <c>entryNameEncoding</c> in order to decode the entry name.</item>
        ///         <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is set,
        ///         use UTF-8 (<c>Encoding.UTF8</c>) in order to decode the entry name.</item>
        ///     </list>
        ///     <para>Writing (saving) ZIP archive files:</para>
        ///     <para>If <c>entryNameEncoding</c> is not specified (<c>== null</c>):</para>
        ///     <list>
        ///         <item>For entry names that contain characters outside the ASCII range,
        ///         the language encoding flag (EFS) will be set in the general purpose bit flag of the local file header,
        ///         and UTF-8 (<c>Encoding.UTF8</c>) will be used in order to encode the entry name into bytes.</item>
        ///         <item>For entry names that do not contain characters outside the ASCII range,
        ///         the language encoding flag (EFS) will not be set in the general purpose bit flag of the local file header,
        ///         and the current system default code page (<c>Encoding.Default</c>) will be used to encode the entry names into bytes.</item>
        ///     </list>
        ///     <para>If <c>entryNameEncoding</c> is specified (<c>!= null</c>):</para>
        ///     <list>
        ///         <item>The specified <c>entryNameEncoding</c> will always be used to encode the entry names into bytes.
        ///         The language encoding flag (EFS) in the general purpose bit flag of the local file header will be set if and only
        ///         if the specified <c>entryNameEncoding</c> is a UTF-8 encoding.</item>
        ///     </list>
        ///     <para>Note that Unicode encodings other than UTF-8 may not be currently used for the <c>entryNameEncoding</c>,
        ///     otherwise an <see cref="ArgumentException"/> is thrown.</para>
        /// </param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]  // See comment in the body.
        public static ZipArchive Open(string archiveFileName, ZipArchiveMode mode, Encoding entryNameEncoding)
        {
            // Relies on FileStream's ctor for checking of archiveFileName

            FileMode fileMode;
            FileAccess access;
            FileShare fileShare;

            switch (mode)
            {
                case ZipArchiveMode.Read:
                    fileMode = FileMode.Open;
                    access = FileAccess.Read;
                    fileShare = FileShare.Read;
                    break;

                case ZipArchiveMode.Create:
                    fileMode = FileMode.CreateNew;
                    access = FileAccess.Write;
                    fileShare = FileShare.None;
                    break;

                case ZipArchiveMode.Update:
                    fileMode = FileMode.OpenOrCreate;
                    access = FileAccess.ReadWrite;
                    fileShare = FileShare.None;
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(mode));
            }

            // Suppress CA2000: fs gets passed to the new ZipArchive, which stores it internally.
            // The stream will then be owned by the archive and be disposed when the archive is disposed.
            // If the ctor completes without throwing, we know fs has been successfully stores in the archive;
            // If the ctor throws, we need to close it here.

            FileStream fs = new FileStream(archiveFileName, fileMode, access, fileShare, bufferSize: 0x1000, useAsync: false);

            try
            {
                return new ZipArchive(fs, mode, leaveOpen: false, entryNameEncoding: entryNameEncoding);
            }
            catch
            {
                fs.Dispose();
                throw;
            }
        }

        ///
        ///
Creates a Zip archive at the path destinationArchiveFileName that contains the files and directories from
        /// the directory specified by sourceDirectoryName. The directory structure is preserved in the archive, and a
        /// recursive search is done for files to be archived. The archive must not exist. If the directory is empty, an empty
        /// archive will be created. If a file in the directory cannot be added to the archive, the archive will be left incomplete
        /// and invalid and the method will throw an exception. This method does not include the base directory into the archive.
        /// If an error is encountered while adding files to the archive, this method will stop adding files and leave the archive
        /// in an invalid state. The paths are permitted to specify relative or absolute path information. Relative path information
        /// is interpreted as relative to the current working directory. If a file in the archive has data in the last write time
        /// field that is not a valid Zip timestamp, an indicator value of 1980 January 1 at midnight will be used for the file's
        /// last modified time.

        ///
        ///
If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name.

        ///
        ///
Since no CompressionLevel is specified, the default provided by the implementation of the underlying compression
        /// algorithm will be used; the ZipArchive will not impose its own default.
        /// (Currently, the underlying compression algorithm is provided by the System.IO.Compression.DeflateStream class.)

        ///
        ///
        /// <exception cref="ArgumentException">sourceDirectoryName or destinationArchiveFileName is a zero-length
        ///                                     string, contains only whitespace, or contains one or more invalid characters as defined by
        ///                                     InvalidPathChars.</exception>
        /// <exception cref="ArgumentNullException">sourceDirectoryName or destinationArchiveFileName is null.</exception>
        /// <exception cref="PathTooLongException">In sourceDirectoryName or destinationArchiveFileName, the specified
        ///                                        path, file name, or both exceed the system-defined maximum length.
        ///                                        For example, on Windows-based platforms, paths must be less than 248 characters, and file
        ///                                        names must be less than 260 characters.</exception>
        /// <exception cref="DirectoryNotFoundException">The path specified in sourceDirectoryName or destinationArchiveFileName
        ///                                              is invalid, (for example, it is on an unmapped drive).
        ///                                              -OR- The directory specified by sourceDirectoryName does not exist.</exception>
        /// <exception cref="IOException">destinationArchiveFileName already exists.
        ///                                     -OR- An I/O error occurred while opening a file to be archived.</exception>
        /// <exception cref="UnauthorizedAccessException">destinationArchiveFileName specified a directory.
        ///                                               -OR- The caller does not have the required permission.</exception>
        /// <exception cref="NotSupportedException">sourceDirectoryName or destinationArchiveFileName is
        ///                                         in an invalid format.</exception>
        ///
        /// <param name="sourceDirectoryName">The path to the directory on the file system to be archived. </param>
        /// <param name="destinationArchiveFileName">The name of the archive to be created.</param>
        public static void CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName) =>
            DoCreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, compressionLevel: null, includeBaseDirectory: false, entryNameEncoding: null);

        ///
        ///
Creates a Zip archive at the path destinationArchiveFileName that contains the files and directories in the directory
        /// specified by sourceDirectoryName. The directory structure is preserved in the archive, and a recursive search is
        /// done for files to be archived. The archive must not exist. If the directory is empty, an empty archive will be created.
        /// If a file in the directory cannot be added to the archive, the archive will be left incomplete and invalid and the
        /// method will throw an exception. This method optionally includes the base directory in the archive.
        /// If an error is encountered while adding files to the archive, this method will stop adding files and leave the archive
        /// in an invalid state. The paths are permitted to specify relative or absolute path information. Relative path information
        /// is interpreted as relative to the current working directory. If a file in the archive has data in the last write time
        /// field that is not a valid Zip timestamp, an indicator value of 1980 January 1 at midnight will be used for the file's
        /// last modified time.

        ///
        ///
If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name.

        ///
        ///
Since no CompressionLevel is specified, the default provided by the implementation of the underlying compression
        /// algorithm will be used; the ZipArchive will not impose its own default.
        /// (Currently, the underlying compression algorithm is provided by the System.IO.Compression.DeflateStream class.)

        ///
        ///
        /// <exception cref="ArgumentException">sourceDirectoryName or destinationArchiveFileName is a zero-length
        ///                                     string, contains only whitespace, or contains one or more invalid characters as defined by
        ///                                     InvalidPathChars.</exception>
        /// <exception cref="ArgumentNullException">sourceDirectoryName or destinationArchiveFileName is null.</exception>
        /// <exception cref="PathTooLongException">In sourceDirectoryName or destinationArchiveFileName, the
        ///                                        specified path, file name, or both exceed the system-defined maximum length.
        ///                                        For example, on Windows-based platforms, paths must be less than 248 characters,
        ///                                        and file names must be less than 260 characters.</exception>
        /// <exception cref="DirectoryNotFoundException">The path specified in sourceDirectoryName or
        ///                                              destinationArchiveFileName is invalid, (for example, it is on an unmapped drive).
        ///                                              -OR- The directory specified by sourceDirectoryName does not exist.</exception>
        /// <exception cref="IOException">destinationArchiveFileName already exists.
        ///                               -OR- An I/O error occurred while opening a file to be archived.</exception>
        /// <exception cref="UnauthorizedAccessException">destinationArchiveFileName specified a directory.
        ///                                               -OR- The caller does not have the required permission.</exception>
        /// <exception cref="NotSupportedException">sourceDirectoryName or destinationArchiveFileName
        ///                                         is in an invalid format.</exception>
        ///
        /// <param name="sourceDirectoryName">The path to the directory on the file system to be archived.</param>
        /// <param name="destinationArchiveFileName">The name of the archive to be created.</param>
        /// <param name="compressionLevel">The level of the compression (speed/memory vs. compressed size trade-off).</param>
        /// <param name="includeBaseDirectory">true to indicate that a directory named sourceDirectoryName should
        /// be included at the root of the archive. false to indicate that the files and directories in sourceDirectoryName
        /// should be included directly in the archive.</param>
        public static void CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName, CompressionLevel compressionLevel, bool includeBaseDirectory) =>
            DoCreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, compressionLevel, includeBaseDirectory, entryNameEncoding: null);

        ///
        ///
Creates a Zip archive at the path destinationArchiveFileName that contains the files and directories in the directory
        /// specified by sourceDirectoryName. The directory structure is preserved in the archive, and a recursive search is
        /// done for files to be archived. The archive must not exist. If the directory is empty, an empty archive will be created.
        /// If a file in the directory cannot be added to the archive, the archive will be left incomplete and invalid and the
        /// method will throw an exception. This method optionally includes the base directory in the archive.
        /// If an error is encountered while adding files to the archive, this method will stop adding files and leave the archive
        /// in an invalid state. The paths are permitted to specify relative or absolute path information. Relative path information
        /// is interpreted as relative to the current working directory. If a file in the archive has data in the last write time
        /// field that is not a valid Zip timestamp, an indicator value of 1980 January 1 at midnight will be used for the file's
        /// last modified time.

        ///
        ///
If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name.

        ///
        ///
Since no CompressionLevel is specified, the default provided by the implementation of the underlying compression
        /// algorithm will be used; the ZipArchive will not impose its own default.
        /// (Currently, the underlying compression algorithm is provided by the System.IO.Compression.DeflateStream class.)

        ///
        ///
        /// <exception cref="ArgumentException">sourceDirectoryName or destinationArchiveFileName is a zero-length
        ///                                     string, contains only whitespace, or contains one or more invalid characters as defined by
        ///                                     InvalidPathChars.</exception>
        /// <exception cref="ArgumentNullException">sourceDirectoryName or destinationArchiveFileName is null.</exception>
        /// <exception cref="PathTooLongException">In sourceDirectoryName or destinationArchiveFileName, the
        ///                                        specified path, file name, or both exceed the system-defined maximum length.
        ///                                        For example, on Windows-based platforms, paths must be less than 248 characters,
        ///                                        and file names must be less than 260 characters.</exception>
        /// <exception cref="DirectoryNotFoundException">The path specified in sourceDirectoryName or
        ///                                              destinationArchiveFileName is invalid, (for example, it is on an unmapped drive).
        ///                                              -OR- The directory specified by sourceDirectoryName does not exist.</exception>
        /// <exception cref="IOException">destinationArchiveFileName already exists.
        ///                               -OR- An I/O error occurred while opening a file to be archived.</exception>
        /// <exception cref="UnauthorizedAccessException">destinationArchiveFileName specified a directory.
        ///                                               -OR- The caller does not have the required permission.</exception>
        /// <exception cref="NotSupportedException">sourceDirectoryName or destinationArchiveFileName
        ///                                         is in an invalid format.</exception>
        ///
        /// <param name="sourceDirectoryName">The path to the directory on the file system to be archived.</param>
        /// <param name="destinationArchiveFileName">The name of the archive to be created.</param>
        /// <param name="compressionLevel">The level of the compression (speed/memory vs. compressed size trade-off).</param>
        /// <param name="includeBaseDirectory">true to indicate that a directory named sourceDirectoryName should
        /// be included at the root of the archive. false to indicate that the files and directories in sourceDirectoryName
        /// should be included directly in the archive.</param>
        /// <param name="entryNameEncoding">The encoding to use when reading or writing entry names in this ZipArchive.
        ///         ///     <para>NOTE: Specifying this parameter to values other than <c>null</c> is discouraged.
        ///         However, this may be necessary for interoperability with ZIP archive tools and libraries that do not correctly support
        ///         UTF-8 encoding for entry names.

        ///         This value is used as follows while creating the archive:</para>
        ///     <para>If <c>entryNameEncoding</c> is not specified (<c>== null</c>):</para>
        ///     <list>
        ///         <item>For file names that contain characters outside the ASCII range:

        ///         The language encoding flag (EFS) will be set in the general purpose bit flag of the local file header of the corresponding entry,
        ///         and UTF-8 (<c>Encoding.UTF8</c>) will be used in order to encode the entry name into bytes.</item>
        ///         <item>For file names that do not contain characters outside the ASCII range:

        ///         the language encoding flag (EFS) will not be set in the general purpose bit flag of the local file header of the corresponding entry,
        ///         and the current system default code page (<c>Encoding.Default</c>) will be used to encode the entry names into bytes.</item>
        ///     </list>
        ///     <para>If <c>entryNameEncoding</c> is specified (<c>!= null</c>):</para>
        ///     <list>
        ///         <item>The specified <c>entryNameEncoding</c> will always be used to encode the entry names into bytes.
        ///         The language encoding flag (EFS) in the general purpose bit flag of the local file header for each entry will be set if and only
        ///         if the specified <c>entryNameEncoding</c> is a UTF-8 encoding.</item>
        ///     </list>
        ///     <para>Note that Unicode encodings other than UTF-8 may not be currently used for the <c>entryNameEncoding</c>,
        ///     otherwise an <see cref="ArgumentException"/> is thrown.</para>
        /// </param>
        public static void CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName,
                                               CompressionLevel compressionLevel, bool includeBaseDirectory, Encoding entryNameEncoding) =>
            DoCreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, compressionLevel, includeBaseDirectory, entryNameEncoding: null);

        private static void DoCreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName,
                                                  CompressionLevel? compressionLevel, bool includeBaseDirectory, Encoding entryNameEncoding)

        {
            // Rely on Path.GetFullPath for validation of sourceDirectoryName and destinationArchive

            // Checking of compressionLevel is passed down to DeflateStream and the IDeflater implementation
            // as it is a pluggable component that completely encapsulates the meaning of compressionLevel.

            sourceDirectoryName = Path.GetFullPath(sourceDirectoryName);
            destinationArchiveFileName = Path.GetFullPath(destinationArchiveFileName);

            using (ZipArchive archive = Open(destinationArchiveFileName, ZipArchiveMode.Create, entryNameEncoding))
            {
                bool directoryIsEmpty = true;

                //add files and directories
                DirectoryInfo di = new DirectoryInfo(sourceDirectoryName);

                string basePath = di.FullName;

                if (includeBaseDirectory && di.Parent != null)
                    basePath = di.Parent.FullName;

                // Windows' MaxPath (260) is used as an arbitrary default capacity, as it is likely
                // to be greater than the length of typical entry names from the file system, even
                // on non-Windows platforms. The capacity will be increased, if needed.
                const int DefaultCapacity = 260;
                char[] entryNameBuffer = ArrayPool<char>.Shared.Rent(DefaultCapacity);

                try
                {
                    foreach (FileSystemInfo file in di.EnumerateFileSystemInfos("*", SearchOption.AllDirectories))
                    {
                        directoryIsEmpty = false;

                        int entryNameLength = file.FullName.Length - basePath.Length;
                        Debug.Assert(entryNameLength > 0);

                        if (file is FileInfo)
                        {
                            // Create entry for file:
                            string entryName = ZipFileUtils.EntryFromPath(file.FullName, basePath.Length, entryNameLength, ref entryNameBuffer);
                            ZipFileExtensions.DoCreateEntryFromFile(archive, file.FullName, entryName, compressionLevel);
                        }
                        else
                        {
                            // Entry marking an empty dir:
                            DirectoryInfo possiblyEmpty = file as DirectoryInfo;
                            if (possiblyEmpty != null && ZipFileUtils.IsDirEmpty(possiblyEmpty))
                            {
                                // FullName never returns a directory separator character on the end,
                                // but Zip archives require it to specify an explicit directory:
                                string entryName = ZipFileUtils.EntryFromPath(file.FullName, basePath.Length, entryNameLength, ref entryNameBuffer, appendPathSeparator: true);
                                archive.CreateEntry(entryName);
                            }
                        }
                    }  // foreach

                    // If no entries create an empty root directory entry:
                    if (includeBaseDirectory && directoryIsEmpty)
                        archive.CreateEntry(ZipFileUtils.EntryFromPath(di.Name, 0, di.Name.Length, ref entryNameBuffer, appendPathSeparator: true));
                }
                finally
                {
                    ArrayPool<char>.Shared.Return(entryNameBuffer);
                }

            }
        }
    }
}


text:
<?php

namespace Kunstmaan\AdminListBundle\AdminList\FilterType\DBAL;

use Symfony\Component\HttpFoundation\Request;

/**
 * BooleanFilterType.
 */
class BooleanFilterType extends AbstractDBALFilterType
{
    /**
     * @param Request $request  The request
     * @param array   &$data    The data
     * @param string  $uniqueId The unique identifier
     */
    public function bindRequest(Request $request, array &$data, $uniqueId)
    {
        $data['value'] = $request->query->get('filter_value_'.$uniqueId);
    }

    /**
     * @param array  $data     The data
     * @param string $uniqueId The unique identifier
     */
    public function apply(array $data, $uniqueId)
    {
        if (isset($data['value'])) {
            switch ($data['value']) {
                case 'true':
                    $this->queryBuilder->andWhere($this->queryBuilder->expr()->eq($this->getAlias().$this->columnName, 'true'));

                    break;
                case 'false':
                    $this->queryBuilder->andWhere($this->queryBuilder->expr()->eq($this->getAlias().$this->columnName, 'false'));

                    break;
            }
        }
    }

    /**
     * @return string
     */
    public function getTemplate()
    {
        return 'KunstmaanAdminListBundle:FilterType:booleanFilter.html.twig';
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Problem 24. Order words

// Write a program that reads a list of words, separated by spaces and prints the list in an alphabetical order.

namespace P24_OrderWords
{
    using System;
    using System.Linq;

    class OrderWords
    {
        static void Main()
        {
            Console.WriteLine("Enter some text:");
            string input = Console.ReadLine();
            string[] words = input.Split(new char[] { ' ', '.', ',', '!', '?', ':', ';', '\t', '(', ')', '{', '}', '[', ']' }, StringSplitOptions.RemoveEmptyEntries);

            for (int i = 0; i < words.Length; i++)
            {
                words[i] = words[i].ToLower();
            }

            words = words.Distinct().ToArray();
            words = words.OrderBy(x => x).ToArray();

            Console.WriteLine(string.Join("\n", words));
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Mocha</title>
    <link rel="stylesheet" href="../bower_components/mocha/mocha.css">
    <link rel="shortcut icon" href="../favicon.ico">


text:
"""How To Run This Program
	1) Ensure you have Ryu installed.
	2) Save the following files to /home/ubuntu/ryu/ryu/app/Ryuretic directory
		a) Ryuretic_Intf.py
		b) Ryuretic.py
		c) Pkt_Parse13.py
		d) switch_mod13.py
	3) In your controller terminal type: cd ryu
	4) Enter PYTHONPATH=. ./bin/ryu-manager ryu/app/Ryuretic/Ryuretic_Intf_v1.py
"""
#########################################################################
from Ryuretic import coupler
#################1     Import Needed Libraries    	 1###################
#[1] Import needed libraries here                                    	#
#########################################################################
import string, random

class Ryuretic_coupler(coupler):
	def __init__(self, *args, **kwargs):
		super(Ryuretic_coupler, self).__init__(*args, **kwargs)

		############## 2     Add User Variables     2 ###################
		#[2] Add new global variables here.                             #
		#    Ex. ICMP_ECHO_REQUEST = 8, self.netView = {}               #
		#################################################################
		self.cntrl = {'mac':'ca:ca:ca:ad:ad:ad','ip':'192.168.0.40','port':None}
		self.validNAT = {'mac':'aa:aa:aa:aa:aa:aa','ip':'192.168.0.224'}
		self.t_agentIP = '192.168.0.1'
		self.t_agent = {} #Records TA parameter from respond_to_ping
		self.dns_tbl = {} #Use to redirect DNS
		self.tcp_tbl = {} #Use to redirect TCP
		self.port_mac_map = {} #Used by multi-mac detector
		self.port_AV = {} #Tracks per port Time-2-ack average
		self.tta = {}     #Tracks TCP handshake per (src,srcip,srcport,dstip)
		self.tcpConnCount = 0 #Future var for tracking total TCP connections
		self.policyTbl = {} #Tracks policies applied to port/mac
		self.netView = {} #Maps switch connections by port,mac,ip
		self.portTbl, self.macTbl, self.ipTbl = {},{},{}
		self.testIP = '0.0.0.0' #'192.168.0.22'
		#self.portTbl[9]='test'
		#self.macTbl['aa:aa:aa:aa:00:22'] = 'test'
		#self.ipTbl['192.168.0.22'] = 'test'
		#Assigns flag to MAC/Port
		self.keyID = 101
		ICMP_ECHO_REPLY = 0
		ICMP_ECHO_REQUEST = 8

    ################ 3       Proactive Rule Sets    3 ###################
    #[3] Insert proactive rules defined below. Follow format below      #
    #    Options include drop or redirect, fwd is the default.          #
    #####################################################################
	def get_proactive_rules(self, dp, parser, ofproto):
		return None, None
		#fields, ops = self.honeypot(dp, parser, ofproto)
		#return fields, ops

    ################# 4     Reactive Rule Sets    4 #####################
    #[4] use below handles to direct packets to reactive user modules   #
    #    defined in location #[5]. If no rule is added, then            #
    #    the default self.default_Fields_Ops(pkt) must be used          #
    #####################################################################
    # Determine highest priority fields and ops pair, if needed         #
    # xfields = [fields0, fields1, fields2]                             #
    # xops = [ops0, ops1, ops2]                                         #
    # fields,ops = self._build_FldOps(xfields,xops)                     #
    #####################################################################
	def handle_eth(self,pkt):
		print "Handle Ether: ", pkt['srcmac'],'->',pkt['dstmac']
		fields, ops = self.default_Field_Ops(pkt)
		self.install_field_ops(pkt,fields,ops)

	#def handle_arp(self,pkt):
		#print "-------------------------------------------------------------"
		#print "Handle ARP: ",pkt['srcmac'],"->",pkt['dstmac']
		#print "Handle ARP: ",pkt['srcip'],"->",pkt['dstip']
		#fields, ops = self.respond_to_arp(pkt)
		##Determin if mac or port has a status
		##pkt_status = self.check_net_tbl(pkt['srcmac'],pkt['inport'])
		##print pkt_status
		#self.install_field_ops(pkt,fields,ops)

	def handle_arp(self,pkt):
		print "-------------------------------------------------------------"
		print "Handle ARP: ",pkt['srcmac'],"->",pkt['dstmac']
		print "Handle ARP: ",pkt['srcip'],"->",pkt['dstip']
		fields, ops = self.respond_to_arp(pkt)
		self.install_field_ops(pkt,fields,ops)

	def handle_ip(self,pkt):
		print "-------------------------------------------------------------"
 		print "Handle IP"
		#fields, ops = self.TTL_Check(pkt) #Lab 9
		fields, ops = self.default_Field_Ops(pkt)
		self.install_field_ops(pkt,fields,ops)

	def handle_icmp(self,pkt):
		print "-------------------------------------------------------------"
		print "Handle ICMP: ",pkt['srcmac'],"->",pkt['dstmac']
		print "Handle ICMP: ",pkt['srcip'],"->",pkt['dstip']
		fields,ops = self.respond_to_ping(pkt)
		self.install_field_ops(pkt, fields, ops)

	def handle_tcp(self,pkt):
		#print "-------------------------------------------------------------"
		#print "Handle TCP: ",pkt['srcmac'],"->",pkt['dstmac']
		#print "Handle TCP: ",pkt['srcip'],"->",pkt['dstip']
		#print "Handle TCP: ",pkt['srcport'],"->",pkt['dstport']
		pkt_status = self.check_ip_tbl(pkt)
		if pkt_status == 'test': #test src and dest
			fields,ops = self.redirect_TCP(pkt)
		elif pkt_status == 'deny':
			fields,ops = self.redirect_TCP(pkt)
		else:
			#fields,ops = self.default_Field_Ops(pkt)
			#fields,ops = self.test_TCP(pkt)
			fields,ops = self.TTA_analysis(pkt)
		self.install_field_ops(pkt, fields, ops)

	def test_TCP(self,pkt):
		fields,ops = self.default_Field_Ops(pkt)
		if pkt['srcip'] == self.testIP:
			print "IP detected: ", pkt['srcip']
			self.flagHost(pkt,'test')
			fields,ops=self.redirect_TCP(pkt)
			return fields,ops
		return fields,ops

	def redirect_TCP(self,pkt):
		print "Redirect_TCP: "
		print "pkt info: ", pkt['srcmac'],' ',pkt['dstmac'],' ',pkt['srcip'],' ',pkt['dstip']
		print pkt['srcport'],' ',pkt['dstport']
		#Uses ipTbl, tcp_tbl, and t_agent
		fields,ops = self.default_Field_Ops(pkt)

		if self.ipTbl.has_key(pkt['srcip']):
			if self.ipTbl[pkt['srcip']] in ['test','deny']:
				print "ipTbl Contents", self.ipTbl
				key = (pkt['srcip'],pkt['srcport'])
				print "Key is : ", key
				self.tcp_tbl[key] = {'dstip':pkt['dstip'],'dstmac':pkt['dstmac'],
						 'dstport':pkt['dstport']}
				fields.update({'srcmac':pkt['srcmac'],'srcip':pkt['srcip']})
				fields.update({'dstmac':self.t_agent['mac'],'dstip':self.t_agent['ip']})
				#if pkt['dstport'] == 443:
					#fields['dstport'] = 80
				ops = {'hard_t':None, 'idle_t':None, 'priority':100,\
					'op':'mod', 'newport':self.t_agent['port']}
				print "TCP Table: ", self.tcp_tbl[key]

		elif self.ipTbl.has_key(pkt['dstip']):
			print "Returning to ", pkt['dstip']
			if self.ipTbl[pkt['dstip']] in ['test','deny']:
				print "ipTbl Contents", self.ipTbl
				key = (pkt['dstip'],pkt['dstport'])
				print "Key and table: ", key, ' ', self.tcp_tbl[key]
				fields.update({'srcmac':self.tcp_tbl[key]['dstmac'],
				   'srcip':self.tcp_tbl[key]['dstip']})
				#if self.tcp_tbl[key]['dstport'] == 443:
					#fields.update({'srcport':443})
				fields.update({'dstmac':pkt['dstmac'], 'dstip':pkt['dstip']})
				ops = {'hard_t':None, 'idle_t':None, 'priority':100,\
					'op':'mod', 'newport':None}
				#self.tcp_tbl.pop(key)
				#print "TCP Table: ", self.tcp_tbl
		return fields, ops

	# Add flag to policyTbl, macTbl, portTbl
	def flagHost(self,pkt,flag):
		print 'Flag Host: ', pkt['srcmac'],'->',flag
		self.macTbl[pkt['srcmac']]={'stat':flag,'port':pkt['inport'],
							  'ip':pkt['srcip']}
		self.portTbl[pkt['inport']]=flag
		self.ipTbl[pkt['srcip']] = flag
		if flag != 'norm':
			keyID = self.keyID
			self.keyID += 1
			#create passkey
			passkey =''.join(random.choice(string.ascii_letters) for x in range(8))
			#update policy table
			self.policyTbl[keyID]={'inport':pkt['inport'],'srcmac':pkt['srcmac'],
								   'ip':pkt['srcip'],'passkey':passkey,'stat':flag}

			#Notify trusted agent of newly flagged client
			self.update_TA(pkt, keyID, 'l')  #load message'

	def handle_udp(self,pkt):
		print "-------------------------------------------------------------"
		print "Handle UDP: ",pkt['srcmac'],"->",pkt['dstmac']
		print "Handle UDP: ",pkt['srcip'],'->',pkt['dstip']
		#Added to build MAC and port associations
		pkt_status = self.check_ip_tbl(pkt)
		if pkt_status == 'test': #test src and dest
			fields,ops = self.redirect_DNS(pkt)
		elif pkt_status == 'deny':
			fields,ops = self.redirect_DNS(pkt)
		else:
			fields,ops = self.test_DNS(pkt)
		self.install_field_ops(pkt, fields, ops)

	def test_DNS(self,pkt):
		print "Testing DNS"
		fields,ops = self.default_Field_Ops(pkt)
		if pkt['srcip'] == self.testIP:
			print "IP detected: ", pkt['srcip']
			self.flagHost(pkt,'test')
			fields,ops=self.redirect_DNS(pkt)
			return fields,ops
		return fields,ops

	def redirect_DNS(self,pkt):
		print "Redirect_DNS: "
		#Uses macTbl, dns_tbl, and t_agent
		fields,ops = self.default_Field_Ops(pkt)
		if self.ipTbl.has_key(pkt['srcip']):
			if self.ipTbl[pkt['srcip']]== 'test':
				key = (pkt['srcip'],pkt['srcport'])
				print key
				self.dns_tbl[key] = {'dstip':pkt['dstip'],'dstmac':pkt['dstmac']}
				fields.update({'dstmac':self.t_agent['mac'],
				   'dstip':self.t_agent['ip']})
				fields.update({'srcmac':pkt['srcmac'],'srcip':pkt['srcip']})
				ops = {'hard_t':None, 'idle_t':None, 'priority':100,\
					'op':'mod', 'newport':self.t_agent['port']}
		elif self.ipTbl.has_key(pkt['dstip']):
			if self.ipTbl[pkt['dstip']]== 'test':
				key = (pkt['dstip'],pkt['dstport'])
				print key
				fields.update({'srcmac':self.dns_tbl[key]['dstmac'],
				   'srcip':self.dns_tbl[key]['dstip']})
				fields.update({'dstmac':pkt['dstmac'], 'dstip':pkt['dstip']})
				ops = {'hard_t':None, 'idle_t':None, 'priority':100,\
					'op':'mod', 'newport':None}
				#self.dns_tbl.pop(key)
				#print "DNS Table: ", self.dns_tbl
		return fields, ops

	#Check status of port and mac.
	def check_ip_tbl(self,pkt):
		#print "Check_ip_tbl:"
		srcip,dstip = pkt['srcip'],pkt['dstip']
		if self.ipTbl.has_key(srcip):
			#print "Found: ", srcip,'->', self.ipTbl[srcip]
			return self.ipTbl[srcip]
		elif self.ipTbl.has_key(dstip):
			#print "Found: ", dstip,'->', self.ipTbl[dstip]
			return self.ipTbl[dstip]
		else:
			#print "Not Found: ", srcip, ', ', dstip
			return 'No_Flag'

	# All packets not defined above are handled here.
	def handle_unk(self,pkt):
		print "-------------------------------------------------------------"
		print "Handle Uknown"
		fields, ops = self.default_Field_Ops(pkt)
		self.install_field_ops(pkt, fields, ops)

	######################################################################
	# The following are from the old NFG file.
	def default_Field_Ops(self,pkt):
		def _loadFields(pkt):
			#keys specifies match fields for action. Default is
			#inport and srcmac. ptype used for craft icmp, udp, etc.
			fields = {'keys':['inport','srcmac'],'ptype':[], 'dp':pkt['dp'],
                      'ofproto':pkt['ofproto'], 'msg':pkt['msg'],
                      'inport':pkt['inport'], 'srcmac':pkt['srcmac'],
                      'ethtype':pkt['ethtype'], 'dstmac':None, 'srcip':None,
                      'proto':None, 'dstip':None, 'srcport':None, 'dstport':None,
                      'com':None, 'id':0}
			return fields

		def _loadOps():
			#print "Loading ops"
			#Specifies the timeouts, priority, operation and outport
			#options for op: 'fwd','drop', 'mir', 'redir', 'craft'
			ops = {'hard_t':None, 'idle_t':None, 'priority':10, \
                   'op':'fwd', 'newport':None}
			return ops

		#print "default Field_Ops called"
		fields = _loadFields(pkt)
		ops = _loadOps()
		return fields, ops
	######################################################################
	############ 5  Ryuretic Network Application Modules  5 ##############
	#[5] Add user created methods below. Examples are provided to assist #
	# the user with basic python, dictionary, list, and function calls   #
	######################################################################
	# Confirm mac has been seen before and no issues are recorded
	def TTL_Check(self, pkt):
		#initialize fields and ops with default settings
		fields, ops = self.default_Field_Ops(pkt)
		if pkt['srcmac'] != self.validNAT['mac']:
			if pkt['ttl']==63 or pkt['ttl']==127:
				print 'TTL Decrement Detected on ',pkt['srcmac'],' TTL is :',pkt['ttl']
				fields, ops = self.add_drop_params(pkt,fields,ops)
			else:
				ops['idle_t'] = 5
			print "Packet TTL: ", pkt['ttl'], '  ', pkt['srcip'],' ', \
				  pkt['inport'],' ', pkt['srcmac']
		else:
			ops['idle_t'] = 20
			priority = 10
		return fields, ops

	def Multi_MAC_Checker(self, pkt):
		fields, ops = self.default_Field_Ops(pkt)
		print "*** Checking MAC ***"
		#self.port_mac_map = {}
		if self.port_mac_map.has_key(pkt['inport']):
			if pkt['srcmac'] != self.port_mac_map[pkt['inport']]:
				print " Multi-mac port detected "
				fields, ops = self.add_drop_params(pkt,fields,ops)
			else:
				fields, ops = self.fwd_persist(pkt,fields,ops)
		else:
			self.port_mac_map[pkt['inport']] = pkt['srcmac']
		return fields, ops

	#change name to monitor_TCP for RAP
	def TTA_analysis(self,pkt):
		fields, ops = self.default_Field_Ops(pkt)
		bits = pkt['bits']
		dst, dstip, dstport = pkt['dstmac'], pkt['dstip'], pkt['dstport']
		src, srcip, srcport = pkt['srcmac'], pkt['srcip'], pkt['srcport']
		inport = pkt['inport']
		send = (src,srcip,srcport,dstip)
		arrive = (dst,dstip,dstport,srcip)
		t_in = pkt['t_in']

		#print"*****\n"+self.tta+"/n******/n"+self.port_AV+"/n*****"

		if bits == 20:
			if self.tta.has_key(send):
				self.tta[send]['stage'] = 0
			elif self.tta.has_key(arrive):
				#print pkt
				self.tta[arrive]['stage'] = 0
			return fields, ops

		if bits == 2:
			if self.tta.has_key(send):
				self.tta[send].update({'inport':inport,'stage':1})
			else:
				self.tta.update({send:{'inport':inport,'stage':1}})
			return fields, ops

		if bits == 18:
			if self.tta.has_key(arrive):
				if self.tta[arrive]['stage']==1:
					self.tta[arrive].update({'syn':t_in,'stage':2})
			return fields,ops

		if bits == 16:
			if self.tta.has_key(send):
				if self.tta[send]['stage']==2:
					tta = t_in - self.tta[send]['syn']
					self.tta[send].update({'stage':3, 'ack':t_in, 'tta':tta})
					#print '** Calc TTA :', tta
					if self.port_AV.has_key(self.tta[send]['inport']):
						portAV = ((self.port_AV[self.tta[send]['inport']] * \
								   9) + tta)/10
						self.port_AV[self.tta[send]['inport']] = portAV
					else:
						portAV = ((0.001*9)+tta)/10
						self.port_AV.update({self.tta[send]['inport']:portAV})
					#print "****"
					#print "Port and TTA: ", inport, self.tta[send]['tta']
					print '****\nPort Averages: ', self.port_AV, '\n****'
					#print "****"
					del self.tta[send]
					return fields, ops
			#print "Persist"
			fields, ops = self.tcp_persist(pkt,fields,ops)
			return fields, ops

		if bits == 24:
			#print "HTTP Push"
			return fields, ops

		if bits == 17:
			print 'Port Averages: ', self.port_AV
			if self.tta.has_key(send):
				del self.tta[send]
			elif self.tta.has_key(arrive):
				del self.tta[arrive]
			return fields, ops

		print "Packet not addressed", bits, inport, src, dstip

		return fields, ops

	# Call to temporarily install drop parameter for a packet to switch
	def add_drop_params(self, pkt, fields, ops):
		#may need to include priority
		fields['keys'] = ['inport']
		fields['inport'] = pkt['inport']
		ops['priority'] = 100
		ops['idle_t'] = 60
		ops['op']='drop'
		return fields, ops

	# Call to temporarily install TCP flow connection on switch
	def tcp_persist(self, pkt,fields,ops):
		#print "TCP_Persist: ", pkt['srcmac'],'->', pkt['dstmac']
		#print "TCP_Persist: ", pkt['srcip'],'->',pkt['dstip']
		fields['keys'] = ['inport', 'srcmac', 'srcip', 'ethtype', 'srcport']
		fields['srcport'] = pkt['srcport']
		fields['srcip'] = pkt['srcip']
		ops['idle_t'] = 5
		ops['priority'] = 10
		return fields, ops

	def fwd_persist(self, pkt,fields,ops):
		ops['idle_t'] = 3
		ops['priority'] = 10
		return fields, ops

	def arp_persist(self, pkt):
		fields, ops = self.default_Field_Ops(pkt)
		fields['keys'] = ['inport','srcmac','ethtype']
		ops['idle_t'] = 10
		ops['priority'] = 2
		return fields, ops

	################################################################
	"""
	The following code is implemented to allow the trusted agent to comm
	with the controller and vice versa.
	"""
	################################################################
	#Receive and respond to arp
	def respond_to_arp(self,pkt):
		print 'Respond to Arp:', pkt['srcmac'],'->',pkt['dstmac']
		print 'Respond to Arp:', pkt['srcip'],'->',pkt['dstip']
		fields, ops = self.default_Field_Ops(pkt)
		#Added to build MAC and port associations
		if not self.macTbl.has_key(pkt['srcmac']):
			self.macTbl[pkt['srcmac']] = {'port':pkt['inport'], 'stat':'unk'}
		if pkt['dstip'] == self.cntrl['ip']:
			print "Message to Controller"
			fields['keys']=['srcmac', 'srcip', 'ethtype', 'inport']
			fields['ptype'] = 'arp'
			fields['dstip'] = pkt['srcip']
			fields['srcip'] = self.cntrl['ip']
			fields['dstmac'] = pkt['srcmac']
			fields['srcmac'] = self.cntrl['mac']
			fields['ethtype'] = 0x0806
			ops['op'] = 'craft'
			ops['newport'] = pkt['inport']
			#print "INPORT: ", pkt['inport']
		return fields, ops

	#Respond to ping. Forward or respond if to cntrl from trusted agent.
	def respond_to_ping(self,pkt):
		def get_fields(keyID):
			srcmac = self.policyTbl[keyID]['srcmac']
			inport = self.policyTbl[keyID]['inport']
			srcip = self.policyTbl[keyID]['ip']
			print inport, ', ', srcmac, ', ', srcip
			return srcmac, inport, srcip

		def remove_keyID(keyID):
			print "Policy Table Contents: ", self.policyTbl
			if self.policyTbl.has_key(keyID):
				srcmac, inport, srcip = get_fields(keyID)
				if self.macTbl.has_key(srcmac):
					print "Removing MAC", srcmac
					self.macTbl.pop(srcmac)
				if self.portTbl.has_key(inport):
					print "Removing Port", inport
					self.portTbl.pop(inport)
				if self.ipTbl.has_key(srcip):
					print "Removing IP", srcip
					self.ipTbl.pop(srcip)
				self.policyTbl.pop(keyID)

		print "Respond to Ping: ", pkt['srcmac'],'->',pkt['dstmac']
		fields, ops = self.default_Field_Ops(pkt)
		if pkt['dstip'] == self.cntrl['ip'] and pkt['srcip'] == self.t_agentIP:
			#print'respond to ping'
			rcvData = pkt['data'].data
			#Actions {a-acknowledge, i-init, d-delete, r-result, v-verify}
			#action, keyID = rcvData.split(',')
			#keyID = keyID.rstrip(' \t\r\n\0')
			print rcvData
			try:
				action, keyID, result = rcvData.split(',')
				result = result.rstrip(' \t\r\n\0')
				print "Received Result"
			except:
				action, keyID = rcvData.split(',')
				print "Received Revocation."
			keyID = keyID.rstrip(' \t\r\n\0')
			print "Key ID Length: ", len(keyID)
			keyID = int(keyID)
			print "KeyID is ", keyID, ', ', type(keyID)
			print "Action is ", action, "\n\n\n*********"
			######################################################
			if action == 'i':
				self.t_agent = {'ip':pkt['srcip'],'mac':pkt['srcmac'],
								  'port':pkt['inport'],'msg':pkt['msg'],
								  'ofproto':pkt['ofproto'], 'dp':pkt['dp']}
				print "T_AGENT Loaded"
			elif action == 'd':
				#Deleting flagged host policy
				print "Removing (",keyID,") from Policy Table"
				print "Existing Keys: ", self.policyTbl.keys()
				remove_keyID(keyID)
			elif action == 'r':
				print "Validating result"
				print "Key present?", self.policyTbl.has_key(keyID)
				if self.policyTbl.has_key(keyID):
					print "Test Result is: ", result
					if result == 'P':
						print "Removing keyID"
						remove_keyID(keyID)
					elif result =='F':
						print "Flagging Host: ", self.policyTbl[keyID]['ip']
						self.policyTbl[keyID]['stat'] = 'deny'
						srcmac, inport, srcip = get_fields(keyID)
						self.macTbl[srcmac].update({'stat':'deny'})
						self.portTbl[inport],self.ipTbl[srcip] ='deny','deny'
						self.update_TA(pkt, keyID,'e') #send edit message
						#Notify TA of update_TA(self,pkt, keyID)
					else:
						print "An Error Occured"
			elif action is 'u':
				#This is more complicated it requires data not being stored
				#may need to add fields to policyTable. Maybe not.
				pass
			elif action is 'a':
				#Acknowledge receipt
				pass
			else:
				print "No match"
			fields.update({'srcmac':self.cntrl['mac'], 'dstmac':pkt['srcmac']})
			fields.update({'srcip':self.cntrl['ip'], 'dstip':pkt['srcip']})
			fields.update({'ptype':'icmp','ethtype':0x0800, 'proto':1})
			fields['com'] = 'a,'+rcvData
			ops.update({'op':'craft', 'newport':pkt['inport']})
		return fields, ops

	#Crafts tailored ICMP message for trusted agent
	def update_TA(self,pkt, keyID, message):
		table = self.policyTbl[keyID]
		print 'Update Table: ', pkt['srcmac'],'->',keyID,'->',table['stat']
		print 'Update Table: ', table['srcmac'],'->',keyID,'->',table['stat']
		#print "Updating Trusted Agent"
		fields, ops = {},{}
		fields['keys'] = ['inport', 'srcip']
		fields.update({'dstip':self.t_agent['ip'], 'srcip':self.cntrl['ip']})
		fields.update({'dstmac':self.t_agent['mac'], 'srcmac':self.cntrl['mac']})
		fields.update({'dp':self.t_agent['dp'], 'msg':self.t_agent['msg']})
		fields.update({'inport':self.t_agent['port'],'ofproto':\
			self.t_agent['ofproto']})
		fields.update({'ptype':'icmp', 'ethtype':0x0800, 'proto':1, 'id':0})
		fields['com'] = message+','+table['srcmac']+','+str(table['inport'])+\
						','+str(table['passkey'])+','+table['stat']+\
						','+str(keyID)
		ops = {'hard_t':None, 'idle_t':None, 'priority':0, \
				   'op':'craft', 'newport':self.t_agent['port']}
		self.install_field_ops(pkt, fields, ops)

	################################################################
	"""
	The following code controls the redirection of packets from their intended
	destination to our trusted agent. This occurs when a port is flagged.
	"""
	################################################################
	#Create a method to inject a redirect anytime the sta4 IP address is

	#Check status of port and mac.
	def check_net_tbl(self,pkt):
		mac, ip, port = pkt['srcmac'], pkt['srcip'], pkt['inport']
		print "(536) Check NetTbl: ", mac, ' & ', port,'->',self.macTbl.keys()
		if mac in self.macTbl.keys():
			#print "Found: ", mac,'->', self.macTbl[mac]['stat']
			return self.macTbl[mac]['stat']
		elif port in self.portTbl.keys():
			#print "Port ", port, " found in table."
			return self.portTbl[port]
		elif ip in self.ipTbl.keys():
			#print "IP ", ip, " found in table."
			return self.ipTbl[ip]
		else:
			#print "Not Found: ", mac
			return 'new'

	#Redirect ICMP packets to trusted agent
	def Icmp_Redirect(self,pkt):
		print "Redirecting ICMP", pkt['srcmac'],'->',pkt['dstmac'],'||',self.t_agent['mac']
		fields, ops = self.default_Field_Ops(pkt)
		fields['keys'] = ['inport', 'ethtype']
		fields['dstmac'] = self.t_agent['mac']
		fields['dstip'] = self.t_agent['ip']
		fields['ethtype'] = pkt['ethtype']
		ops['op'] = 'redir'
		ops['newport'] = self.t_agent['port']
		ops['priority'] = 100
		ops['idle_t'] = 180
		#ops['hard_t'] = 180
		return fields, ops


text:
def foo(x):
    """
    :type x: collections.MutableMapping
    :rtype: dict
    """
    return {v: k for k, v in x.iteritems()}

d = dict(a=1, b=2)
foo(d)

l = [i for i in range(10)]
foo(<warning descr="Expected type 'MutableMapping', got 'List[int]' instead">l</warning>)


text:
'''The app module, containing the app factory function.'''
from flask import Flask, render_template

from news_serve.settings import ProdConfig
from news_serve.assets import assets
from news_serve.extensions import (
    bcrypt,
    cache,
    db,
    login_manager,
    migrate,
    debug_toolbar,
)
from news_serve import public, user, admin, story, translation, recording
from flask.ext.admin.contrib.sqla import ModelView
from .admin.views import CatsView, MyModelView, MyHomeView
from flask.ext.admin import Admin
from news_serve.user.models import User
from news_serve.story.models import Story
from news_serve.util.models import Language, Tag
from news_serve.translation.models import Translation
from news_serve.recording.models import Recording

def create_app(config_object=ProdConfig):
    '''An application factory, as explained here:
        http://flask.pocoo.org/docs/patterns/appfactories/

    :param config_object: The configuration object to use.
    '''
    app = Flask(__name__)
    app.config.from_object(config_object)
    register_extensions(app)
    register_blueprints(app)
    register_errorhandlers(app)
    return app

def register_extensions(app):
    assets.init_app(app)
    bcrypt.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    debug_toolbar.init_app(app)
    migrate.init_app(app, db)

    # flask-admin
    amin = Admin(app,index_view=MyHomeView())
    amin.add_view(MyModelView(User, db.session))
    amin.add_view(CatsView(name='Cats'))
    amin.add_view(MyModelView(Story, db.session))
    amin.add_view(MyModelView(Translation, db.session))
    amin.add_view(MyModelView(Recording, db.session))
    amin.add_view(MyModelView(Language, db.session))
    amin.add_view(MyModelView(Tag, db.session))
    return None
    import pdb; pdb.set_trace()  # XXX BREAKPOINT

def register_blueprints(app):
    app.register_blueprint(public.views.blueprint)
    app.register_blueprint(user.views.blueprint)
    app.register_blueprint(story.views.story_blueprint)
    app.register_blueprint(recording.views.blueprint)
    app.register_blueprint(translation.views.translation_blueprint)
    return None

def register_errorhandlers(app):
    def render_error(error):
        # If a HTTPException, pull the `code` attribute; default to 500
        error_code = getattr(error, 'code', 500)
        return render_template("{0}.html".format(error_code)), error_code
    for errcode in [401, 404, 500]:
        app.errorhandler(errcode)(render_error)
    return None


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.videoanalyzer.generated;

import com.azure.core.util.Context;

/** Samples for PipelineJobs Delete. */
public final class PipelineJobsDeleteSamples {
    /*
     * x-ms-original-file: specification/videoanalyzer/resource-manager/Microsoft.Media/preview/2021-11-01-preview/examples/pipeline-job-delete.json
     */
    /**
     * Sample code: Deletes a pipeline job.
     *
     * @param manager Entry point to VideoAnalyzerManager.
     */
    public static void deletesAPipelineJob(com.azure.resourcemanager.videoanalyzer.VideoAnalyzerManager manager) {
        manager.pipelineJobs().deleteWithResponse("testrg", "testaccount2", "pipelineJob1", Context.NONE);
    }
}


text:
#include <chrono>
#include <fstream>
#include <mutex>
#include <thread>
#include <type_traits>

#include "TestUtilBundleListener.h"
#include "TestUtils.h"
#include "cppmicroservices/Bundle.h"
#include "cppmicroservices/BundleContext.h"
#include "cppmicroservices/BundleEvent.h"
#include "cppmicroservices/Constants.h"
#include "cppmicroservices/Framework.h"
#include "cppmicroservices/FrameworkEvent.h"
#include "cppmicroservices/FrameworkFactory.h"
#include "cppmicroservices/util/FileSystem.h"
#include "gtest/gtest.h"

#ifdef US_PLATFORM_POSIX
#  include <dlfcn.h>
#endif

using namespace cppmicroservices;
using cppmicroservices::testing::File;
using cppmicroservices::testing::GetTempDirectory;
using cppmicroservices::testing::MakeUniqueTempDirectory;
using cppmicroservices::testing::TempDir;

#if !defined(__clang__) && defined(__GNUC__)
#  define US_GCC_VER                                                           \
    (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#endif

// TODO: Remove all occurences of US_TYPE_OPERATIONS_AVAILABLE macro
// once the minimum GCC compiler required is 4.7 or above
#if defined(US_GCC_VER) && (US_GCC_VER < 40700)
#  define US_TYPE_OPERATIONS_AVAILABLE 0
#else
#  define US_TYPE_OPERATIONS_AVAILABLE 1
#endif

TEST(FrameworkTest, Ctor)
{
#if US_TYPE_OPERATIONS_AVAILABLE
  ASSERT_FALSE(std::is_default_constructible<Framework>::value);
  ASSERT_TRUE((std::is_constructible<Framework, Bundle>::value));
#endif
  //Bundle b;
  //ASSERT_THROW(Framework(Bundle(b)), std::logic_error); This causes a crash. TODO: Fix crash and uncomment this line.

  auto f = FrameworkFactory().NewFramework();
  ASSERT_TRUE(f);
  f.Start();
#if defined(US_BUILD_SHARED_LIBS)
  auto bundle =
    cppmicroservices::testing::InstallLib(f.GetBundleContext(), "TestBundleA");
#else
  auto bundle =
    cppmicroservices::testing::GetBundle("TestBundleA", f.GetBundleContext());
#endif
  ASSERT_THROW(auto f1 = Framework(Bundle(bundle)), std::logic_error);
}

TEST(FrameworkTest, MoveCtor)
{
#if US_TYPE_OPERATIONS_AVAILABLE
  ASSERT_TRUE(std::is_move_constructible<Framework>::value);
#endif
  auto f = FrameworkFactory().NewFramework();
  ASSERT_TRUE(f);
  f.Start();
  ASSERT_EQ(f.GetState(), Bundle::STATE_ACTIVE);
  Framework f1(std::move(f));
  ASSERT_EQ(f1.GetState(), Bundle::STATE_ACTIVE);
}

TEST(FrameworkTest, MoveAssign)
{
#if US_TYPE_OPERATIONS_AVAILABLE
  ASSERT_TRUE(std::is_move_assignable<Framework>::value);
#endif
  auto f = FrameworkFactory().NewFramework();
  ASSERT_TRUE(f);
  f.Start();
  ASSERT_EQ(f.GetState(), Bundle::STATE_ACTIVE);
  Framework f1 = FrameworkFactory().NewFramework();
  ASSERT_TRUE(f1);
  ASSERT_EQ(f1.GetState(), Bundle::STATE_INSTALLED);
  f1 = std::move(f);
  ASSERT_EQ(f1.GetState(), Bundle::STATE_ACTIVE);
}

TEST(FrameworkTest, CopyCtor)
{
#if US_TYPE_OPERATIONS_AVAILABLE
  ASSERT_TRUE(std::is_copy_constructible<Framework>::value);
#endif
  auto f = FrameworkFactory().NewFramework();
  ASSERT_TRUE(f);
  f.Start();
  ASSERT_EQ(f.GetState(), Bundle::STATE_ACTIVE);
  Framework f1(f);
  ASSERT_EQ(f1.GetState(), Bundle::STATE_ACTIVE);
  f1.Stop();
  f1.WaitForStop(std::chrono::milliseconds::zero());
  ASSERT_NE(f1.GetState(), Bundle::STATE_ACTIVE);
  ASSERT_EQ(f.GetState(), f1.GetState());
}

TEST(FrameworkTest, CopyAssign)
{
#if US_TYPE_OPERATIONS_AVAILABLE
  ASSERT_TRUE(std::is_copy_assignable<Framework>::value);
#endif
  auto f = FrameworkFactory().NewFramework();
  ASSERT_TRUE(f);
  f.Start();
  ASSERT_EQ(f.GetState(), Bundle::STATE_ACTIVE);
  Framework f1 = FrameworkFactory().NewFramework();
  ASSERT_TRUE(f1);
  ASSERT_EQ(f1.GetState(), Bundle::STATE_INSTALLED);
  f1 = f;
  ASSERT_EQ(f1.GetState(), Bundle::STATE_ACTIVE);
  f1.Stop();
  f1.WaitForStop(std::chrono::milliseconds::zero());
  ASSERT_NE(f1.GetState(), Bundle::STATE_ACTIVE);
  ASSERT_EQ(f.GetState(), f1.GetState());
}

TEST(FrameworkTest, DefaultConfig)
{
  auto f = FrameworkFactory().NewFramework();
  ASSERT_TRUE(f);

  f.Start();

  auto ctx = f.GetBundleContext();

  // Default framework properties:
  //  - threading model: multi
  //  - persistent storage location: The current working directory
  //  - diagnostic logging: off
  //  - diagnostic logger: std::clog
#ifdef US_ENABLE_THREADING_SUPPORT
  ASSERT_EQ(ctx.GetProperty(Constants::FRAMEWORK_THREADING_SUPPORT).ToString(),
            "multi");
#else
  ASSERT_EQ(ctx.GetProperty(Constants::FRAMEWORK_THREADING_SUPPORT).ToString(),
            "single");
#endif
  ASSERT_EQ(ctx.GetProperty(Constants::FRAMEWORK_STORAGE),
            std::string("fwdir"));
  ASSERT_FALSE(cppmicroservices::any_cast<bool>(
    ctx.GetProperty(Constants::FRAMEWORK_LOG)));

  ASSERT_EQ(ctx.GetProperty(Constants::FRAMEWORK_WORKING_DIR),
            util::GetCurrentWorkingDirectory());
}

TEST(FrameworkTest, CustomConfiguration)
{
  FrameworkConfiguration configuration;
  configuration["org.osgi.framework.security"] = std::string("osgi");
  configuration["org.osgi.framework.startlevel.beginning"] = 0;
  configuration["org.osgi.framework.bsnversion"] = std::string("single");
  configuration["org.osgi.framework.custom1"] = std::string("foo");
  configuration["org.osgi.framework.custom2"] = std::string("bar");
  configuration[Constants::FRAMEWORK_LOG] = true;
  configuration[Constants::FRAMEWORK_STORAGE] = GetTempDirectory();
  configuration[Constants::FRAMEWORK_WORKING_DIR] = GetTempDirectory();

  // the threading model framework property is set at compile time and read-only at runtime. Test that this
  // is always the case.
#ifdef US_ENABLE_THREADING_SUPPORT
  configuration[Constants::FRAMEWORK_THREADING_SUPPORT] = std::string("single");
#else
  configuration[Constants::FRAMEWORK_THREADING_SUPPORT] = std::string("multi");
#endif

  auto f = FrameworkFactory().NewFramework(configuration);
  ASSERT_TRUE(f);

  ASSERT_NO_THROW(f.Start(););

  auto ctx = f.GetBundleContext();

  ASSERT_EQ("osgi", ctx.GetProperty("org.osgi.framework.security").ToString());
  ASSERT_EQ(
    0,
    any_cast<int>(ctx.GetProperty("org.osgi.framework.startlevel.beginning")));
  ASSERT_EQ(
    "single",
    any_cast<std::string>(ctx.GetProperty("org.osgi.framework.bsnversion")));
  ASSERT_EQ(
    "foo",
    any_cast<std::string>(ctx.GetProperty("org.osgi.framework.custom1")));
  ASSERT_EQ(
    "bar",
    any_cast<std::string>(ctx.GetProperty("org.osgi.framework.custom2")));
  ASSERT_EQ(any_cast<bool>(ctx.GetProperty(Constants::FRAMEWORK_LOG)), true);
  ASSERT_EQ(ctx.GetProperty(Constants::FRAMEWORK_STORAGE).ToString(),
            GetTempDirectory());
  ASSERT_EQ(ctx.GetProperty(Constants::FRAMEWORK_WORKING_DIR),
            GetTempDirectory());

#ifdef US_ENABLE_THREADING_SUPPORT
  ASSERT_EQ(ctx.GetProperty(Constants::FRAMEWORK_THREADING_SUPPORT).ToString(),
            "multi");
#else
  ASSERT_EQ(ctx.GetProperty(Constants::FRAMEWORK_THREADING_SUPPORT).ToString(),
            "single");
#endif
}

TEST(FrameworkTest, NonIntegerLibraryLoadOption)
{
  FrameworkConfiguration configuration;
  configuration["org.cppmicroservices.library.load.options"] =
    std::string("bogus");

  auto f = FrameworkFactory().NewFramework(configuration);
  ASSERT_TRUE(f);
  ASSERT_NO_THROW(f.Start(););

#ifdef US_PLATFORM_POSIX
  ASSERT_EQ((RTLD_LAZY | RTLD_LOCAL),
            any_cast<int>(f.GetProperty(Constants::LIBRARY_LOAD_OPTIONS)));
#else
  ASSERT_EQ(0, any_cast<int>(f.GetProperty(Constants::LIBRARY_LOAD_OPTIONS)));
#endif

  f.Stop();
  f.WaitForStop(std::chrono::milliseconds::zero());
}

TEST(FrameworkTest, FrameworkStartsWhenFileNamedDataExistsInTempDir)
{
  class ScopedFile
  {
  public:
    ScopedFile(std::string directory, std::string filename)
      : filePath(std::move(directory) + util::DIR_SEP + std::move(filename))
    {
      CreateFile();
    }
    ~ScopedFile()
    {
      // Note: The file is created in the temp area anyway, so not being able
      // to remove the file is not catastrophic. We simply ignore it.
      std::remove(filePath.c_str());
    }

  private:
    void CreateFile()
    {
      std::fstream file(filePath, std::fstream::out);
      ASSERT_FALSE(file.fail())
        << "Failbit of the file stream should not be set.";
      file << "test";
      file.close();
    }
    const std::string filePath;
  };

  auto frameworkStorage = MakeUniqueTempDirectory();
  TempDir scopedDir(
    frameworkStorage); // delete "frameworkStorage" dir on destruction
  ScopedFile scopedFile(
    frameworkStorage,
    "data"); // create a file named "data" inside "scopedDir" and delete file on destruction
  FrameworkConfiguration frameworkConfig;
  frameworkConfig[Constants::FRAMEWORK_STORAGE] = frameworkStorage;

  auto framework = FrameworkFactory().NewFramework(frameworkConfig);
  ASSERT_TRUE(framework);
  ASSERT_NO_THROW(framework.Start(););
  framework.Stop();
  framework.WaitForStop(std::chrono::milliseconds::zero());
}

TEST(FrameworkTest, TempDataDirIsNotCreatedWhenFrameworkStarts)
{
  TempDir frameworkStorage = MakeUniqueTempDirectory();
  FrameworkConfiguration frameworkConfig;
  frameworkConfig[Constants::FRAMEWORK_STORAGE] =
    static_cast<std::string>(frameworkStorage);
  std::string persistentStoragePath =
    static_cast<std::string>(frameworkStorage) + util::DIR_SEP + "data";

  auto framework = FrameworkFactory().NewFramework(frameworkConfig);
  ASSERT_NO_THROW(framework.Start(););
  ASSERT_FALSE(util::Exists(persistentStoragePath))
    << "The framework should not create a directory named data in the "
       "temporary directory.";
  framework.Stop();
  framework.WaitForStop(std::chrono::milliseconds::zero());
}

TEST(FrameworkTest, DefaultLogSink)
{
  FrameworkConfiguration configuration;
  // turn on diagnostic logging
  configuration[Constants::FRAMEWORK_LOG] = true;

  // Needs improvement to guarantee that log messages are generated,
  // however for the moment do some operations using the framework
  // which would create diagnostic log messages.
  std::stringstream temp_buf;
  auto clog_buf = std::clog.rdbuf();
  std::clog.rdbuf(temp_buf.rdbuf());

  auto f = FrameworkFactory().NewFramework(configuration);
  ASSERT_TRUE(f);

  f.Start();
  cppmicroservices::testing::InstallLib(f.GetBundleContext(), "TestBundleA");

  f.Stop();
  f.WaitForStop(std::chrono::milliseconds::zero());

  ASSERT_FALSE(temp_buf.str().empty());

  std::clog.rdbuf(clog_buf);
}

TEST(FrameworkTest, CustomLogSink)
{
  FrameworkConfiguration configuration;
  // turn on diagnostic logging
  configuration[Constants::FRAMEWORK_LOG] = true;

  std::ostream custom_log_sink(std::cerr.rdbuf());

  auto f = FrameworkFactory().NewFramework(configuration, &custom_log_sink);
  ASSERT_TRUE(
    f); //Test Framework instantiation succeeded with custom diagnostic logger

  f.Start();
  f.Stop();
}

TEST(FrameworkTest, Properties)
{
  auto f = FrameworkFactory().NewFramework();
  f.Init();
  ASSERT_EQ(f.GetLocation(),
            "System Bundle"); // "Test Framework Bundle Location"
  ASSERT_EQ(
    f.GetSymbolicName(),
    Constants::SYSTEM_BUNDLE_SYMBOLICNAME); // "Test Framework Bundle Name"
  ASSERT_EQ(f.GetBundleId(), 0);            // "Test Framework Bundle Id"
}

TEST(Framework, LifeCycle)
{
  TestBundleListener listener;
  std::vector<BundleEvent> pEvts;

  auto f = FrameworkFactory().NewFramework();

  ASSERT_EQ(f.GetState(),
            Bundle::STATE_INSTALLED); // "Check framework is installed"

  // make sure WaitForStop returns immediately when the Framework's state is "Installed"
  auto fNoWaitEvent = f.WaitForStop(std::chrono::milliseconds::zero());
  ASSERT_TRUE(fNoWaitEvent); // "Check for valid framework event");
  ASSERT_EQ(fNoWaitEvent.GetType(),
            FrameworkEvent::Type::
              FRAMEWORK_ERROR); // "Check for correct framework event type"
  ASSERT_EQ(fNoWaitEvent.GetThrowable(),
            nullptr); // "Check that no exception was thrown"

  f.Init();

  ASSERT_EQ(f.GetState(),
            Bundle::STATE_STARTING); // "Check framework is starting"
  ASSERT_TRUE(f.GetBundleContext()); // "Check for a valid bundle context"

  f.Start();

  ASSERT_TRUE(listener.CheckListenerEvents(
    pEvts)); // "Check framework bundle event listener"

  ASSERT_EQ(f.GetState(), Bundle::STATE_ACTIVE); // "Check framework is active"

  f.GetBundleContext().AddBundleListener(std::bind(
    &TestBundleListener::BundleChanged, &listener, std::placeholders::_1));

#ifdef US_ENABLE_THREADING_SUPPORT
  // To test that the correct FrameworkEvent is returned, we must guarantee that the Framework
  // is in a STARTING, ACTIVE, or STOPPING state.
  std::thread waitForStopThread([&f]() {
    auto fStopEvent = f.WaitForStop(std::chrono::milliseconds::zero());
    ASSERT_FALSE(
      f.GetState() &
      Bundle::STATE_ACTIVE); // "Check framework is in the Stop state"
    ASSERT_TRUE(fStopEvent); // "Check for valid framework event"
    ASSERT_EQ(
      fStopEvent.GetType(),
      FrameworkEvent::Type::
        FRAMEWORK_STOPPED); // "Check for correct framework event type");
    ASSERT_EQ(fStopEvent.GetThrowable(),
              nullptr); // "Check that no exception was thrown");
  });

  f.Stop();
  waitForStopThread.join();
#else
  f.Stop();
#endif

  pEvts.push_back(BundleEvent(BundleEvent::BUNDLE_STOPPING, f));

  ASSERT_TRUE(listener.CheckListenerEvents(
    pEvts)); // "Check framework bundle event listener")

  ASSERT_THROW(
    f.Uninstall(),
    std::
      runtime_error); // Test that uninstalling a framework throws an exception

  // Test that all bundles in the Start state are stopped when the framework is stopped.
  f.Start();
#if defined(US_BUILD_SHARED_LIBS)
  auto bundle =
    cppmicroservices::testing::InstallLib(f.GetBundleContext(), "TestBundleA");
#else
  auto bundle =
    cppmicroservices::testing::GetBundle("TestBundleA", f.GetBundleContext());
#endif
  ASSERT_TRUE(bundle); // "Non-null bundle"
  bundle.Start();
  ASSERT_EQ(
    bundle.GetState(),
    Bundle::STATE_ACTIVE); // "Check that TestBundleA is in an Active state"

#ifdef US_ENABLE_THREADING_SUPPORT
  // To test that the correct FrameworkEvent is returned, we must guarantee that the Framework
  // is in a STARTING, ACTIVE, or STOPPING state.
  waitForStopThread = std::thread([&f]() {
    auto ev = f.WaitForStop(std::chrono::seconds(10));
    ASSERT_TRUE(
      ev); // "Test for valid framework event returned by Framework::WaitForStop()"
    if (!ev && ev.GetType() == FrameworkEvent::Type::FRAMEWORK_ERROR)
      std::rethrow_exception(ev.GetThrowable());
    ASSERT_EQ(ev.GetType(),
              FrameworkEvent::Type::
                FRAMEWORK_STOPPED); // "Check that framework event is stopped"
  });

  // Stopping the framework stops all active bundles.
  f.Stop();
  waitForStopThread.join();
#else
  f.Stop();
#endif
  ASSERT_NE(bundle.GetState(),
            Bundle::STATE_ACTIVE); // "Check that TestBundleA is not active"
  ASSERT_NE(f.GetState(),
            Bundle::STATE_ACTIVE); // "Check framework is not active"
}

#ifdef US_ENABLE_THREADING_SUPPORT

TEST(FrameworkTest, ConcurrentFrameworkStart)
{
  // test concurrent Framework starts.
  auto f = FrameworkFactory().NewFramework();
  f.Init();
  int start_count{ 0 };
  f.GetBundleContext().AddFrameworkListener(
    [&start_count](const FrameworkEvent& ev) {
      if (FrameworkEvent::Type::FRAMEWORK_STARTED == ev.GetType())
        ++start_count;
    });
  size_t num_threads{ 100 };
  std::vector<std::thread> threads;
  for (size_t i = 0; i < num_threads; ++i) {
    threads.push_back(std::thread{ [&f]() { f.Start(); } });
  }

  for (auto& t : threads)
    t.join();

  // To test that the correct FrameworkEvent is returned, we must guarantee that the Framework
  // is in a STARTING, ACTIVE, or STOPPING state.
  std::thread waitForStopThread([&f]() {
    auto fEvent = f.WaitForStop(std::chrono::milliseconds::zero());
    ASSERT_TRUE(
      fEvent); // "Check for a valid framework event returned from WaitForStop"
    ASSERT_EQ(fEvent.GetType(),
              FrameworkEvent::Type::
                FRAMEWORK_STOPPED); // "Check that framework event is stopped"
    ASSERT_EQ(fEvent.GetThrowable(),
              nullptr); // "Check that no exception was thrown"
  });

  f.Stop();
  waitForStopThread.join();

  // Its somewhat ambiguous in the OSGi spec whether or not multiple Framework STARTED events should be sent
  // when repeated calls to Framework::Start() are made on the same Framework instance once its in the
  // ACTIVE bundle state.
  // Felix and Knopflerfish OSGi implementations take two different stances.
  // Lock down the behavior that only one Framework STARTED event is sent.
  ASSERT_EQ(
    1,
    start_count); // "Multiple Framework::Start() calls only produce one Framework STARTED event."
}

TEST(FrameworkTest, ConcurrentFrameworkStop)
{
  // test concurrent Framework stops.
  auto f = FrameworkFactory().NewFramework();
  f.Start();

  // To test that the correct FrameworkEvent is returned, we must guarantee that the Framework
  // is in a STARTING, ACTIVE, or STOPPING state.
  std::thread waitForStopThread([&f]() {
    auto fEvent = f.WaitForStop(std::chrono::milliseconds::zero());
    ASSERT_TRUE(
      fEvent); // "Check for a valid framework event returned from WaitForStop"
    ASSERT_EQ(fEvent.GetType(),
              FrameworkEvent::Type::
                FRAMEWORK_STOPPED); // "Check that framework event is stopped"
    ASSERT_EQ(fEvent.GetThrowable(),
              nullptr); // "Check that no exception was thrown"
  });

  size_t num_threads{ 100 };
  std::vector<std::thread> threads;
  for (size_t i = 0; i < num_threads; ++i) {
    threads.push_back(std::thread{ [&f]() { f.Stop(); } });
  }

  for (auto& t : threads)
    t.join();
  waitForStopThread.join();
}

TEST(FrameworkTest, ConcurrentFrameworkWaitForStop)
{
  // test concurrent Framework stops.
  auto f = FrameworkFactory().NewFramework();
  f.Start();

  std::mutex m;
  size_t num_threads{ 100 };
  std::vector<std::thread> threads;
  for (size_t i = 0; i < num_threads; ++i) {
    // To test that the correct FrameworkEvent is returned, we must guarantee that the Framework
    // is in a STARTING, ACTIVE, or STOPPING state.
    threads.push_back(std::thread([&f, &m]() {
      auto fEvent = f.WaitForStop(std::chrono::milliseconds::zero());
      std::unique_lock<std::mutex> lock(m);
      ASSERT_TRUE(
        fEvent); // "Check for a valid framework event returned from WaitForStop"
      ASSERT_EQ(fEvent.GetType(),
                FrameworkEvent::Type::
                  FRAMEWORK_STOPPED); // "Check that framework event is stopped"
      ASSERT_EQ(fEvent.GetThrowable(),
                nullptr); // "Check that no exception was thrown"
    }));
  }

  f.Stop();
  for (auto& t : threads) {
    t.join();
  }
}

#endif

TEST(FrameworkTest, Events)
{
  TestBundleListener listener;
  std::vector<BundleEvent> pEvts;
  std::vector<BundleEvent> pStopEvts;

  auto f = FrameworkFactory().NewFramework();

  f.Start();

  auto fmc = f.GetBundleContext();
  fmc.AddBundleListener(std::bind(
    &TestBundleListener::BundleChanged, &listener, std::placeholders::_1));

#ifdef US_BUILD_SHARED_LIBS
  auto install = [&pEvts, &fmc](const std::string& libName) {
    auto bundle = cppmicroservices::testing::InstallLib(fmc, libName);
    pEvts.push_back(BundleEvent(BundleEvent::BUNDLE_INSTALLED, bundle));
    if (bundle.GetSymbolicName() == "TestBundleB") {
      // This is an additional install event from the bundle
      // that is statically imported by TestBundleB.
      pEvts.push_back(BundleEvent(
        BundleEvent::BUNDLE_INSTALLED,
        cppmicroservices::testing::GetBundle("TestBundleImportedByB", fmc)));
    }
  };

  // The bundles used to test bundle events when stopping the framework.
  // For static builds, the order of the "install" calls is imported.

  install("TestBundleA");
  install("TestBundleA2");
  install("TestBundleB");
#  ifdef US_ENABLE_THREADING_SUPPORT
  install("TestBundleC1");
#  endif
  install("TestBundleH");
  install("TestBundleLQ");
  install("TestBundleM");
  install("TestBundleR");
  install("TestBundleRA");
  install("TestBundleRL");
  install("TestBundleS");
  install("TestBundleSL1");
  install("TestBundleSL3");
  install("TestBundleSL4");
  auto bundles(fmc.GetBundles());
#else
  // since all bundles are embedded in the main executable, all bundles are
  // installed at framework start. simply check for start and stop events
  std::vector<cppmicroservices::Bundle> bundles;
  bundles.push_back(cppmicroservices::testing::GetBundle("TestBundleA", fmc));
  bundles.push_back(cppmicroservices::testing::GetBundle("TestBundleA2", fmc));
  bundles.push_back(cppmicroservices::testing::GetBundle("TestBundleB", fmc));
#  ifdef US_ENABLE_THREADING_SUPPORT
  bundles.push_back(cppmicroservices::testing::GetBundle("TestBundleC1", fmc));
#  endif
  bundles.push_back(cppmicroservices::testing::GetBundle("TestBundleH", fmc));
  bundles.push_back(
    cppmicroservices::testing::GetBundle("TestBundleImportedByB", fmc));
  bundles.push_back(cppmicroservices::testing::GetBundle("TestBundleLQ", fmc));
  bundles.push_back(cppmicroservices::testing::GetBundle("TestBundleM", fmc));
  bundles.push_back(cppmicroservices::testing::GetBundle("TestBundleR", fmc));
  bundles.push_back(cppmicroservices::testing::GetBundle("TestBundleRA", fmc));
  bundles.push_back(cppmicroservices::testing::GetBundle("TestBundleRL", fmc));
  bundles.push_back(cppmicroservices::testing::GetBundle("TestBundleS", fmc));
  bundles.push_back(cppmicroservices::testing::GetBundle("TestBundleSL1", fmc));
  bundles.push_back(cppmicroservices::testing::GetBundle("TestBundleSL3", fmc));
  bundles.push_back(cppmicroservices::testing::GetBundle("TestBundleSL4", fmc));
  bundles.push_back(cppmicroservices::testing::GetBundle("main", fmc));
#endif

  for (auto& bundle : bundles) {
    bundle.Start();
    // no events will be fired for the framework, its already active at this point
    if (bundle != f) {
      pEvts.push_back(BundleEvent(BundleEvent::BUNDLE_RESOLVED, bundle));
      pEvts.push_back(BundleEvent(BundleEvent::BUNDLE_STARTING, bundle));
      pEvts.push_back(BundleEvent(BundleEvent::BUNDLE_STARTED, bundle));

      // bundles will be stopped in the reverse order in which they were started.
      // It is easier to maintain this test if the stop events are setup in the
      // right order here, while the bundles are starting, instead of hard coding
      // the order of events somewhere else.
      // Doing it this way also tests the order in which starting and stopping
      // bundles occurs and when their events are fired.
      pStopEvts.push_back(BundleEvent(BundleEvent::BUNDLE_STOPPED, bundle));
      pStopEvts.push_back(BundleEvent(BundleEvent::BUNDLE_STOPPING, bundle));
    }
  }
  // Remember, the framework is stopped first, before all bundles are stopped.
  pStopEvts.push_back(BundleEvent(BundleEvent::BUNDLE_STOPPING, f));
  std::reverse(pStopEvts.begin(), pStopEvts.end());

  ASSERT_TRUE(
    listener.CheckListenerEvents(pEvts)); // "Check for bundle start events"

  // Stopping the framework stops all active bundles.
  f.Stop();
  f.WaitForStop(std::chrono::milliseconds::zero());

  ASSERT_TRUE(
    listener.CheckListenerEvents(pStopEvts)); // "Check for bundle stop events"
}

TEST(FrameworkTest, IndirectFrameworkStop)
{
  auto f = FrameworkFactory().NewFramework();
  f.Start();
  auto bundle = f.GetBundleContext().GetBundle(0);
  bundle.Stop();
  Framework f2(bundle);
  f2.WaitForStop(std::chrono::milliseconds::zero());
  ASSERT_EQ(f.GetState(), Bundle::STATE_RESOLVED); // "Framework stopped"
}

TEST(FrameworkTest, ShutdownAndStart)
{
  int startCount = 0;

  FrameworkEvent fwEvt;
  {
    auto f = FrameworkFactory().NewFramework();
    f.Init();

    auto ctx = f.GetBundleContext();

    ctx.AddFrameworkListener([&startCount](const FrameworkEvent& fwEvt) {
      if (fwEvt.GetType() == FrameworkEvent::FRAMEWORK_STARTED) {
        ++startCount;
        auto bundle = fwEvt.GetBundle();
        ASSERT_EQ(bundle.GetBundleId(), 0); // "Got framework bundle"
        ASSERT_EQ(bundle.GetState(),
                  Bundle::STATE_ACTIVE); // "Started framework"

        // This stops the framework
        bundle.Stop();
      }
    });

    ASSERT_EQ(f.GetState(), Framework::STATE_STARTING); // "Starting framework"
    f.Start();

    // Wait for stop
    fwEvt = f.WaitForStop(std::chrono::milliseconds::zero());
  }

  ASSERT_EQ(fwEvt.GetType(),
            FrameworkEvent::FRAMEWORK_STOPPED); // "Stopped framework event"

  Bundle fwBundle = fwEvt.GetBundle();
  ASSERT_EQ(fwBundle.GetState(),
            Bundle::STATE_RESOLVED); // "Resolved framework"

  // Start the framework again
  fwBundle.Start();

  ASSERT_EQ(fwBundle.GetState(), Bundle::STATE_ACTIVE); // "Active framework"

  ASSERT_EQ(startCount, 1); // "One framework start notification"
}


text:
/*
 * Do not modify this file. This file is generated from the opsworks-2013-02-18.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.OpsWorks.Model
{
    ///
    /// Container for the parameters to the DeregisterEcsCluster operation.
    /// Deregisters a specified Amazon ECS cluster from a stack. For more information, see
    ///
    /// Resource Management.
    ///
    ///
    /// <para>
    /// Required Permissions: To use this action, an IAM user must have a Manage permissions
    /// level for the stack or an attached policy that explicitly grants permissions. For
    /// more information on user permissions, see .
    /// </para>
    ///
    public partial class DeregisterEcsClusterRequest : AmazonOpsWorksRequest
    {
        private string _ecsClusterArn;

        ///
        /// Gets and sets the property EcsClusterArn.
        /// <para>
        /// The cluster's ARN.
        /// </para>
        ///
        public string EcsClusterArn
        {
            get { return this._ecsClusterArn; }
            set { this._ecsClusterArn = value; }
        }

        // Check to see if EcsClusterArn property is set
        internal bool IsSetEcsClusterArn()
        {
            return this._ecsClusterArn != null;
        }

    }
}


text:
<?php namespace Studiz\Core\View\Navigation;

/**
 * Class Node
 *
 * @author  Selcuk Kekec <senycorp@googlemail.com>
 * @package Studiz\Core\View\Navigation
 */
abstract class Node
{

    /**
     * Return nodes
     *
     * @return array
     */
    public function getNodes()
    {
        return $this->getNodeRegister();
    }

    /**
     * Get nodes of navigational component
     *
     * @return array
     */
    abstract protected function getNodeRegister();
}