text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#pragma warning disable 1573

namespace AsyncIO.FileSystem.Extensions
{
    /// <summary>
    /// Provides async extension method for <see cref="FileInfo"/>.
    /// </summary>
    public static class FileInfoExtensions
    {
        #region AppendAllLinesAsync

        /// <summary>
        /// Appends lines asynchronously to a file, and then closes the file.
        /// If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file.
        /// </summary>
        /// <param name="contents">The lines to append to the file.</param>
        /// <exception cref="ArgumentNullException"><paramref name="contents"/> is <c>null</c>.</exception>
        /// <exception cref="DirectoryNotFoundException">File path is invalid (for example, the directory doesn't exist or it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        /// <exception cref="UnauthorizedAccessException">File path specifies a file that is read-only.
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>File path is a directory.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        /// <remarks>The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter must contain existing directories.</remarks>
        /// <returns>Task that represents asynchronous operation.</returns>
        public static Task AppendAllLinesAsync(this FileInfo fileInfo, IEnumerable<string> contents)
        {
            return AsyncFile.AppendAllLinesAsync(fileInfo.FullName, contents);
        }

        /// <summary>
        /// Appends lines asynchronously to a file by using a specified encoding, and then closes the file.
        /// If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file.
        /// </summary>
        /// <param name="contents">The lines to append to the file.</param>
        /// <param name="encoding">The character encoding to use.</param>
        /// <exception cref="ArgumentNullException"><paramref name="contents"/> is <c>null</c>.</exception>
        /// <exception cref="DirectoryNotFoundException">File path is invalid (for example, the directory doesn't exist or it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        /// <exception cref="UnauthorizedAccessException">File path specifies a file that is read-only.
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>File path is a directory.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        /// <remarks>The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter must contain existing directories.</remarks>
        /// <returns>Task that represents asynchronous operation.</returns>
        public static Task AppendAllLinesAsync(this FileInfo fileInfo, IEnumerable<string> contents, Encoding encoding)
        {
            return AsyncFile.AppendAllLinesAsync(fileInfo.FullName, contents, encoding, CancellationToken.None);
        }

        /// <summary>
        /// Appends lines asynchronously to a file, and then closes the file, and monitors cancellation requests.
        /// If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file.
        /// </summary>
        /// <param name="contents">The lines to append to the file.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <exception cref="ArgumentNullException"><paramref name="contents"/> is <c>null</c>.</exception>
        /// <exception cref="DirectoryNotFoundException">File path is invalid (for example, the directory doesn't exist or it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        /// <exception cref="UnauthorizedAccessException">File path specifies a file that is read-only.
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>File path is a directory.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        /// <remarks>The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter must contain existing directories.</remarks>
        /// <returns>Task that represents asynchronous operation.</returns>
        public static Task AppendAllLinesAsync(this FileInfo fileInfo, IEnumerable<string> contents, CancellationToken cancellationToken)
        {
            return AsyncFile.AppendAllLinesAsync(fileInfo.FullName, contents, Encoding.UTF8, cancellationToken);
        }

        /// <summary>
        /// Appends lines asynchronously to a file by using a specified encoding, and then closes the file, and monitors cancellation requests.
        /// If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file.
        /// </summary>
        /// <param name="contents">The lines to append to the file.</param>
        /// <param name="encoding">The character encoding to use.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <exception cref="ArgumentNullException"><paramref name="contents"/> is <c>null</c>.</exception>
        /// <exception cref="DirectoryNotFoundException">File path is invalid (for example, the directory doesn't exist or it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        /// <exception cref="UnauthorizedAccessException">File path specifies a file that is read-only.
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>File path is a directory.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        /// <remarks>The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter must contain existing directories.</remarks>
        /// <returns>Task that represents asynchronous operation.</returns>
        public static Task AppendAllLinesAsync(this FileInfo fileInfo, IEnumerable<string> contents, Encoding encoding,
                                               CancellationToken cancellationToken)
        {
            return AsyncFile.AppendAllLinesAsync(fileInfo.FullName, contents, encoding, cancellationToken);
        }

        #endregion

        #region AppendAllTextAsync

        /// <summary>
        /// Asynchronously appends the specified string to the file, creating the file if it does not already exist.
        /// </summary>
        /// <param name="contents">The string to append to the file.</param>
        /// <remarks>
        /// <para>Given a string and a file path, this method opens the specified file, appends the string to the end of the file using the specified encoding, and then closes the file. The file handle is guaranteed to be closed by this method, even if exceptions are raised.</para>
        /// <para>The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter must contain existing directories.</para>
        /// </remarks>
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains one more invalid characters defined by the <see cref="Path.GetInvalidPathChars"/> method.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="contents"/> is <c>null</c>.</exception>
        /// <exception cref="DirectoryNotFoundException">File path is invalid (for example, the directory doesn't exist or it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="PathTooLongException">File path 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="SecurityException">The caller does not have the required permission.</exception>
        /// <exception cref="UnauthorizedAccessException">File path specifies a file that is read-only.
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>File path is a directory.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        /// <returns>Task that represents asynchronous operation.</returns>
        public static Task AppendAllTextAsync(this FileInfo fileInfo, string contents)
        {
            return AsyncFile.AppendAllTextAsync(fileInfo.FullName, contents, Encoding.UTF8);
        }

        /// <summary>
        /// Asynchronously appends the specified string to the file, creating the file if it does not already exist.
        /// </summary>
        /// <param name="contents">The string to append to the file.</param>
        /// <param name="encoding">The character encoding to use.</param>
        /// <remarks>
        /// <para>Given a string and a file path, this method opens the specified file, appends the string to the end of the file using the specified encoding, and then closes the file. The file handle is guaranteed to be closed by this method, even if exceptions are raised.</para>
        /// <para>The method creates the file if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter must contain existing directories.</para>
        /// </remarks>
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains one more invalid characters defined by the <see cref="Path.GetInvalidPathChars"/> method.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="contents"/> is <c>null</c>.</exception>
        /// <exception cref="DirectoryNotFoundException">File path is invalid (for example, the directory doesn't exist or it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="PathTooLongException">File path 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="SecurityException">The caller does not have the required permission.</exception>
        /// <exception cref="UnauthorizedAccessException">File path specifies a file that is read-only.
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>File path is a directory.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        /// <returns>Task that represents asynchronous operation.</returns>
        public static Task AppendAllTextAsync(this FileInfo fileInfo, string contents, Encoding encoding)
        {
            return AsyncFile.AppendAllTextAsync(fileInfo.FullName, contents, encoding);
        }

        #endregion

        #region CopyToAsync

        /// <summary>
        /// Asynchronously copies an existing file to a new file, and monitors cancellation requests. Overwriting a file of the same name is not allowed.
        /// </summary>
        ///
        /// <param name="destFileName">The name of the destination file. This cannot be a directory.</param>
        /// <remarks>
        /// <para>
        /// The <paramref name="destFileName"/> parameter can specify relative or absolute path information.
        /// Relative path information is interpreted as relative to the current working directory.
        /// This method does not support wildcard characters in the parameters.
        /// </para>
        /// <para>The attributes of the original file are retained in the copied file.</para>
        /// </remarks>
        ///
        /// <exception cref="ArgumentException">
        /// File path or <paramref name="destFileName"/> is a zero-length string, contains only white space, or contains one more invalid characters defined by the <see cref="Path.GetInvalidPathChars"/> method.
        /// <para>-or-</para>
        /// <para>File path or <paramref name="destFileName"/> specifies a directory.</para>
        /// </exception>
        /// <exception cref="ArgumentNullException">Either File path or <paramref name="destFileName"/>is <c>null</c>.</exception>
        /// <exception cref="DirectoryNotFoundException">The path specified inFile path or <paramref name="destFileName"/> is invalid (for example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">
        /// <para><paramref name="destFileName"/> exists.</para>
        /// <para>-or-</para>
        /// <para>An I/O error has occurred.</para>
        /// </exception>
        /// <exception cref="PathTooLongException">
        /// 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="FileNotFoundException">Source file was not found.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        /// <exception cref="UnauthorizedAccessException"><paramref name="destFileName"/> is read-only.
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        ///
        /// <returns>Task that represents asynchronous operation.</returns>
        public static Task CopyToAsync(this FileInfo fileInfo, string destFileName)
        {
            return AsyncFile.CopyAsync(fileInfo.FullName, destFileName);
        }

        /// <summary>
        /// Asynchronously copies an existing file to a new file, and monitors cancellation requests. Overwriting a file of the same name is not allowed.
        /// </summary>
        ///
        /// <param name="destFileName">The name of the destination file. This cannot be a directory.</param>
        /// <param name="overwrite"><c>true</c> if the destination file can be overwritten; otherwise, <c>false</c>.</param>
        /// <remarks>
        /// <para>
        /// The <paramref name="destFileName"/> parameter can specify relative or absolute path information.
        /// Relative path information is interpreted as relative to the current working directory.
        /// This method does not support wildcard characters in the parameters.
        /// </para>
        /// <para>The attributes of the original file are retained in the copied file.</para>
        /// </remarks>
        ///
        /// <exception cref="ArgumentException">
        /// File path or <paramref name="destFileName"/> is a zero-length string, contains only white space, or contains one more invalid characters defined by the <see cref="Path.GetInvalidPathChars"/> method.
        /// <para>-or-</para>
        /// <para>File path or <paramref name="destFileName"/> specifies a directory.</para>
        /// </exception>
        /// <exception cref="ArgumentNullException">Either File path or <paramref name="destFileName"/>is <c>null</c>.</exception>
        /// <exception cref="DirectoryNotFoundException">The path specified inFile path or <paramref name="destFileName"/> is invalid (for example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">
        /// <para><paramref name="destFileName"/> exists.</para>
        /// <para>-or-</para>
        /// <para>An I/O error has occurred.</para>
        /// </exception>
        /// <exception cref="PathTooLongException">
        /// 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="FileNotFoundException">Source file was not found.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        /// <exception cref="UnauthorizedAccessException"><paramref name="destFileName"/> is read-only.
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        ///
        /// <returns>Task that represents asynchronous operation.</returns>
        public static Task CopyToAsync(this FileInfo fileInfo, string destFileName, bool overwrite)
        {
            return AsyncFile.CopyAsync(fileInfo.FullName, destFileName, overwrite);
        }

        /// <summary>
        /// Asynchronously copies an existing file to a new file, and monitors cancellation requests. Overwriting a file of the same name is not allowed.
        /// </summary>
        ///
        /// <param name="destFileName">The name of the destination file. This cannot be a directory.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <remarks>
        /// <para>
        /// The <paramref name="destFileName"/> parameter can specify relative or absolute path information.
        /// Relative path information is interpreted as relative to the current working directory.
        /// This method does not support wildcard characters in the parameters.
        /// </para>
        /// <para>The attributes of the original file are retained in the copied file.</para>
        /// </remarks>
        ///
        /// <exception cref="ArgumentException">
        /// File path or <paramref name="destFileName"/> is a zero-length string, contains only white space, or contains one more invalid characters defined by the <see cref="Path.GetInvalidPathChars"/> method.
        /// <para>-or-</para>
        /// <para>File path or <paramref name="destFileName"/> specifies a directory.</para>
        /// </exception>
        /// <exception cref="ArgumentNullException">Either File path or <paramref name="destFileName"/>is <c>null</c>.</exception>
        /// <exception cref="DirectoryNotFoundException">The path specified inFile path or <paramref name="destFileName"/> is invalid (for example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">
        /// <para><paramref name="destFileName"/> exists.</para>
        /// <para>-or-</para>
        /// <para>An I/O error has occurred.</para>
        /// </exception>
        /// <exception cref="PathTooLongException">
        /// 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="FileNotFoundException">Source file was not found.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        /// <exception cref="UnauthorizedAccessException"><paramref name="destFileName"/> is read-only.
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        ///
        /// <returns>Task that represents asynchronous operation.</returns>
        public static Task CopyToAsync(this FileInfo fileInfo, string destFileName, CancellationToken cancellationToken)
        {
            return AsyncFile.CopyAsync(fileInfo.FullName, destFileName, cancellationToken);
        }

        /// <summary>
        /// Asynchronously copies an existing file to a new file, and monitors cancellation requests. Overwriting a file of the same name is not allowed.
        /// </summary>
        ///
        /// <param name="destFileName">The name of the destination file. This cannot be a directory.</param>
        /// <param name="overwrite"><c>true</c> if the destination file can be overwritten; otherwise, <c>false</c>.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <remarks>
        /// <para>
        /// The <paramref name="destFileName"/> parameter can specify relative or absolute path information.
        /// Relative path information is interpreted as relative to the current working directory.
        /// This method does not support wildcard characters in the parameters.
        /// </para>
        /// <para>The attributes of the original file are retained in the copied file.</para>
        /// </remarks>
        ///
        /// <exception cref="ArgumentException">
        /// File path or <paramref name="destFileName"/> is a zero-length string, contains only white space, or contains one more invalid characters defined by the <see cref="Path.GetInvalidPathChars"/> method.
        /// <para>-or-</para>
        /// <para>File path or <paramref name="destFileName"/> specifies a directory.</para>
        /// </exception>
        /// <exception cref="ArgumentNullException">Either File path or <paramref name="destFileName"/>is <c>null</c>.</exception>
        /// <exception cref="DirectoryNotFoundException">The path specified inFile path or <paramref name="destFileName"/> is invalid (for example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">
        /// <para><paramref name="destFileName"/> exists.</para>
        /// <para>-or-</para>
        /// <para>An I/O error has occurred.</para>
        /// </exception>
        /// <exception cref="PathTooLongException">
        /// 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="FileNotFoundException">Source file was not found.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        /// <exception cref="UnauthorizedAccessException"><paramref name="destFileName"/> is read-only.
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        ///
        /// <returns>Task that represents asynchronous operation.</returns>
        public static Task CopyToAsync(this FileInfo fileInfo, string destFileName, bool overwrite, CancellationToken cancellationToken)
        {
            return AsyncFile.CopyAsync(fileInfo.FullName, destFileName, overwrite, cancellationToken);
        }

        #endregion

        #region DeleteAsync

        /// <summary>
        /// Asynchronously deletes the specified file.
        /// </summary>
        ///
        /// <remarks>
        /// <para>If the file to be deleted does not exist, no exception is thrown.</para>
        /// </remarks>
        ///
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains one more invalid characters defined by the <see cref="Path.GetInvalidPathChars"/> method.</exception>
        /// <exception cref="ArgumentNullException">File path is <c>null</c>.</exception>
        /// <exception cref="DirectoryNotFoundException">The path specified in File path is invalid (for example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">
        /// <para>The specified file is in use.</para>
        /// <para>-or-</para>
        /// <para>There is an open handle on the file, and the operating system is Windows XP or earlier. This open handle can result from enumerating directories and files.</para>
        /// </exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="PathTooLongException">
        /// 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="SecurityException">The caller does not have the required permission.</exception>
        /// <exception cref="UnauthorizedAccessException">File path specifies a read-only file.
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// <para>-or-</para>
        /// <para>The file is an executable file that is in use.</para>
        /// </exception>
        ///
        /// <returns>Task that represents asynchronous operation.</returns>
        public static Task DeleteAsync(this FileInfo fileInfo)
        {
            return AsyncFile.DeleteAsync(fileInfo.FullName);
        }

        #endregion

        #region ReadAllBytesAsync

        /// <summary>
        /// Opens a binary file, asynchronously reads the contents of the file into a byte array, and then closes the file.
        /// </summary>
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains invalid characters as defined in <see cref="Path.GetInvalidPathChars"/></exception>
        /// <exception cref="ArgumentNullException">File path is <c>null</c>.</exception>
        /// <exception cref="PathTooLongException">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 File path is invalid, (dor example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="UnauthorizedAccessException">
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        /// <exception cref="FileNotFoundException">The file specified in File path was not found.</exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        ///
        /// <returns>A task with a byte array containing the contents of the file.</returns>
        public static Task<byte[]> ReadAllBytesAsync(this FileInfo fileInfo)
        {
            return AsyncFile.ReadAllBytesAsync(fileInfo.FullName);
        }

        /// <summary>
        /// Opens a binary file, asynchronously reads the contents of the file into a byte array, and then closes the file.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains invalid characters as defined in <see cref="Path.GetInvalidPathChars"/></exception>
        /// <exception cref="ArgumentNullException">File path is <c>null</c>.</exception>
        /// <exception cref="PathTooLongException">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 File path is invalid, (dor example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="UnauthorizedAccessException">
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        /// <exception cref="FileNotFoundException">The file specified in File path was not found.</exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        ///
        /// <returns>A task with a byte array containing the contents of the file.</returns>
        public static Task<byte[]> ReadAllBytesAsync(this FileInfo fileInfo, CancellationToken cancellationToken)
        {
            return AsyncFile.ReadAllBytesAsync(fileInfo.FullName, cancellationToken);
        }

        #endregion

        #region ReadAllLinesAsync

        /// <summary>
        /// Opens a file, asynchronously reads all lines of the file, and then closes the file.
        /// </summary>
        ///
        /// <returns>A task with a string array containing all lines of the file.</returns>
        ///
        /// <remarks>
        /// <para>
        /// This method opens a file, reads each line of the file, and then adds each line as an element of a string array. It then closes the file.
        /// A line is defined as a sequence of characters followed by a carriage return ('\r'), a line feed ('\n'), or a carriage return immediately followed by a line feed.
        /// The resulting string does not contain the terminating carriage return and/or line feed.
        /// </para>
        /// </remarks>
        ///
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains invalid characters as defined in <see cref="Path.GetInvalidPathChars"/></exception>
        /// <exception cref="ArgumentNullException">File path is <c>null</c>.</exception>
        /// <exception cref="PathTooLongException">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 File path is invalid, (dor example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="UnauthorizedAccessException">
        /// <para>File path specified a file that is read-only.</para>
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        /// <exception cref="FileNotFoundException">The file specified in File path was not found.</exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        public static Task<string[]> ReadAllLinesAsync(this FileInfo fileInfo)
        {
            return AsyncFile.ReadAllLinesAsync(fileInfo.FullName);
        }

        /// <summary>
        /// Opens a file, asynchronously reads all lines of the file, and then closes the file.
        /// </summary>
        ///
        /// <param name="encoding">The encoding applied to the contents of the file.</param>
        ///
        /// <returns>A task with a string array containing all lines of the file.</returns>
        ///
        /// <remarks>
        /// <para>
        /// This method opens a file, reads each line of the file, and then adds each line as an element of a string array. It then closes the file.
        /// A line is defined as a sequence of characters followed by a carriage return ('\r'), a line feed ('\n'), or a carriage return immediately followed by a line feed.
        /// The resulting string does not contain the terminating carriage return and/or line feed.
        /// </para>
        /// </remarks>
        ///
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains invalid characters as defined in <see cref="Path.GetInvalidPathChars"/></exception>
        /// <exception cref="ArgumentNullException">File path is <c>null</c>.</exception>
        /// <exception cref="PathTooLongException">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 File path is invalid, (dor example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="UnauthorizedAccessException">
        /// <para>File path specified a file that is read-only.</para>
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        /// <exception cref="FileNotFoundException">The file specified in File path was not found.</exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        public static Task<string[]> ReadAllLinesAsync(this FileInfo fileInfo, Encoding encoding)
        {
            return AsyncFile.ReadAllLinesAsync(fileInfo.FullName, encoding);
        }

        /// <summary>
        /// Opens a file, asynchronously reads all lines of the file, and then closes the file.
        /// </summary>
        ///
        /// <param name="cancellationToken">The cancellation token.</param>
        ///
        /// <returns>A task with a string array containing all lines of the file.</returns>
        ///
        /// <remarks>
        /// <para>
        /// This method opens a file, reads each line of the file, and then adds each line as an element of a string array. It then closes the file.
        /// A line is defined as a sequence of characters followed by a carriage return ('\r'), a line feed ('\n'), or a carriage return immediately followed by a line feed.
        /// The resulting string does not contain the terminating carriage return and/or line feed.
        /// </para>
        /// </remarks>
        ///
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains invalid characters as defined in <see cref="Path.GetInvalidPathChars"/></exception>
        /// <exception cref="ArgumentNullException">File path is <c>null</c>.</exception>
        /// <exception cref="PathTooLongException">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 File path is invalid, (dor example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="UnauthorizedAccessException">
        /// <para>File path specified a file that is read-only.</para>
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        /// <exception cref="FileNotFoundException">The file specified in File path was not found.</exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        public static Task<string[]> ReadAllLinesAsync(this FileInfo fileInfo, CancellationToken cancellationToken)
        {
            return AsyncFile.ReadAllLinesAsync(fileInfo.FullName, cancellationToken);
        }

        /// <summary>
        /// Opens a file, asynchronously reads all lines of the file, and then closes the file.
        /// </summary>
        ///
        /// <param name="encoding">The encoding applied to the contents of the file.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        ///
        /// <returns>A task with a string array containing all lines of the file.</returns>
        ///
        /// <remarks>
        /// <para>
        /// This method opens a file, reads each line of the file, and then adds each line as an element of a string array. It then closes the file.
        /// A line is defined as a sequence of characters followed by a carriage return ('\r'), a line feed ('\n'), or a carriage return immediately followed by a line feed.
        /// The resulting string does not contain the terminating carriage return and/or line feed.
        /// </para>
        /// </remarks>
        ///
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains invalid characters as defined in <see cref="Path.GetInvalidPathChars"/></exception>
        /// <exception cref="ArgumentNullException">File path is <c>null</c>.</exception>
        /// <exception cref="PathTooLongException">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 File path is invalid, (dor example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="UnauthorizedAccessException">
        /// <para>File path specified a file that is read-only.</para>
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        /// <exception cref="FileNotFoundException">The file specified in File path was not found.</exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        public static Task<string[]> ReadAllLinesAsync(this FileInfo fileInfo, Encoding encoding, CancellationToken cancellationToken)
        {
            return AsyncFile.ReadAllLinesAsync(fileInfo.FullName, encoding, cancellationToken);
        }

        #endregion

        #region ReadAllTextAsync

        /// <summary>
        /// Opens a file, asynchronously reads all lines of the file, and then closes the file.
        /// </summary>
        ///
        /// <returns>A task with a string containing all lines of the file.</returns>
        ///
        /// <remarks>
        /// <para>
        /// This method opens a file, reads each line of the file, and then adds each line as an element of a string. It then closes the file.
        /// A line is defined as a sequence of characters followed by a carriage return ('\r'), a line feed ('\n'), or a carriage return immediately followed by a line feed.
        /// The resulting string does not contain the terminating carriage return and/or line feed.
        /// </para>
        /// <para>The file handle is guaranteed to be closed by this method, even if exceptions are raised.</para>
        /// </remarks>
        ///
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains invalid characters as defined in <see cref="Path.GetInvalidPathChars"/></exception>
        /// <exception cref="ArgumentNullException">File path is <c>null</c>.</exception>
        /// <exception cref="PathTooLongException">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 File path is invalid, (dor example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="UnauthorizedAccessException">
        /// <para>File path specified a file that is read-only.</para>
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        /// <exception cref="FileNotFoundException">The file specified in File path was not found.</exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        public static Task<string> ReadAllTextAsync(this FileInfo fileInfo)
        {
            return AsyncFile.ReadAllTextAsync(fileInfo.FullName);
        }

        /// <summary>
        /// Opens a file, asynchronously reads all lines of the file, and then closes the file.
        /// </summary>
        ///
        /// <param name="encoding">The encoding applied to the contents of the file.</param>
        ///
        /// <returns>A task with a string containing all lines of the file.</returns>
        ///
        /// <remarks>
        /// <para>
        /// This method opens a file, reads each line of the file, and then adds each line as an element of a string. It then closes the file.
        /// A line is defined as a sequence of characters followed by a carriage return ('\r'), a line feed ('\n'), or a carriage return immediately followed by a line feed.
        /// The resulting string does not contain the terminating carriage return and/or line feed.
        /// </para>
        /// <para>The file handle is guaranteed to be closed by this method, even if exceptions are raised.</para>
        /// </remarks>
        ///
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains invalid characters as defined in <see cref="Path.GetInvalidPathChars"/></exception>
        /// <exception cref="ArgumentNullException">File path is <c>null</c>.</exception>
        /// <exception cref="PathTooLongException">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 File path is invalid, (dor example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="UnauthorizedAccessException">
        /// <para>File path specified a file that is read-only.</para>
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        /// <exception cref="FileNotFoundException">The file specified in File path was not found.</exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        public static Task<string> ReadAllTextAsync(this FileInfo fileInfo, Encoding encoding)
        {
            return AsyncFile.ReadAllTextAsync(fileInfo.FullName, encoding);
        }

        #endregion

        #region WriteAllBytesAsync

        /// <summary>
        /// Creates a new file, asynchronously writes the specified byte array to the file, and then closes the file.
        /// If the target file already exists, it is overwritten.
        /// </summary>
        ///
        /// <param name="bytes">The bytes to write to the file.</param>
        ///
        /// <returns>Task that represents asynchronous operation.</returns>
        ///
        /// <remarks>Given a byte array, this method opens the specified file, writes the contents of the byte array to the file, and then closes the file.</remarks>
        ///
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains invalid characters as defined in <see cref="Path.GetInvalidPathChars"/></exception>
        /// <exception cref="ArgumentNullException">File path or <paramref name="bytes"/> is <c>null</c></exception>
        /// <exception cref="PathTooLongException">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 specified path is invalid (for example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="UnauthorizedAccessException">
        /// <para>File path specified a file that is read-only.</para>
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        public static Task WriteAllBytesAsync(this FileInfo fileInfo, byte[] bytes)
        {
            return AsyncFile.WriteAllBytesAsync(fileInfo.FullName, bytes);
        }

        /// <summary>
        /// Creates a new file, asynchronously writes the specified byte array to the file, and then closes the file.
        /// If the target file already exists, it is overwritten.
        /// </summary>
        ///
        /// <param name="bytes">The bytes to write to the file.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        ///
        /// <returns>Task that represents asynchronous operation.</returns>
        ///
        /// <remarks>Given a byte array, this method opens the specified file, writes the contents of the byte array to the file, and then closes the file.</remarks>
        ///
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains invalid characters as defined in <see cref="Path.GetInvalidPathChars"/></exception>
        /// <exception cref="ArgumentNullException">File path or <paramref name="bytes"/> is <c>null</c></exception>
        /// <exception cref="PathTooLongException">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 specified path is invalid (for example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="UnauthorizedAccessException">
        /// <para>File path specified a file that is read-only.</para>
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        public static Task WriteAllBytesAsync(this FileInfo fileInfo, byte[] bytes, CancellationToken cancellationToken)
        {
            return AsyncFile.WriteAllBytesAsync(fileInfo.FullName, bytes, cancellationToken);
        }

        #endregion

        #region WriteAllLinesAsync

        /// <summary>
        /// Creates a new file, asynchronously writes a collection of strings to the file, and then closes the file.
        /// </summary>
        ///
        /// <param name="contents">The lines to write to the file.</param>
        ///
        /// <returns>Task that represents asynchronous operation.</returns>
        ///
        /// <remarks>If the target file already exists, it is overwritten.</remarks>
        ///
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains invalid characters as defined in <see cref="Path.GetInvalidPathChars"/></exception>
        /// <exception cref="ArgumentNullException">File path or <paramref name="contents"/> is <c>null</c></exception>
        /// <exception cref="DirectoryNotFoundException">File path is invalid (for example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="PathTooLongException">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="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        /// <exception cref="UnauthorizedAccessException">
        /// <para>File path specified a file that is read-only.</para>
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        public static Task WriteAllLinesAsync(this FileInfo fileInfo, IEnumerable<string> contents)
        {
            return AsyncFile.WriteAllLinesAsync(fileInfo.FullName, contents);
        }

        /// <summary>
        /// Creates a new file, asynchronously writes a collection of strings to the file, and then closes the file.
        /// </summary>
        ///
        /// <param name="contents">The lines to write to the file.</param>
        /// <param name="encoding">The character encoding to use.</param>
        ///
        /// <returns>Task that represents asynchronous operation.</returns>
        ///
        /// <remarks>If the target file already exists, it is overwritten.</remarks>
        ///
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains invalid characters as defined in <see cref="Path.GetInvalidPathChars"/></exception>
        /// <exception cref="ArgumentNullException">File path or <paramref name="contents"/> is <c>null</c></exception>
        /// <exception cref="DirectoryNotFoundException">File path is invalid (for example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="PathTooLongException">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="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        /// <exception cref="UnauthorizedAccessException">
        /// <para>File path specified a file that is read-only.</para>
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        public static Task WriteAllLinesAsync(this FileInfo fileInfo, IEnumerable<string> contents, Encoding encoding)
        {
            return AsyncFile.WriteAllLinesAsync(fileInfo.FullName, contents, encoding);
        }

        /// <summary>
        /// Creates a new file, asynchronously writes a collection of strings to the file, and then closes the file.
        /// </summary>
        ///
        /// <param name="contents">The lines to write to the file.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        ///
        /// <returns>Task that represents asynchronous operation.</returns>
        ///
        /// <remarks>If the target file already exists, it is overwritten.</remarks>
        ///
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains invalid characters as defined in <see cref="Path.GetInvalidPathChars"/></exception>
        /// <exception cref="ArgumentNullException">File path or <paramref name="contents"/> is <c>null</c></exception>
        /// <exception cref="DirectoryNotFoundException">File path is invalid (for example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="PathTooLongException">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="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        /// <exception cref="UnauthorizedAccessException">
        /// <para>File path specified a file that is read-only.</para>
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        public static Task WriteAllLinesAsync(this FileInfo fileInfo, IEnumerable<string> contents, CancellationToken cancellationToken)
        {
            return AsyncFile.WriteAllLinesAsync(fileInfo.FullName, contents, cancellationToken);
        }

        /// <summary>
        /// Creates a new file, asynchronously writes a collection of strings to the file, and then closes the file.
        /// </summary>
        ///
        /// <param name="contents">The lines to write to the file.</param>
        /// <param name="encoding">The character encoding to use.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        ///
        /// <returns>Task that represents asynchronous operation.</returns>
        ///
        /// <remarks>If the target file already exists, it is overwritten.</remarks>
        ///
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains invalid characters as defined in <see cref="Path.GetInvalidPathChars"/></exception>
        /// <exception cref="ArgumentNullException">File path or <paramref name="contents"/> is <c>null</c></exception>
        /// <exception cref="DirectoryNotFoundException">File path is invalid (for example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="PathTooLongException">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="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        /// <exception cref="UnauthorizedAccessException">
        /// <para>File path specified a file that is read-only.</para>
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        public static Task WriteAllLinesAsync(this FileInfo fileInfo, IEnumerable<string> contents, Encoding encoding, CancellationToken cancellationToken)
        {
            return AsyncFile.WriteAllLinesAsync(fileInfo.FullName, contents, encoding, cancellationToken);
        }

        #endregion

        #region WriteAllTextAsync

        /// <summary>
        /// Creates a new file, asynchronously writes the specified string to the file, and then closes the file.
        /// If the target file already exists, it is overwritten.
        /// </summary>
        ///
        /// <param name="contents">The string to write to the file.</param>
        ///
        /// <returns>Task that represents asynchronous operation.</returns>
        ///
        /// <remarks>If the target file already exists, it is overwritten.</remarks>
        ///
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains invalid characters as defined in <see cref="Path.GetInvalidPathChars"/></exception>
        /// <exception cref="ArgumentNullException">File path or <paramref name="contents"/>is <c>null</c></exception>
        /// <exception cref="PathTooLongException">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">File path is invalid (for example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        /// <exception cref="UnauthorizedAccessException">
        /// <para>File path specified a file that is read-only.</para>
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        public static Task WriteAllTextAsync(this FileInfo fileInfo, string contents)
        {
            return AsyncFile.WriteAllTextAsync(fileInfo.FullName, contents);
        }

        /// <summary>
        /// Creates a new file, asynchronously writes the specified string to the file, and then closes the file.
        /// If the target file already exists, it is overwritten.
        /// </summary>
        ///
        /// <param name="contents">The string to write to the file.</param>
        /// <param name="encoding">The encoding to apply to the string.</param>
        ///
        /// <returns>Task that represents asynchronous operation.</returns>
        ///
        /// <remarks>If the target file already exists, it is overwritten.</remarks>
        ///
        /// <exception cref="ArgumentException">File path is a zero-length string, contains only white space, or contains invalid characters as defined in <see cref="Path.GetInvalidPathChars"/></exception>
        /// <exception cref="ArgumentNullException">File path or <paramref name="contents"/>is <c>null</c></exception>
        /// <exception cref="PathTooLongException">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">File path is invalid (for example, it is on an unmapped drive).</exception>
        /// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
        /// <exception cref="NotSupportedException">File path is in an invalid format.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission.</exception>
        /// <exception cref="UnauthorizedAccessException">
        /// <para>File path specified a file that is read-only.</para>
        /// <para>-or-</para>
        /// <para>This operation is not supported on the current platform.</para>
        /// <para>-or-</para>
        /// <para>The caller does not have the required permission.</para>
        /// </exception>
        public static Task WriteAllTextAsync(this FileInfo fileInfo, string contents, Encoding encoding)
        {
            return AsyncFile.WriteAllTextAsync(fileInfo.FullName, contents, encoding);
        }

        #endregion
    }
}


text:
package war.cs;

import java.util.List;
import org.skfiy.typhon.domain.item.Gender;
import org.skfiy.typhon.script.Script;
import org.skfiy.typhon.session.Session;
import org.skfiy.typhon.spi.war.FightObject;

/**
 * 祝融.
 *
 * @author Kevin Zou <kevinz@skfiy.org>
 */
public class L_s042 implements Script {

    @Override
    public Object invoke(Session session, Object obj) {
        List<FightObject> objs = (List<FightObject>) obj;
        for (FightObject fo : objs) {
            if (fo.getGender() == Gender.Female) {
                fo.setMaxParryRate(fo.getMaxParryRate() + 0.15);
            }
        }
        return null;
    }

}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>LineaLeastSquares.jl Examples — LLS 0.1 documentation</title>

    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="LLS 0.1 documentation" href="index.html" />
    <link rel="next" title="Credits" href="credits.html" />
    <link rel="prev" title="LinearLeastSquares.jl Tutorial" href="julia_tutorial.html" />

Navigation

          index

          next |

          previous |

LLS 0.1 documentation »

LineaLeastSquares.jl Examples¶

This tutorial showcases LinearLeastSquares.jl through a few involved examples of linearly
constrained least squares problems. We’ll refer to LinearLeastSquares.jl as “LLS”
throughout.
The plots generated by the following examples use the Gadfly package.
The documentation on how to use Gadfly can be found here,
but by no means is it necessary to read unless you would like to create plots for yourself.
To install Gadfly, run the following command in a Julia shell

Pkg.add("Gadfly")

Some of the examples will also use data files, which can all be found here.

Regression¶

Regression is the problem of trying to fit a function to some data.
In this example, we will frame some simple regression problems as
unconstrained least squares problems for LLS to solve.

We are given n points, represented by two n-by-1 vectors, <tt class="docutils literal">x_data</tt> and <tt class="docutils literal">y_data</tt>. The x and y coordinates of the i-th point are given by the i-th entries of <tt class="docutils literal">x_data</tt> and <tt class="docutils literal">y_data</tt>, respectively.

We’ll start by generating and visualizing some data to get a better sense of the problem at hand:

# Set the random seed to get consistent data
srand(1)

# Number of examples to use
n = 100

# Specify the true value of the variable
true_coeffs = [2; -2; 0.5]

# Generate data
x_data = rand(n, 1) * 5
x_data_expanded = hcat([x_data .^ i for i in 1 : 3]...)
y_data = x_data_expanded * true_coeffs + 0.5 * rand(n, 1)

p = plot(
  x=x_data, y=y_data, Geom.point,
  Theme(panel_fill=color("white"))
)

The following graph of the data will appear

Linear Regression¶

We will first try to fit a line to the data. A general function for a line is

\[f(x) = \alpha + \beta x\]

where \(\alpha\) is the offset and \(\beta\) is the slope.
We would like to pick \(\alpha\) and \(\beta\) so that our data points lie “close” to
our line. For a point with coordinates \(x\) and \(y\) the residual between the point
and our line is defined as

\[r(x, y) = f(x) - y.\]

One reasonable way to measure the how different line is from the data is to
sum the squares of the residuals between each point in the data and the line:

\[E(\alpha, \beta) = \sum_{i = 1}^n (r(x_i, y_i))^2 = \sum_{i = 1}^n (\alpha + \beta x_i - y_i)^2.\]

We would like to choose \(\alpha\) and \(\beta\) to minimize this error.
We can now frame this problem in Julia code and solve our problem using LLS:

slope = Variable()
offset = Variable()
line = offset + x_data * slope
residuals = line - y_data
fit_error = sum_squares(residuals)
optval = minimize!(fit_error)

# plot the data and the line
t = [0; 5; 0.1]
p = plot(
  layer(x=x_data, y=y_data, Geom.point),
  layer(x=t, y=evaluate(slope) * t + evaluate(offset), Geom.line),
  Theme(panel_fill=color("white"))
)

The line of best fit on our data is shown below:

Quadratic Regression¶

A line is probably not the best function to fit to this data. Instead, let’s try
to fit a quadratic function, which has the form:

\[f(x) = \alpha + \beta x + \gamma x ^ 2\]

where the new coefficient \(\gamma\) corresponds to the quadratic term
A similar residual function from the linear regression example can be used here;
we measure the error of our quadratic fit by summing the squares of the
residuals

\[E(\alpha, \beta, \gamma) = \sum_{i = 1}^n (r(x_i, y_i))^2 = \sum_{i = 1}^n (\alpha + \beta x_i + \gamma x_i^2 - y_i)^2.\]

Again, we pick our coefficients to minimize the error.
Here is the Julia code to solve this problem using LLS and plot the quadratic:

quadratic_coeff = Variable()
slope = Variable()
offset = Variable()
quadratic = offset + x_data * slope + quadratic_coeff * x_data .^ 2
residuals = quadratic - y_data
fit_error = sum_squares(residuals)
optval = minimize!(fit_error)

# Create some evenly spaced points for plotting, again replicate powers
t = reshape([0 : 0.1 : 5], length([0 : 0.1 : 5]), 1)
t_squared = t .^ 2

# Plot our regressed function
p = plot(
  layer(x=x_data, y=y_data, Geom.point),
  layer(x=t, y=evaluate(offset) + t * evaluate(slope) + t_squared * evaluate(quadratic_coeff), Geom.line),
  Theme(panel_fill=color("white"))
)

A much better fit than the line!

Control¶

A simple control problem on a system usually involves a variable \(x(t)\)
that denotes the state of the system over time, and a variable \(u(t)\) that
denotes the input into the system over time. Linear constraints are used to
capture the evolution of the system over time:

\[x(t) = Ax(t - 1) + Bu(t), \ \mbox{for} \ t = 1,\ldots, T,\]

where the numerical matrices \(A\) and \(B\) are called the dynamics and input matrices,
respectively.

The goal of the control problem is to find a sequence of inputs
\(u(t)\) that will allow the state \(x(t)\) to achieve specified values
at certain times. For example, we can specify initial and final states of the system:

\[\begin{split}\begin{align*}
  x(0) &= x_i \\
  x(T) &= x_f
\end{align*}\end{split}\]

Additional states between the initial and final states can also be specified. These
are known as waypoint constraints. Often, the input and state of the system will
have physical meaning, so we often want to find a sequence inputs that also
minimizes a least squares objective like the following:

\[\sum_{t = 0}^T \|Fx(t)\|^2_2 + \sum_{t = 1}^T\|Gu(t)\|^2_2,\]

where \(F\) and \(G\) are numerical matrices.

We’ll now apply the basic format of the control problem to an example of controlling
the motion of an object in a fluid over \(T\) intervals, each of \(h\) seconds.
The state of the system at time interval \(t\) will be given by the position and the velocity of the
object, denoted \(p(t)\) and \(v(t)\), while the input will be forces
applied to the object, denoted by \(f(t)\).
By the basic laws of physics, the relationship between force, velocity, and position
must satisfy:

\[\begin{split}\begin{align*}
  p(t+1) &= p(t) + h v(t) \\
  v(t+1) &= v(t) + h a(t)
\end{align*}.\end{split}\]

Here, \(a(t)\) denotes the acceleration at time \(t\), for which we we use
\(a(t) = f(t) / m + g - d v(t)\),
where \(m\), \(d\), \(g\) are constants for the mass of the object, the drag
coefficient of the fluid, and the acceleration from gravity, respectively.

Additionally, we have our initial/final position/velocity conditions:

\[\begin{split}\begin{align*}
  p(1) &= p_i\\
  v(1) &= v_i\\
  p(T+1) &= p_f\\
  v(T+1) &= 0
\end{align*}\end{split}\]

One reasonable objective to minimize would be

\[\mbox{objective} = \mu \sum_{t = 1}^{T+1} (v(t))^2 + \sum_{t = 1}^T (f(t))^2\]

We would like to keep both the forces small to perhaps save fuel, and keep
the velocities small for safety concerns.
Here \(\mu\) serves as a parameter to control which part of the objective we
deem more important, keeping the velocity small or keeping the force small.

The following code builds and solves our control example:

# Some constraints on our motion
# The object should start from the origin, and end at rest
initial_velocity = [-20; 100]
final_position = [100; 100]

T = 100 # The number of timesteps
h = 0.1 # The time between time intervals
mass = 1 # Mass of object
drag = 0.1 # Drag on object
g = [0, -9.8] # Gravity on object

# Declare the variables we need
position = Variable(2, T)
velocity = Variable(2, T)
force = Variable(2, T - 1)

# Create a problem instance
mu = 1
constraints = []

# Add constraints on our variables
for i in 1 : T - 1
  constraints += position[:, i + 1] == position[:, i] + h * velocity[:, i]
end

for i in 1 : T - 1
  acceleration = force[:, i]/mass + g - drag * velocity[:, i]
  constraints += velocity[:, i + 1] == velocity[:, i] + h * acceleration
end

# Add position constraints
constraints += position[:, 1] == 0
constraints += position[:, T] == final_position

# Add velocity constraints
constraints += velocity[:, 1] == initial_velocity
constraints += velocity[:, T] == 0

# Solve the problem
optval = minimize!(sum_squares(force), constraints)

We can plot the trajectory taken by the object. The blue point denotes the initial
position, and the green point denotes the final position.

pos = evaluate(position)
p = plot(
  layer(x=[pos[1, 1]], y=[pos[2, 1]], Geom.point, Theme(default_color=color("blue"))),
  layer(x=[pos[1, T]], y=[pos[2, T]], Geom.point, Theme(default_color=color("green"))),
  layer(x=pos[1, :], y=pos[2, :], Geom.line(preserve_order=true)),
  Theme(panel_fill=color("white"))
)

We can also see how the magnitude of the force changes over time.

p = plot(x=1:T, y=sum(evaluate(force).^2, 1), Geom.line, Theme(panel_fill=color("white")))

Image Processing¶

Tomography¶

Tomography is the process of reconstructing a density distribution from given
integrals over sections of the distribution. In our example, we will
work with tomography on black and white images.
Suppose \(x\) be the vector of \(n\) pixel densities, with \(x_j\)
denoting how white pixel \(j\) is.
Let \(y\) be the vector of \(m\) line integrals over the image, with \(y_i\)
denoting the integral for line \(i\).
We can define a matrix \(A\) to describe the geometry of the lines. Entry
\(A_{ij}\) describes how much of pixel \(j\) is intersected by line \(i\).
Assuming our measurements of the line integrals are perfect, we have the relationship that

\[y = Ax\]

However, anytime we have measurements, there are usually small errors that occur.
Therefore it makes sense to try to minimize

\[\|y - Ax\|_2^2.\]

This is simply an unconstrained least squares problem; something we can
readily solve in LLS!

line_mat_x = readdlm("tux_sparse_x.txt")
line_mat_y = readdlm("tux_sparse_y.txt")
line_mat_val = readdlm("tux_sparse_val.txt")
line_vals = readdlm("tux_sparse_lines.txt")

# Form the sparse matrix from the data
# Image is 50 x 50
img_size = 50
# The number of pixels in the image
num_pixels = img_size * img_size

line_mat = spzeros(3300, num_pixels)

num_vals = length(line_mat_val)

for i in 1:num_vals
  x = int(line_mat_x[i])
  y = int(line_mat_y[i])
  line_mat[x + 1, y + 1] = line_mat_val[i]
end

x = Variable(num_pixels)
objective = sum_squares(line_mat * x - line_vals)
optval = minimize!(objective)

rows = zeros(img_size*img_size)
cols = zeros(img_size*img_size)
for i = 1:img_size
  for j = 1:img_size
    rows[(i-1)*img_size + j] = i
    cols[(i-1)*img_size + j] = img_size + 1 - j
  end
end

p = plot(
  x=rows, y=cols, color=reshape(evaluate(x), img_size, img_size), Geom.rectbin,
  Scale.ContinuousColorScale(Scale.lab_gradient(color("black"), color("white")))
)

The final result of the tomography will look something like

Machine Learning¶

Binary Classification¶

One common problem found in machine learning is the classification of a group of objects into two subgroups.
In this example, we will try to separate sports articles from
other texts in a collection of documents.

When classifying text documents, one of the most common techniques is to build
a term-by-document frequency matrix \(F\), where \(F_{ij}\)
reflects the frequency of term \(j\) in document \(i\).

The documents are then split into a training and testing set. For each document
in the training example, we also label the document with a label. In this case,
sports articles are labelled with a \(1\) and all other text documents are
labelled with a \(-1\).
One reasonable approach to classify the documents is to model the label
as an affine function of the term frequencies of the document:

\[\mbox{label}(i) = v + \sum_{j = 1}^n w_jF_{ij}.\]

The goal now is to find a scalar \(v\) and a weight vector \(w\), where \(w_j\) reflects how
important term \(j\) is in determining the label of the document. In our context, a positive value
means that the term is often seen in sports articles, while a negative value means
the term is often seen in the other documents. One reasonable approach to
finding the best \(w\) and \(v\) is to minimize the following objective:

\[\sum_{i = 1}^m  \left(\mbox{label}(i) - v - \sum_{j = 1}^n w_jF_{ij}\right)^2 + \lambda \sum_{j = 1}^n w_j^2\]

The first part of the objective is to ensure that our linear model actually closely
reproduces the labels of our training documents. The second part of the objective
ensures that the components of \(w\) are relatively small.
Keeping \(w\) small allows our model to behave better on documents not in the training set.
The regularization parameter \(\lambda\)
is used to control how much we should prioritize keeping \(w\) small versus
how close the affine function should fit the labels.

Here is the LLS code:

# read in the data
include("MatrixMarket.jl")
using MatrixMarket
A = full(MatrixMarket.mmread("largeCorpus.mtx"))

# extract the classes of each document
classes = A[:,1]
# TODO: modify classes so that 4 5 6 are 1 2 3
classes[classes .> 3] = classes[classes .> 3] - 3
A = A[:, 2:end]

# split into train/test
numData = size(A, 1)
data = randperm(numData)
ind = floor(numData*0.7)
training = data[1:ind]
test = data[ind+1:end]
trainDocuments = A[training,:]
trainClasses = classes[training,:]
testDocuments = A[test,:]
testClasses = classes[test,:]

# change all other than sports to -1 (sports is 1)
holdClass = 1
trainClasses[trainClasses .!= holdClass] = -1
trainClasses[trainClasses .== holdClass] = 1
testClasses[testClasses .!= holdClass] = -1
testClasses[testClasses .== holdClass] = 1

# build the problem and solve with LLS
lambda = 100
w = Variable(size(A, 2))
v = Variable()
objective = sum_squares(trainDocuments * w + v - trainClasses) + lambda * sum_squares(w)
optval = minimize!(objective)

We can now sort our weight vector \(w\) to see which words were the most
indicative of sports articles and which were most indicative of nonsports.

# print out the 5 words most indicative of sports and nonsports
words = String[]
f = open("largeCorpusfeatures.txt")
for i = 1:length(evaluate(w))
  push!(words, readline(f))
end
indices = sortperm(vec(evaluate(w)))
for i = 1:5
  print(words[indices[i]])
end
for i = 0:4
  print(words[indices[length(words) - i]])
end

Each run will yield different words, but it’ll be clear which words
come from sports articles.

Time Series Analysis¶

A time series is a sequence of data points, each associated with a time.
In our example, we will work with a time series of daily
temperatures in the city of Melbourne, Australia over a period of a few years.
Let \(x\) be the vector of the time series, and \(x_i\) denote
the temperature in Melbourne on day \(i\).
Here is a picture of the time series:

We can quickly compute the mean of the time series to be \(11.2\). If
we were to always guess the mean as the temperature of Melbourne on a given day,
the RMS error of our guesswork would be \(4.1\). We’ll try to lower
this RMS error by coming up with better ways to model the temperature than
guessing the mean.

A simple way to model this time series would be to find a smooth curve that
approximates the yearly ups and downs.
We can represent this model as a vector \(s\) where \(s_i\)
denotes the temperature on the \(i\)-th day.
To force this trend to repeat yearly, we simply want

\[s_i = s_{i + 365}\]

for each applicable \(i\).

We also want our model to have two more properties. The first is that
the temperature on each day in our model should be relatively close to the actual temperature of that day.
The second is that our model needs to be smooth, so the change in temperature from day to
day should be relatively small. The following objective would capture both properties:

\[\sum_{i = 1}^n (s_i - x_i)^2 + \lambda \sum_{i = 2}^n(s_i - s_{i - 1})^2\]

where \(\lambda\) is the smoothing parameter. The larger \(\lambda\) is,
the smoother our model will be.

The following code uses LLS to find and plot the model:

temps = readdlm("melbourne_temps.txt", ',')
n = size(temps)[1]
p = plot(
  x=1:1500, y=temps[1:1500], Geom.line,
  Theme(panel_fill=color("white"))
)
# draw(PNG("melbourne.png", 16cm, 12cm), p)

yearly = Variable(n)
eq_constraints = []
for i in 365 + 1 : n
  eq_constraints += yearly[i] == yearly[i - 365]
end

smoothing = 100
smooth_objective = sum_squares(yearly[1 : n - 1] - yearly[2 : n])
optval = minimize!(sum_squares(temps - yearly) + smoothing * smooth_objective, eq_constraints)
residuals = temps - evaluate(yearly)

# Plot smooth fit
p = plot(
  layer(x=1:1500, y=evaluate(yearly)[1:1500], Geom.line, Theme(default_color=color("red"), line_width=2px)),
  layer(x=1:1500, y=temps[1:1500], Geom.line),
  Theme(panel_fill=color("white"))
)

We can also plot the residual temperatures, \(r\), define as \(r = x - s\).

# Plot residuals for a few days
p = plot(
  x=1:100, y=residuals[1:100], Geom.line,
  Theme(default_color=color("green"), panel_fill=color("white"))
)

Our smooth model has a RMS error of \(2.7\), a significant improvement from
just guessing the mean, but we can do better.

We now make the hypothesis that the residual temperature on a given day is
some linear combination of the previous \(5\) days. Such a model is called
autoregressive. We are essentially trying to fit the residuals
as a function of other parts of the data itself.
We want to find a vector of coefficients \(a\) such that

\[\mbox{r}(i) \approx \sum_{j = 1}^5 a_j \mbox{r}(i - j)\]

This can be done by simply minimizing the following sum of squares objective

\[\sum_{i = 6}^n \left(\mbox{r}(i) - \sum_{j = 1}^5 a_j \mbox{r}(i - j)\right)^2\]

The following LLS code solves this problem and plots our autoregressive model
against the actual residual temperatures:

# Generate the residuals matrix
ar_len = 5
residuals_mat = residuals[ar_len : n - 1]
for i = 1:ar_len - 1
  residuals_mat = [residuals_mat residuals[ar_len - i : n - i - 1]]
end

# Solve autoregressive problem
ar_coef = Variable(ar_len)
optval2 = minimize!(sum_squares(residuals_mat * ar_coef - residuals[ar_len + 1 : end]))

# plot autoregressive fit of daily fluctuations for a few days
ar_range = 1:145
day_range = ar_range + ar_len
p = plot(
  layer(x=day_range, y=residuals[day_range], Geom.line, Theme(default_color=color("green"))),
  layer(x=day_range, y=residuals_mat[ar_range, :] * evaluate(ar_coef), Geom.line, Theme(default_color=color("red"))),
  Theme(panel_fill=color("white"))
)

Now, we can add our autoregressive model for the residual temperatures to our
smooth model to get an better fitting model for the daily temperatures in the city of
Melbourne:

total_estimate = evaluate(yearly)
total_estimate[ar_len + 1 : end] += residuals_mat * evaluate(ar_coef)

# plot final fit of data
p = plot(
  layer(x=1:1500, y=total_estimate[1:1500], Geom.line, Theme(default_color=color("red"))),
  layer(x=1:1500, y=temps[1:1500], Geom.line),
  Theme(panel_fill=color("white"))
)

The RMS error of this final model is \(2.3\).

Table Of Contents

LineaLeastSquares.jl Examples

Regression

Linear Regression

Quadratic Regression

Control

Image Processing

Tomography

Machine Learning

Binary Classification

Time Series Analysis

Previous topic

LinearLeastSquares.jl Tutorial

Next topic

Credits

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

LLS 0.1 documentation »

        © Copyright 2014, David Zeng, Keegan Go, Karanveer Mohan.
      Created using Sphinx 1.2.2.


text:
.ui-select-bootstrap .ui-select-choices-row>a {
  white-space: normal!important;
}

.ui-select-bootstrap .form-control.ui-select-match {
  height: auto!important;
  white-space: normal!important;
}

.ui-select-bootstrap .ui-select-match .btn span {
  white-space: normal!important;
}

.dropdown-menu:before {
  position: absolute;
  top: -7px;
  left: 9px;
  display: inline-block;
  border-right: 7px solid transparent;
  border-bottom: 7px solid #ccc;
  border-left: 7px solid transparent;
  border-bottom-color: rgba(0, 0, 0, 0.2);
  content: '';
}

.dropdown-menu:after {
  position: absolute;
  top: -6px;
  left: 10px;
  display: inline-block;
  border-right: 6px solid transparent;
  border-bottom: 6px solid #ffffff;
  border-left: 6px solid transparent;
  content: '';
}

.dropdown-menu-right:before {
  right: 9px!important;
  left: inherit!important;
}

.dropdown-menu-right:after {
  right: 9px!important;
  left: inherit!important;
}

.dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus {
  background-color: #e5e5e5;
  color: #333;
}

.dropdown-menu > li > a > .fa {
  padding: 6px 12px 6px 0px;
}

.dropdown-menu-subgroup {
  list-style: none;
  padding: 0px;
}

.dropdown-menu-subgroup > li > a {
  clear: both;
  color: #333;
  display: block;
  font-weight: normal;
  line-height: 1.42857;
  padding: 3px 20px;
  white-space: nowrap;
}

.dropdown-menu-subgroup > li > a:hover,  .dropdown-menu-subgroup > li > a:focus {
  background: #e5e5e5;
  color: #333;
  text-decoration: none;
}

body > .ui-select-bootstrap.open {
  z-index: 2000;
}

.popover {
  max-width: 350px;
}

.ui-autocomplete {
  position: absolute;
  top: 0;
  left: 0;
  cursor: default;
  z-index: 1060;
  list-style: none;
  padding: 0;
  margin: 0;
  display: block;
  outline: none;
  border: 1px solid #ccc;
  color: #333333;
  background: #fff;
}

.ui-autocomplete li {
  position: relative;
  margin: 0;
  padding: 3px 1em 3px .4em;
  cursor: pointer;
  min-height: 0;
}

.ui-state-hover, .ui-state-focus,
.ui-autocomplete li:focus,
.ui-autocomplete li:hover {
  background: #f5f5f5;
}

.ui-autocomplete li a {
  color: #333333;
}

.datepicker {
  z-index: 1050!important;
}


text:
package org.apache.sling.hapi;

/**
 * A Hypermedia API exception
 */
public class HApiException extends RuntimeException {

    private static final long serialVersionUID = 2626376214501558054L;

    public HApiException() {
    }

    /**
     *
     * @param message
     */
    public HApiException(String message) {
        super(message);
    }

    /**
     *
     * @param message
     * @param cause
     */
    public HApiException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     *
     * @param cause
     */
    public HApiException(Throwable cause) {
        super(cause);
    }
}


text:
package cdc.impl.join.dnm;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cdc.components.AbstractDataSource;
import cdc.components.AbstractDistance;
import cdc.components.AbstractJoin;
import cdc.components.AbstractJoinCondition;
import cdc.components.EvaluatedCondition;
import cdc.components.LinkageSummary;
import cdc.datamodel.DataColumnDefinition;
import cdc.datamodel.DataRow;
import cdc.gui.GUIVisibleComponent;
import cdc.impl.conditions.WeightedJoinCondition;
import cdc.impl.datasource.sampling.DataSampleInterface;
import cdc.impl.datasource.sampling.RandomSampler;
import cdc.impl.join.blocking.BucketManager;
import cdc.impl.join.blocking.BlockingFunction;
import cdc.utils.HTMLUtils;
import cdc.utils.Props;
import cdc.utils.RJException;
import cdc.utils.RowUtils;

//Assume: distance is 0..100 (100 is the closest!!)

public class DNMJoin extends AbstractJoin {

	public static final String PROP_CLUSTER_PARAMS = "clustering-params";
	private static final int MAX_COMPARISONS = 	Props.getInteger("dnm-max-comparisons-factor");
	private static final int MAX_SL_COMPARISONS = Props.getInteger("dnm-max-second-level-comparisons-factor");

	private boolean closed = false;

	private KMeansClusterer clusterer;
	private BucketManager buckets;
	private DataRow[][] activeBucket;

	private int index1;
	private int index2;
	private boolean secondLevelActive = false;
	private BucketManager secondLevel;
	private boolean sampleLeft = false;
	private DataColumnDefinition[] sampledSourceColumns;
	private ClusteringDistance[] clusteringDistances;
	private BlockingFunction hash;
	private DataColumnDefinition[][] clusteringColumns;

	public DNMJoin(AbstractDataSource sourceA, AbstractDataSource sourceB, AbstractJoinCondition condition,
			DataColumnDefinition[] outColumns, Map params) throws IOException, RJException {
		super(fixSource(sourceA, condition.getLeftJoinColumns()),
				fixSource(sourceB, condition.getRightJoinColumns()), condition, outColumns, params);

		String ids = (String) params.get(PROP_CLUSTER_PARAMS);
		if (ids == null) {
			throw new RJException("Configuration of ClusteringJoin requires parameter " + PROP_CLUSTER_PARAMS + ". Please verify the configuration.");
		}
		String[] idsT = ids.split(",");
		int[] idsInt = new int[idsT.length];
		for (int i = 0; i < idsInt.length; i++) {
			idsInt[i] = Integer.parseInt(idsT[i]);
		}

		AbstractDistance[] distances = new AbstractDistance[idsInt.length];
		DataColumnDefinition[] leftCols = new DataColumnDefinition[idsInt.length];
		DataColumnDefinition[] rightCols = new DataColumnDefinition[idsInt.length];
		for (int i = 0; i < distances.length; i++) {
			distances[i] = condition.getDistanceFunctions()[idsInt[i]];
		}
		for (int i = 0; i < leftCols.length; i++) {
			leftCols[i] = condition.getLeftJoinColumns()[idsInt[i]];
		}
		for (int i = 0; i < rightCols.length; i++) {
			rightCols[i] = condition.getRightJoinColumns()[idsInt[i]];
		}
		clusteringColumns = new DataColumnDefinition[][] {leftCols, rightCols};

		sampledSourceColumns = sampleLeft ? leftCols : rightCols;
		DataSampleInterface sampler = new RandomSampler(sourceB, 10);

		List data = new ArrayList();
		DataRow row;
		while ((row = sampler.getNextRow()) != null) {
			data.add(row);
		}
		System.out.println("Sampled " + data.size() + " records.");
		int k = data.size() / 50;
		if (k < 2) k = 2;
		if (k > 20) k = 20;
		if (condition instanceof WeightedJoinCondition) {
			double[] weights = ((WeightedJoinCondition)condition).getWeights();
			clusterer = new KMeansClusterer(k, 4, new DNMDistance(distances, sampledSourceColumns, sampledSourceColumns, weights));
		} else {
			clusterer = new KMeansClusterer(k, 4, new DNMDistance(distances, sampledSourceColumns, sampledSourceColumns));
		}

		clusterer.learn(data.toArray());

		sourceA.reset();
		sourceB.reset();

		clusteringDistances = new ClusteringDistance[2];
		if (condition instanceof WeightedJoinCondition) {
			double[] weights = ((WeightedJoinCondition)condition).getWeights();
			clusteringDistances[0] = new DNMDistance(distances, sampledSourceColumns, leftCols, weights);
			clusteringDistances[1] = new DNMDistance(distances, sampledSourceColumns, rightCols, weights);
		} else {
			clusteringDistances[0] = new DNMDistance(distances, sampledSourceColumns, leftCols);
			clusteringDistances[1] = new DNMDistance(distances, sampledSourceColumns, rightCols);
		}
		hash = new ClusterHashingFunction(clusterer.getCentroids(), clusteringDistances);
		buckets = new BucketManager(hash);

		while ((row = getSourceA().getNextRow()) != null) {
			buckets.addToBucketLeftSource(row);
		}
		while ((row = getSourceB().getNextRow()) != null) {
			buckets.addToBucketRightSource(row);
		}
	}

	private static AbstractDataSource fixSource(AbstractDataSource source, DataColumnDefinition[] order) throws IOException, RJException {
		return source;
//		if (source.canSort()) {
//			source.setOrderBy(order);
//			return source;
//		} else {
//			ExternallySortingDataSource sorter = new ExternallySortingDataSource(source.getSourceName(), source, order, new HashMap());
//			return sorter;
//		}
	}

	protected DataRow doJoinNext() throws IOException, RJException {
		while (true) {

			DataRow[][] activeBucket = getActiveOrNextBucket();
			if (activeBucket == null) {
				return null;
			}

			for (; index1 < activeBucket[0].length; index1++) {
				for (; index2 < activeBucket[1].length; index2++) {
					DataRow rowA = activeBucket[0][index1];
					DataRow rowB = activeBucket[1][index2];
					EvaluatedCondition eval;
					if ((eval = getJoinCondition().conditionSatisfied(rowA, rowB)).isSatisfied()) {
						DataRow joined = RowUtils.buildMergedRow(this, rowA, rowB, getOutColumns(), eval);
						if (isAnyJoinListenerRegistered()) {
							notifyJoined(rowA, rowB, joined);
						}
						index2++;
						return joined;
					} else {
						if (isAnyJoinListenerRegistered()) {
							notifyNotJoined(rowA, rowB, eval.getConfidence());
						}
					}

					if (isCancelled()) {
						return null;
					}
				}
				index2 = 0;
				if (activeBucket[0][index1].getProperty(PROPERTY_JOINED) != null) {
					notifyTrashingJoined(activeBucket[0][index1]);
				} else if (RowUtils.shouldReportTrashingNotJoined(this, activeBucket[0][index1])) {
					notifyTrashingNotJoined(activeBucket[0][index1]);
				}
			}

			for (index2=0; index2 < activeBucket[1].length; index2++) {
				if (activeBucket[1][index2].getProperty(PROPERTY_JOINED) != null) {
					notifyTrashingJoined(activeBucket[1][index2]);
				} else if (RowUtils.shouldReportTrashingNotJoined(this, activeBucket[1][index2])) {
					notifyTrashingNotJoined(activeBucket[1][index2]);
				}
			}
		}
	}

	public DataRow[][] getActiveOrNextBucket() throws IOException, RJException {
		if (activeBucket == null || (index1 == activeBucket[0].length)) {
			index1 = 0;
			if (secondLevelActive ) {
				DataRow[][] bucket = readFromManager(secondLevel);
				if (bucket == null) {
					secondLevelActive = false;
				} else {
					activeBucket = bucket;
					return activeBucket;
				}
			}
			DataRow[][] bucket = readFromManager(buckets);
			if (bucket == null) {
				return null;
			}
			System.out.println("Bucket: " + bucket[0].length + " <---> " + bucket[1].length);
			if (bucket[0].length * bucket[1].length > MAX_COMPARISONS) {
				secondLevelActive = true;

				//new cluster
				int sourceId = sampleLeft ? 0 : 1;
				//double percent = MAX_SL_COMPARISONS / (double)(bucket[0].length * bucket[1].length);
				//if (percent > 1) percent = 1;
				int k = (int) Math.sqrt((bucket[0].length * bucket[1].length / MAX_SL_COMPARISONS));
				if (k < 2) {
					k = 2;
				}
				if (k > 50) {
					k = 50;
				}
				System.out.println("Second level k=" + k);
				KMeansClusterer clustererSecondLevel  = new KMeansClusterer(k, 4, clusterer.getDistance());
				clustererSecondLevel.learn(bucket[sourceId]);

				//second level blocks
				secondLevel = new BucketManager(new ClusterHashingFunction(clustererSecondLevel.getCentroids(), clusteringDistances), false);
				for (int i = 0; i < bucket[0].length; i++) {
					secondLevel.addToBucketLeftSource(bucket[0][i]);
				}
				for (int i = 0; i < bucket[1].length; i++) {
					secondLevel.addToBucketRightSource(bucket[1][i]);
				}
				activeBucket = secondLevel.getBucket();
				System.out.println("Bucket: " + activeBucket[0].length + " <---> " + activeBucket[1].length);
			} else {
				activeBucket = bucket;
			}

		}
		return activeBucket;
	}

	private DataRow[][] readFromManager(BucketManager manager) throws IOException, RJException {
		DataRow[][] potentialBucket = null;
		do {
			potentialBucket = manager.getBucket();
			if (potentialBucket == null) {
				return null;
			}
		} while (potentialBucket[0].length == 0 || potentialBucket[1].length == 0);
		return potentialBucket;
	}

	protected DataRow[] doJoinNext(int size) throws IOException, RJException {
		List joinResult = new ArrayList();
		DataRow result;
		while (((result = joinNext()) != null) && joinResult.size() < size) {
			joinResult.add(result);
		}
		return (DataRow[]) joinResult.toArray(new DataRow[] {});
	}

	protected void doReset(boolean deep) throws IOException, RJException {
		getSourceA().reset();
		getSourceB().reset();
		closed = false;
	}

	protected void doClose() throws IOException, RJException {
		if (!closed) {
			getSourceA().close();
			getSourceB().close();
			closed = true;
		}
	}

	public String toString() {
		return "Distance neighbourhood method (under development)";
	}

	public static GUIVisibleComponent getGUIVisibleComponent() {
		return new DNMGUIVisibleComponent();
	}

	public String toHTMLString() {
		StringBuilder builder = new StringBuilder();
		builder.append(HTMLUtils.getHTMLHeader());
		builder.append(HTMLUtils.encodeTable(new String[][] {
				{"Search method:", "Clustering search method"},
			}));
		builder.append("
Clustering configuration:
");
		String[][] table = new String[clusteringDistances.length + 1][2];
		table[0][0] = "Attribute (" + getSourceA().getSourceName() + ")";
		table[0][1] = "Attribute (" + getSourceB().getSourceName() + ")";
		for (int i = 1; i < table.length; i++) {
			table[i][0] = clusteringColumns[0][i - 1].getColumnName();
			table[i][1] = clusteringColumns[1][i - 1].getColumnName();
		}
		builder.append(HTMLUtils.encodeTable(table, true));
		builder.append("
Attributes mapping and distance function selection:
");
		builder.append(HTMLUtils.encodeJoinCondition(getJoinCondition()));
		builder.append("");
		return builder.toString();
	}

	public LinkageSummary getLinkageSummary() {
		return null;
	}
}


text:
using System;
using System.Collections.Generic;
using Repo2.Core.ns11.DomainModels;

namespace Repo2.Core.ns11.RestExportViews
{
    public class ErrorsByStatus1 : R2ErrorTicket, IRestExportView
    {
        public string DisplayPath => "errors-by-status-1";

        public List<string> CastArguments(object[] args)
            //=> new List<string> { args[0].ToString() };
            => new List<string>();

        public void PostProcess()
        {
        }
    }
}