text:
package org.spongycastle.jce;

import java.io.UnsupportedEncodingException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import org.spongycastle.asn1.ASN1ObjectIdentifier;
import org.spongycastle.asn1.ASN1Primitive;
import org.spongycastle.asn1.cryptopro.CryptoProObjectIdentifiers;
import org.spongycastle.asn1.pkcs.PrivateKeyInfo;
import org.spongycastle.asn1.x509.AlgorithmIdentifier;
import org.spongycastle.asn1.x509.SubjectPublicKeyInfo;
import org.spongycastle.asn1.x9.X962Parameters;
import org.spongycastle.asn1.x9.X9ECParameters;
import org.spongycastle.asn1.x9.X9ObjectIdentifiers;
import org.spongycastle.jcajce.provider.asymmetric.util.ECUtil;
import org.spongycastle.jce.provider.BouncyCastleProvider;

/**
 * Utility class to allow conversion of EC key parameters to explicit from named
 * curves and back (where possible).
 */
public class ECKeyUtil
{
    /**
     * Convert a passed in public EC key to have explicit parameters. If the key
     * is already using explicit parameters it is returned.
     *
     * @param key key to be converted
     * @param providerName provider name to be used.
     * @return the equivalent key with explicit curve parameters
     * @throws IllegalArgumentException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     */
    public static PublicKey publicToExplicitParameters(PublicKey key, String providerName)
        throws IllegalArgumentException, NoSuchAlgorithmException, NoSuchProviderException
    {
        Provider provider = Security.getProvider(providerName);

        if (provider == null)
        {
            throw new NoSuchProviderException("cannot find provider: " + providerName);
        }

        return publicToExplicitParameters(key, provider);
    }

    /**
     * Convert a passed in public EC key to have explicit parameters. If the key
     * is already using explicit parameters it is returned.
     *
     * @param key key to be converted
     * @param provider provider to be used.
     * @return the equivalent key with explicit curve parameters
     * @throws IllegalArgumentException
     * @throws NoSuchAlgorithmException
     */
    public static PublicKey publicToExplicitParameters(PublicKey key, Provider provider)
        throws IllegalArgumentException, NoSuchAlgorithmException
    {
        try
        {
            SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(key.getEncoded()));

            if (info.getAlgorithmId().getObjectId().equals(CryptoProObjectIdentifiers.gostR3410_2001))
            {
                throw new IllegalArgumentException("cannot convert GOST key to explicit parameters.");
            }
            else
            {
                X962Parameters params = X962Parameters.getInstance(info.getAlgorithmId().getParameters());
                X9ECParameters curveParams;

                if (params.isNamedCurve())
                {
                    ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(params.getParameters());

                    curveParams = ECUtil.getNamedCurveByOid(oid);
                    // ignore seed value due to JDK bug
                    curveParams = new X9ECParameters(curveParams.getCurve(), curveParams.getG(), curveParams.getN(), curveParams.getH());
                }
                else if (params.isImplicitlyCA())
                {
                    curveParams = new X9ECParameters(BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getCurve(), BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getG(), BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getN(), BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getH());
                }
                else
                {
                    return key;   // already explicit
                }

                params = new X962Parameters(curveParams);

                info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params), info.getPublicKeyData().getBytes());

                KeyFactory keyFact = KeyFactory.getInstance(key.getAlgorithm(), provider.getName());

                return keyFact.generatePublic(new X509EncodedKeySpec(info.getEncoded()));
            }
        }
        catch (IllegalArgumentException e)
        {
            throw e;
        }
        catch (NoSuchAlgorithmException e)
        {
            throw e;
        }
        catch (Exception e)
        {               // shouldn't really happen...
            throw new UnexpectedException(e);
        }
    }

    /**
     * Convert a passed in private EC key to have explicit parameters. If the key
     * is already using explicit parameters it is returned.
     *
     * @param key key to be converted
     * @param providerName provider name to be used.
     * @return the equivalent key with explicit curve parameters
     * @throws IllegalArgumentException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     */
    public static PrivateKey privateToExplicitParameters(PrivateKey key, String providerName)
        throws IllegalArgumentException, NoSuchAlgorithmException, NoSuchProviderException
    {
        Provider provider = Security.getProvider(providerName);

        if (provider == null)
        {
            throw new NoSuchProviderException("cannot find provider: " + providerName);
        }

        return privateToExplicitParameters(key, provider);
    }

    /**
     * Convert a passed in private EC key to have explicit parameters. If the key
     * is already using explicit parameters it is returned.
     *
     * @param key key to be converted
     * @param provider provider to be used.
     * @return the equivalent key with explicit curve parameters
     * @throws IllegalArgumentException
     * @throws NoSuchAlgorithmException
     */
    public static PrivateKey privateToExplicitParameters(PrivateKey key, Provider provider)
        throws IllegalArgumentException, NoSuchAlgorithmException
    {
        try
        {
            PrivateKeyInfo info = PrivateKeyInfo.getInstance(ASN1Primitive.fromByteArray(key.getEncoded()));

            if (info.getAlgorithmId().getObjectId().equals(CryptoProObjectIdentifiers.gostR3410_2001))
            {
                throw new UnsupportedEncodingException("cannot convert GOST key to explicit parameters.");
            }
            else
            {
                X962Parameters params = X962Parameters.getInstance(info.getAlgorithmId().getParameters());
                X9ECParameters curveParams;

                if (params.isNamedCurve())
                {
                    ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(params.getParameters());

                    curveParams = ECUtil.getNamedCurveByOid(oid);
                    // ignore seed value due to JDK bug
                    curveParams = new X9ECParameters(curveParams.getCurve(), curveParams.getG(), curveParams.getN(), curveParams.getH());
                }
                else if (params.isImplicitlyCA())
                {
                    curveParams = new X9ECParameters(BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getCurve(), BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getG(), BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getN(), BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getH());
                }
                else
                {
                    return key;   // already explicit
                }

                params = new X962Parameters(curveParams);

                info = new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params), info.parsePrivateKey());

                KeyFactory keyFact = KeyFactory.getInstance(key.getAlgorithm(), provider.getName());

                return keyFact.generatePrivate(new PKCS8EncodedKeySpec(info.getEncoded()));
            }
        }
        catch (IllegalArgumentException e)
        {
            throw e;
        }
        catch (NoSuchAlgorithmException e)
        {
            throw e;
        }
        catch (Exception e)
        {          // shouldn't really happen
            throw new UnexpectedException(e);
        }
    }

    private static class UnexpectedException
        extends RuntimeException
    {
        private Throwable cause;

        UnexpectedException(Throwable cause)
        {
            super(cause.toString());

            this.cause = cause;
        }

        public Throwable getCause()
        {
            return cause;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.batik.svggen.font.table;

import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @version $Id: HeadTable.java 475477 2006-11-15 22:44:28Z cam $
 * @author David Schweinsberg
 */
public class HeadTable implements Table {

    private int versionNumber;
    private int fontRevision;
    private int checkSumAdjustment;
    private int magicNumber;
    private short flags;
    private short unitsPerEm;
    private long created;
    private long modified;
    private short xMin;
    private short yMin;
    private short xMax;
    private short yMax;
    private short macStyle;
    private short lowestRecPPEM;
    private short fontDirectionHint;
    private short indexToLocFormat;
    private short glyphDataFormat;

    protected HeadTable(DirectoryEntry de,RandomAccessFile raf) throws IOException {
        raf.seek(de.getOffset());
        versionNumber = raf.readInt();
        fontRevision = raf.readInt();
        checkSumAdjustment = raf.readInt();
        magicNumber = raf.readInt();
        flags = raf.readShort();
        unitsPerEm = raf.readShort();
        created = raf.readLong();
        modified = raf.readLong();
        xMin = raf.readShort();
        yMin = raf.readShort();
        xMax = raf.readShort();
        yMax = raf.readShort();
        macStyle = raf.readShort();
        lowestRecPPEM = raf.readShort();
        fontDirectionHint = raf.readShort();
        indexToLocFormat = raf.readShort();
        glyphDataFormat = raf.readShort();
    }

    public int getCheckSumAdjustment() {
        return checkSumAdjustment;
    }

    public long getCreated() {
        return created;
    }

    public short getFlags() {
        return flags;
    }

    public short getFontDirectionHint() {
        return fontDirectionHint;
    }

    public int getFontRevision(){
        return fontRevision;
    }

    public short getGlyphDataFormat() {
        return glyphDataFormat;
    }

    public short getIndexToLocFormat() {
        return indexToLocFormat;
    }

    public short getLowestRecPPEM() {
        return lowestRecPPEM;
    }

    public short getMacStyle() {
        return macStyle;
    }

    public long getModified() {
        return modified;
    }

    public int getType() {
        return head;
    }

    public short getUnitsPerEm() {
        return unitsPerEm;
    }

    public int getVersionNumber() {
        return versionNumber;
    }

    public short getXMax() {
        return xMax;
    }

    public short getXMin() {
        return xMin;
    }

    public short getYMax() {
        return yMax;
    }

    public short getYMin() {
        return yMin;
    }

    public String toString() {
        return new StringBuffer()
            .append("head\n\tversionNumber: ").append(versionNumber)
            .append("\n\tfontRevision: ").append(fontRevision)
            .append("\n\tcheckSumAdjustment: ").append(checkSumAdjustment)
            .append("\n\tmagicNumber: ").append(magicNumber)
            .append("\n\tflags: ").append(flags)
            .append("\n\tunitsPerEm: ").append(unitsPerEm)
            .append("\n\tcreated: ").append(created)
            .append("\n\tmodified: ").append(modified)
            .append("\n\txMin: ").append(xMin)
            .append(", yMin: ").append(yMin)
            .append("\n\txMax: ").append(xMax)
            .append(", yMax: ").append(yMax)
            .append("\n\tmacStyle: ").append(macStyle)
            .append("\n\tlowestRecPPEM: ").append(lowestRecPPEM)
            .append("\n\tfontDirectionHint: ").append(fontDirectionHint)
            .append("\n\tindexToLocFormat: ").append(indexToLocFormat)
            .append("\n\tglyphDataFormat: ").append(glyphDataFormat)
            .toString();
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using LanExchange.Ioc;
using LanExchange.SDK;

namespace LanExchange.Misc.Impl
{
    public class PluginManagerImpl : IPluginManager
    {
        private const string PLUGIN_MASK = "LanExchange.Plugin.*.dll";
        private const string IPLUGIN_INTERFACE = "LanExchange.SDK.IPlugin";
        private const string PLUGIN_TYPE_PREFIX = "Plugin";
        private readonly IList<IPlugin> m_Plugins;
        private readonly IDictionary<string, string> m_PluginsAuthors;

        public PluginManagerImpl()
        {
            m_Plugins = new List<IPlugin>();
            m_PluginsAuthors = new Dictionary<string, string>();
        }

        public void LoadPlugins()
        {
            var files = Directory.GetFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Lib"), PLUGIN_MASK, SearchOption.TopDirectoryOnly);
            foreach (var fileName in files)
                try
                {
                    LoadPlugin(fileName);
                }
                catch (Exception ex)
                {
                    Debug.Print(ex.Message);
                }
        }

        [Localizable(false)]
        private void LoadPlugin(string fileName)
        {
            var assembly = Assembly.LoadFile(fileName);
            var fileNameWithoutPath = Path.GetFileName(fileName);
            if (fileNameWithoutPath == null) return;
            var attributes = assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
            var author = attributes.Length == 0 ? "" : ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
            var name = Path.GetFileNameWithoutExtension(fileNameWithoutPath);
            var parts = name.Split('.');
            if (parts.Length < 3) return;
            name = name + "." + PLUGIN_TYPE_PREFIX + parts[parts.Length - 1];
            var type = assembly.GetType(name);//, false, true);
            if (type == null) return;
            var iface = type.GetInterface(IPLUGIN_INTERFACE);
            if (iface == null) return;
            IPlugin plugin = null;
            try
            {
                plugin = (IPlugin)Activator.CreateInstance(type);
            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message);
            }
            if (plugin == null) return;
            try
            {
                m_PluginsAuthors.Add(fileNameWithoutPath, author);
                m_Plugins.Add(plugin);
                plugin.Initialize(App.Resolve<IServiceProvider>());
            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message);
            }
        }

        public IList<IPlugin> Items
        {
            get { return m_Plugins; }
        }

        public IDictionary<string, string> PluginsAuthors
        {
            get { return m_PluginsAuthors; }
        }

    }
}


text:
"""Test client vfs."""

import io
import logging
import os
import shutil
import stat
from unittest import mock

from absl import app
from absl.testing import absltest
import psutil

# pylint: disable=unused-import,g-bad-import-order
from grr_response_client import client_plugins
# pylint: enable=unused-import,g-bad-import-order

from grr_response_client import vfs
from grr_response_client.vfs_handlers import files
from grr_response_core.lib import utils
from grr_response_core.lib.rdfvalues import client as rdf_client
from grr_response_core.lib.rdfvalues import paths as rdf_paths
from grr_response_core.lib.util import temp
from grr.test_lib import test_lib
from grr.test_lib import vfs_test_lib

# pylint: mode=test

class VFSTest(vfs_test_lib.VfsTestCase, test_lib.GRRBaseTest):
  """Test the client VFS switch."""

  def GetNumbers(self):
    """Generate a test string."""
    result = b""
    for i in range(1, 1001):
      result += "{}\n".format(i).encode("ascii")

    return result

  def TestFileHandling(self, fd):
    """Test the file like object behaviour."""
    original_string = self.GetNumbers()

    self.assertEqual(fd.size, len(original_string))

    fd.Seek(0)
    self.assertEqual(fd.Read(100), original_string[0:100])
    self.assertEqual(fd.Tell(), 100)

    fd.Seek(-10, 1)
    self.assertEqual(fd.Tell(), 90)
    self.assertEqual(fd.Read(10), original_string[90:100])

    fd.Seek(0, 2)
    self.assertEqual(fd.Tell(), len(original_string))
    self.assertEqual(fd.Read(10), b"")
    self.assertEqual(fd.Tell(), len(original_string))

    # Raise if we try to list the contents of a file object.
    self.assertRaises(IOError, lambda: list(fd.ListFiles()))

  def testRegularFile(self):
    """Test our ability to read regular files."""
    path = os.path.join(self.base_path, "morenumbers.txt")
    pathspec = rdf_paths.PathSpec(
        path=path, pathtype=rdf_paths.PathSpec.PathType.OS)
    fd = vfs.VFSOpen(pathspec)

    self.TestFileHandling(fd)

  def testOpenFilehandles(self):
    """Test that file handles are cached."""
    current_process = psutil.Process(os.getpid())
    num_open_files = len(current_process.open_files())

    path = os.path.join(self.base_path, "morenumbers.txt")

    fds = []
    for _ in range(100):
      fd = vfs.VFSOpen(
          rdf_paths.PathSpec(
              path=path, pathtype=rdf_paths.PathSpec.PathType.OS))
      self.assertEqual(fd.read(20), b"1\n2\n3\n4\n5\n6\n7\n8\n9\n10")
      fds.append(fd)

    # This should not create any new file handles.
    self.assertLess(len(current_process.open_files()) - num_open_files, 5)

  def testFileCasing(self):
    """Test our ability to read the correct casing from filesystem."""
    try:
      os.lstat(os.path.join(self.base_path, "nUmBeRs.txt"))
      os.lstat(os.path.join(self.base_path, "nuMbErs.txt"))
      # If we reached this point we are on a case insensitive file system
      # and the tests below do not make any sense.
      logging.warning("Case insensitive file system detected. Skipping test.")
      return
    except (IOError, OSError):
      pass

    # Create 2 files with names that differ only in casing.
    with utils.TempDirectory() as temp_dir:
      path1 = os.path.join(temp_dir, "numbers.txt")
      shutil.copy(os.path.join(self.base_path, "numbers.txt"), path1)

      path2 = os.path.join(temp_dir, "numbers.TXT")
      shutil.copy(os.path.join(self.base_path, "numbers.txt.ver2"), path2)

      fd = vfs.VFSOpen(
          rdf_paths.PathSpec(
              path=path1, pathtype=rdf_paths.PathSpec.PathType.OS))
      self.assertEqual(fd.pathspec.Basename(), "numbers.txt")

      fd = vfs.VFSOpen(
          rdf_paths.PathSpec(
              path=path2, pathtype=rdf_paths.PathSpec.PathType.OS))
      self.assertEqual(fd.pathspec.Basename(), "numbers.TXT")

      path = os.path.join(self.base_path, "Numbers.txt")
      fd = vfs.VFSOpen(
          rdf_paths.PathSpec(
              path=path, pathtype=rdf_paths.PathSpec.PathType.OS))
      read_path = fd.pathspec.Basename()

      # The exact file now is non deterministic but should be either of the two:
      if read_path != "numbers.txt" and read_path != "numbers.TXT":
        raise RuntimeError("read path is %s" % read_path)

      # Ensure that the produced pathspec specified no case folding:
      s = fd.Stat()
      self.assertEqual(s.pathspec.path_options,
                       rdf_paths.PathSpec.Options.CASE_LITERAL)

      # Case folding will only occur when requested - this should raise because
      # we have the CASE_LITERAL option:
      pathspec = rdf_paths.PathSpec(
          path=path,
          pathtype=rdf_paths.PathSpec.PathType.OS,
          path_options=rdf_paths.PathSpec.Options.CASE_LITERAL)
      self.assertRaises(IOError, vfs.VFSOpen, pathspec)

  def testTSKFile(self):
    """Test our ability to read from image files."""
    path = os.path.join(self.base_path, "test_img.dd")
    path2 = "Test Directory/numbers.txt"

    p2 = rdf_paths.PathSpec(
        path=path2, pathtype=rdf_paths.PathSpec.PathType.TSK)
    p1 = rdf_paths.PathSpec(path=path, pathtype=rdf_paths.PathSpec.PathType.OS)
    p1.Append(p2)
    fd = vfs.VFSOpen(p1)
    self.TestFileHandling(fd)

  def testTSKBTime(self):
    pathspec = rdf_paths.PathSpec(
        path=os.path.join(self.base_path, "ntfs_img.dd"),
        pathtype=rdf_paths.PathSpec.PathType.OS,
        offset=63 * 512,
        nested_path=rdf_paths.PathSpec(
            path="/Test Directory/notes.txt",
            pathtype=rdf_paths.PathSpec.PathType.TSK))

    fd = vfs.VFSOpen(pathspec)
    st = fd.Stat()
    self.assertEqual(str(st.st_btime), "2011-12-17 00:14:37")

  def testTSKFileInode(self):
    """Test opening a file through an indirect pathspec."""
    pathspec = rdf_paths.PathSpec(
        path=os.path.join(self.base_path, "test_img.dd"),
        pathtype=rdf_paths.PathSpec.PathType.OS)
    pathspec.Append(
        pathtype=rdf_paths.PathSpec.PathType.TSK,
        inode=12,
        path="/Test Directory")
    pathspec.Append(
        pathtype=rdf_paths.PathSpec.PathType.TSK, path="numbers.txt")

    fd = vfs.VFSOpen(pathspec)

    # Check that the new pathspec is correctly reduced to two components.
    self.assertEqual(
        fd.pathspec.first.path,
        utils.NormalizePath(os.path.join(self.base_path, "test_img.dd")))
    self.assertEqual(fd.pathspec[1].path, "/Test Directory/numbers.txt")

    # And the correct inode is placed in the final branch.
    self.assertEqual(fd.Stat().pathspec.nested_path.inode, 15)
    self.TestFileHandling(fd)

  def testTSKFileCasing(self):
    """Test our ability to read the correct casing from image."""
    path = os.path.join(self.base_path, "test_img.dd")
    path2 = os.path.join("test directory", "NuMbErS.TxT")

    ps2 = rdf_paths.PathSpec(
        path=path2, pathtype=rdf_paths.PathSpec.PathType.TSK)

    ps = rdf_paths.PathSpec(path=path, pathtype=rdf_paths.PathSpec.PathType.OS)
    ps.Append(ps2)
    fd = vfs.VFSOpen(ps)

    # This fixes Windows paths.
    path = path.replace("\\", "/")
    # The pathspec should have 2 components.

    self.assertEqual(fd.pathspec.first.path, utils.NormalizePath(path))
    self.assertEqual(fd.pathspec.first.pathtype, rdf_paths.PathSpec.PathType.OS)

    nested = fd.pathspec.last
    self.assertEqual(nested.path, u"/Test Directory/numbers.txt")
    self.assertEqual(nested.pathtype, rdf_paths.PathSpec.PathType.TSK)

  def testTSKInodeHandling(self):
    """Test that we can open files by inode."""
    path = os.path.join(self.base_path, "ntfs_img.dd")
    ps2 = rdf_paths.PathSpec(
        inode=65,
        ntfs_type=128,
        path="/this/will/be/ignored",
        pathtype=rdf_paths.PathSpec.PathType.TSK)

    ps = rdf_paths.PathSpec(
        path=path, pathtype=rdf_paths.PathSpec.PathType.OS, offset=63 * 512)
    ps.Append(ps2)
    fd = vfs.VFSOpen(ps)

    self.assertEqual(fd.Read(100), b"Hello world\n")

    ps2 = rdf_paths.PathSpec(
        inode=65,
        ntfs_type=128,
        ntfs_id=4,
        pathtype=rdf_paths.PathSpec.PathType.TSK)
    ps = rdf_paths.PathSpec(
        path=path, pathtype=rdf_paths.PathSpec.PathType.OS, offset=63 * 512)
    ps.Append(ps2)
    fd = vfs.VFSOpen(ps)

    self.assertEqual(fd.read(100), b"I am a real ADS\n")

    # Make sure the size is correct:
    self.assertEqual(fd.Stat().st_size, len(b"I am a real ADS\n"))

  def testTSKNTFSHandling(self):
    """Test that TSK can correctly encode NTFS features."""
    path = os.path.join(self.base_path, "ntfs_img.dd")
    path2 = "test directory"

    ps2 = rdf_paths.PathSpec(
        path=path2, pathtype=rdf_paths.PathSpec.PathType.TSK)

    ps = rdf_paths.PathSpec(
        path=path, pathtype=rdf_paths.PathSpec.PathType.OS, offset=63 * 512)
    ps.Append(ps2)
    fd = vfs.VFSOpen(ps)

    listing = []
    pathspecs = []

    for f in fd.ListFiles():
      # Make sure the CASE_LITERAL option is set for all drivers so we can just
      # resend this proto back.
      self.assertEqual(f.pathspec.path_options,
                       rdf_paths.PathSpec.Options.CASE_LITERAL)
      pathspec = f.pathspec.nested_path
      self.assertEqual(pathspec.path_options,
                       rdf_paths.PathSpec.Options.CASE_LITERAL)
      pathspecs.append(f.pathspec)
      listing.append((pathspec.inode, pathspec.ntfs_type, pathspec.ntfs_id))

    # The tsk_fs_attr_type enum:
    tsk_fs_attr_type = rdf_paths.PathSpec.tsk_fs_attr_type

    ref = [(65, tsk_fs_attr_type.TSK_FS_ATTR_TYPE_DEFAULT, 0),
           (65, tsk_fs_attr_type.TSK_FS_ATTR_TYPE_NTFS_DATA, 4),
           (66, tsk_fs_attr_type.TSK_FS_ATTR_TYPE_DEFAULT, 0),
           (67, tsk_fs_attr_type.TSK_FS_ATTR_TYPE_DEFAULT, 0)]

    # Make sure that the ADS is recovered.
    self.assertEqual(listing, ref)

    # Try to read the main file
    self.assertEqual(pathspecs[0].nested_path.path, "/Test Directory/notes.txt")
    fd = vfs.VFSOpen(pathspecs[0])
    self.assertEqual(fd.read(1000), b"Hello world\n")

    s = fd.Stat()
    self.assertEqual(s.pathspec.nested_path.inode, 65)
    self.assertEqual(s.pathspec.nested_path.ntfs_type, 1)
    self.assertEqual(s.pathspec.nested_path.ntfs_id, 0)

    # Check that the name of the ads is consistent.
    self.assertEqual(pathspecs[1].nested_path.path, "/Test Directory/notes.txt")
    self.assertEqual(pathspecs[1].nested_path.stream_name, "ads")

    # Check that the ADS name is encoded correctly in the AFF4 URN for this
    # file.
    aff4_urn = pathspecs[1].AFF4Path(rdf_client.ClientURN("C.1234567812345678"))
    self.assertEqual(aff4_urn.Basename(), "notes.txt:ads")

    fd = vfs.VFSOpen(pathspecs[1])
    self.assertEqual(fd.read(1000), b"I am a real ADS\n")

    # Test that the stat contains the inode:
    s = fd.Stat()
    self.assertEqual(s.pathspec.nested_path.inode, 65)
    self.assertEqual(s.pathspec.nested_path.ntfs_type, 128)
    self.assertEqual(s.pathspec.nested_path.ntfs_id, 4)

  def testNTFSProgressCallback(self):

    self.progress_counter = 0

    def Progress():
      self.progress_counter += 1

    path = os.path.join(self.base_path, "ntfs_img.dd")
    path2 = "test directory"

    ps2 = rdf_paths.PathSpec(
        path=path2, pathtype=rdf_paths.PathSpec.PathType.TSK)

    ps = rdf_paths.PathSpec(
        path=path, pathtype=rdf_paths.PathSpec.PathType.OS, offset=63 * 512)
    ps.Append(ps2)

    vfs.VFSOpen(ps, progress_callback=Progress)

    self.assertGreater(self.progress_counter, 0)

  def testUnicodeFile(self):
    """Test ability to read unicode files from images."""
    path = os.path.join(self.base_path, "test_img.dd")
    path2 = os.path.join(u"איןד ןד ש אקדא", u"איןד.txt")

    ps2 = rdf_paths.PathSpec(
        path=path2, pathtype=rdf_paths.PathSpec.PathType.TSK)

    ps = rdf_paths.PathSpec(path=path, pathtype=rdf_paths.PathSpec.PathType.OS)
    ps.Append(ps2)
    fd = vfs.VFSOpen(ps)
    self.TestFileHandling(fd)

  def testListDirectory(self):
    """Test our ability to list a directory."""
    directory = vfs.VFSOpen(
        rdf_paths.PathSpec(
            path=self.base_path, pathtype=rdf_paths.PathSpec.PathType.OS))

    self.CheckDirectoryListing(directory, "morenumbers.txt")

  def testTSKListDirectory(self):
    """Test directory listing in sleuthkit."""
    path = os.path.join(self.base_path, u"test_img.dd")
    ps2 = rdf_paths.PathSpec(
        path=u"入乡随俗 海外春节别样过法", pathtype=rdf_paths.PathSpec.PathType.TSK)
    ps = rdf_paths.PathSpec(path=path, pathtype=rdf_paths.PathSpec.PathType.OS)
    ps.Append(ps2)
    directory = vfs.VFSOpen(ps)
    self.CheckDirectoryListing(directory, u"入乡随俗.txt")

  def testRecursiveImages(self):
    """Test directory listing in sleuthkit."""
    p3 = rdf_paths.PathSpec(
        path="/home/a.txt", pathtype=rdf_paths.PathSpec.PathType.TSK)
    p2 = rdf_paths.PathSpec(
        path="/home/image2.img", pathtype=rdf_paths.PathSpec.PathType.TSK)
    p1 = rdf_paths.PathSpec(
        path=os.path.join(self.base_path, "test_img.dd"),
        pathtype=rdf_paths.PathSpec.PathType.OS)
    p2.Append(p3)
    p1.Append(p2)
    f = vfs.VFSOpen(p1)

    self.assertEqual(f.read(3), b"yay")

  def testGuessPathSpec(self):
    """Test that we can guess a pathspec from a path."""
    path = os.path.join(self.base_path, "test_img.dd", "home/image2.img",
                        "home/a.txt")

    pathspec = rdf_paths.PathSpec(
        path=path, pathtype=rdf_paths.PathSpec.PathType.OS)

    fd = vfs.VFSOpen(pathspec)
    self.assertEqual(fd.read(3), b"yay")

  def testFileNotFound(self):
    """Test that we raise an IOError for file not found."""
    path = os.path.join(self.base_path, "test_img.dd", "home/image2.img",
                        "home/nosuchfile.txt")

    pathspec = rdf_paths.PathSpec(
        path=path, pathtype=rdf_paths.PathSpec.PathType.OS)
    self.assertRaises(IOError, vfs.VFSOpen, pathspec)

  def testGuessPathSpecPartial(self):
    """Test that we can guess a pathspec from a partial pathspec."""
    path = os.path.join(self.base_path, "test_img.dd")
    pathspec = rdf_paths.PathSpec(
        path=path, pathtype=rdf_paths.PathSpec.PathType.OS)
    pathspec.nested_path.path = "/home/image2.img/home/a.txt"
    pathspec.nested_path.pathtype = rdf_paths.PathSpec.PathType.TSK

    fd = vfs.VFSOpen(pathspec)
    self.assertEqual(fd.read(3), b"yay")

    # Open as a directory
    pathspec.nested_path.path = "/home/image2.img/home/"

    fd = vfs.VFSOpen(pathspec)

    names = []
    for s in fd.ListFiles():
      # Make sure that the stat pathspec is correct - it should be 3 levels
      # deep.
      self.assertEqual(s.pathspec.nested_path.path, "/home/image2.img")
      names.append(s.pathspec.nested_path.nested_path.path)

    self.assertIn("home/a.txt", names)

  def testRegistryListing(self):
    """Test our ability to list registry keys."""
    reg = rdf_paths.PathSpec.PathType.REGISTRY
    with vfs_test_lib.VFSOverrider(reg, vfs_test_lib.FakeRegistryVFSHandler):
      pathspec = rdf_paths.PathSpec(
          pathtype=rdf_paths.PathSpec.PathType.REGISTRY,
          path=("/HKEY_USERS/S-1-5-20/Software/Microsoft"
                "/Windows/CurrentVersion/Run"))

      expected_names = {"MctAdmin": stat.S_IFDIR, "Sidebar": stat.S_IFDIR}
      expected_data = [
          u"%ProgramFiles%\\Windows Sidebar\\Sidebar.exe /autoRun",
          u"%TEMP%\\Sidebar.exe"
      ]

      for f in vfs.VFSOpen(pathspec).ListFiles():
        base, name = os.path.split(f.pathspec.CollapsePath())
        self.assertEqual(base, pathspec.CollapsePath())
        self.assertIn(name, expected_names)
        self.assertIn(f.registry_data.GetValue(), expected_data)

  def CheckDirectoryListing(self, directory, test_file):
    """Check that the directory listing is sensible."""

    found = False
    for f in directory.ListFiles():
      # TSK makes virtual files with $ if front of them
      path = f.pathspec.Basename()
      if path.startswith("$"):
        continue

      # Check the time is reasonable
      self.assertGreater(f.st_mtime, 10000000)
      self.assertGreater(f.st_atime, 10000000)
      self.assertGreater(f.st_ctime, 10000000)

      if path == test_file:
        found = True
        # Make sure it's a regular file with the right size
        self.assertTrue(stat.S_ISREG(int(f.st_mode)))
        self.assertEqual(f.st_size, 3893)

    self.assertEqual(found, True)

    # Raise if we try to read the contents of a directory object.
    self.assertRaises(IOError, directory.Read, 5)

  def testVFSVirtualRoot(self):

    # Let's open a file in the virtual root.
    os_root = "os:%s" % self.base_path
    with test_lib.ConfigOverrider({"Client.vfs_virtualroots": [os_root]}):
      # We need to reset the vfs._VFS_VIRTUALROOTS too.
      vfs.Init()

      fd = vfs.VFSOpen(
          rdf_paths.PathSpec(
              path="/morenumbers.txt", pathtype=rdf_paths.PathSpec.PathType.OS))
      data = fd.read(10)
      self.assertEqual(data, b"1\n2\n3\n4\n5\n")

    # This should also work with TSK.
    tsk_root = "tsk:%s" % os.path.join(self.base_path, "test_img.dd")
    with test_lib.ConfigOverrider({"Client.vfs_virtualroots": [tsk_root]}):
      vfs.Init()

      image_file_ps = rdf_paths.PathSpec(
          path=u"איןד ןד ש אקדא/איןד.txt",
          pathtype=rdf_paths.PathSpec.PathType.TSK)

      fd = vfs.VFSOpen(image_file_ps)

      data = fd.read(10)
      self.assertEqual(data, b"1\n2\n3\n4\n5\n")

      # This should not influence vfs handlers other than OS and TSK.
      reg_type = rdf_paths.PathSpec.PathType.REGISTRY
      os_handler = vfs.VFS_HANDLERS[rdf_paths.PathSpec.PathType.OS]
      with vfs_test_lib.VFSOverrider(reg_type, os_handler):
        with self.assertRaises(IOError):
          image_file_ps.pathtype = reg_type
          vfs.VFSOpen(image_file_ps)

  def testFileSizeOverride(self):

    # We assume /dev/null exists and has a 0 size.
    fname = "/dev/null"
    try:
      st = os.stat(fname)
    except OSError:
      self.skipTest("%s not accessible." % fname)
    if st.st_size != 0:
      self.skipTest("%s doesn't have 0 size." % fname)

    pathspec = rdf_paths.PathSpec(
        path=fname, pathtype="OS", file_size_override=100000000)
    fd = vfs.VFSOpen(pathspec)
    self.assertEqual(fd.size, 100000000)

  def testNTFSFile(self):
    pathspec = rdf_paths.PathSpec(
        path=os.path.join(self.base_path, "ntfs.img"),
        pathtype=rdf_paths.PathSpec.PathType.OS,
        path_options=rdf_paths.PathSpec.Options.CASE_LITERAL,
        nested_path=rdf_paths.PathSpec(
            path="numbers.txt", pathtype=rdf_paths.PathSpec.PathType.NTFS))
    fd = vfs.VFSOpen(pathspec)
    self.TestFileHandling(fd)

class VFSMultiOpenTest(absltest.TestCase):

  _VFS_OVERRIDER = vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                             files.File)

  def setUp(self):
    self._VFS_OVERRIDER.Start()
    self.addCleanup(self._VFS_OVERRIDER.Stop)

  def testMultipleFiles(self):
    with temp.AutoTempDirPath(remove_non_empty=True) as tempdir:
      foo_path = os.path.join(tempdir, "foo")
      bar_path = os.path.join(tempdir, "bar")
      baz_path = os.path.join(tempdir, "baz")

      self._Touch(foo_path, b"FOO")
      self._Touch(bar_path, b"BAR")
      self._Touch(baz_path, b"BAZ")

      foo_pathspec = rdf_paths.PathSpec(
          pathtype=rdf_paths.PathSpec.PathType.OS, path=foo_path)
      bar_pathspec = rdf_paths.PathSpec(
          pathtype=rdf_paths.PathSpec.PathType.OS, path=bar_path)
      baz_pathspec = rdf_paths.PathSpec(
          pathtype=rdf_paths.PathSpec.PathType.OS, path=baz_path)

      pathspecs = [foo_pathspec, bar_pathspec, baz_pathspec]
      with vfs.VFSMultiOpen(pathspecs) as filedescs:
        self.assertLen(filedescs, 3)
        self.assertEqual(filedescs[0].Read(), b"FOO")
        self.assertEqual(filedescs[1].Read(), b"BAR")
        self.assertEqual(filedescs[2].Read(), b"BAZ")
        files.FlushHandleCache()

  def testProgressCallback(self):
    with temp.AutoTempFilePath() as temppath:
      self._Touch(temppath, b"QUUX")

      pathspec = rdf_paths.PathSpec(
          pathtype=rdf_paths.PathSpec.PathType.OS, path=temppath)

      func = mock.MagicMock()

      with vfs.VFSMultiOpen([pathspec], progress_callback=func) as filedescs:
        self.assertLen(filedescs, 1)
        self.assertEqual(filedescs[0].Read(), b"QUUX")

      self.assertTrue(func.called)
      files.FlushHandleCache()

  def _Touch(self, filepath, content=b""):
    with io.open(filepath, mode="wb") as filedesc:
      filedesc.write(content)

def main(argv):
  test_lib.main(argv)

if __name__ == "__main__":
  app.run(main)


text:
using System.Globalization;
using System.Text;
using Dot42;
using Dot42.Internal;

namespace System
{
    // Summary:
    //     Represents a time interval.
    [Serializable]
    public struct TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable
    {
        public const long TicksPerDay = 864000000000;
        public const long TicksPerHour = 36000000000;
        public const long TicksPerMillisecond = 10000L;
        public const long TicksPerMinute = 600000000L;
        public const long TicksPerSecond = 10000000L;

        public static readonly TimeSpan MaxValue = new TimeSpan(long.MaxValue);
        public static readonly TimeSpan MinValue = new TimeSpan(long.MinValue);
        public static readonly TimeSpan Zero = new TimeSpan(0L);

        private readonly long ticks;

        /// <summary>
        /// Create a new TimeSpan with a number of ticks specified
        /// </summary>
        /// <param name="ticks">number of ticks (100-nanosecond units = 10.000 ticks/ms)</param>
        public TimeSpan(long ticks)
        {
            this.ticks = ticks;
        }

        public TimeSpan(int hours, int minutes, int seconds)
        {
            this.ticks = CalculateTicks(0, hours, minutes, seconds, 0);
        }

        public TimeSpan(int days, int hours, int minutes, int seconds)
        {
            this.ticks = CalculateTicks(days, hours, minutes, seconds, 0);
        }

        public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds)
        {
            this.ticks = CalculateTicks(days, hours, minutes, seconds, milliseconds);
        }

        internal static long CalculateTicks(int days, int hours, int minutes, int seconds, int milliseconds)
        {
            // there's no overflow checks for hours, minutes, ...
            // so big hours/minutes values can overflow at some point and change expected values
            int hrssec = (hours * 3600); // break point at (Int32.MaxValue - 596523)
            int minsec = (minutes * 60);
            long t = ((long)(hrssec + minsec + seconds) * 1000L + (long)milliseconds);
            t *= 10000;

            bool overflow = false;
            // days is problematic because it can overflow but that overflow can be
            // "legal" (i.e. temporary) (e.g. if other parameters are negative) or
            // illegal (e.g. sign change).
            if (days > 0)
            {
                long td = TicksPerDay * days;
                if (t < 0)
                {
                    long ticks = t;
                    t += td;
                    // positive days -> total ticks should be lower
                    overflow = (ticks > t);
                }
                else
                {
                    t += td;
                    // positive + positive != negative result
                    overflow = (t < 0);
                }
            }
            else if (days < 0)
            {
                long td = TicksPerDay * days;
                if (t <= 0)
                {
                    t += td;
                    // negative + negative != positive result
                    overflow = (t > 0);
                }
                else
                {
                    long ticks = t;
                    t += td;
                    // negative days -> total ticks should be lower
                    overflow = (t > ticks);
                }
            }

            if (overflow)
            {
               throw new ArgumentOutOfRangeException("The TimeSpan is too big or too small.");
            }

            return t;
        }

        // Summary:
        //     Returns a System.TimeSpan whose value is the negated value of the specified
        //     instance.
        //
        // Parameters:
        //   t:
        //     The time interval to be negated.
        //
        // Returns:
        //     An object that has the same numeric value as this instance, but the opposite
        //     sign.
        //
        // Exceptions:
        //   System.OverflowException:
        //     The negated value of this instance cannot be represented by a System.TimeSpan;
        //     that is, the value of this instance is System.TimeSpan.MinValue.
        public static TimeSpan operator -(TimeSpan t)
        {
            return t.Negate();
        }

        //
        // Summary:
        //     Subtracts a specified System.TimeSpan from another specified System.TimeSpan.
        //
        // Parameters:
        //   t1:
        //     The minuend.
        //
        //   t2:
        //     The subtrahend.
        //
        // Returns:
        //     An object whose value is the result of the value of t1 minus the value of
        //     t2.
        //
        // Exceptions:
        //   System.OverflowException:
        //     The return value is less than System.TimeSpan.MinValue or greater than System.TimeSpan.MaxValue.
        public static TimeSpan operator -(TimeSpan t1, TimeSpan t2)
        {
            return t1.Subtract(t2);
        }

        //
        // Summary:
        //     Indicates whether two System.TimeSpan instances are not equal.
        //
        // Parameters:
        //   t1:
        //     The first time interval to compare.
        //
        //   t2:
        //     The second time interval to compare.
        //
        // Returns:
        //     true if the values of t1 and t2 are not equal; otherwise, false.
        public static bool operator !=(TimeSpan t1, TimeSpan t2)
        {
            return t1.ticks != t2.ticks;
        }
        //
        // Summary:
        //     Returns the specified instance of System.TimeSpan.
        //
        // Parameters:
        //   t:
        //     The time interval to return.
        //
        // Returns:
        //     The time interval specified by t.
        public static TimeSpan operator +(TimeSpan t)
        {
            return t;
        }
        //
        // Summary:
        //     Adds two specified System.TimeSpan instances.
        //
        // Parameters:
        //   t1:
        //     The first time interval to add.
        //
        //   t2:
        //     The second time interval to add.
        //
        // Returns:
        //     An object whose value is the sum of the values of t1 and t2.
        //
        // Exceptions:
        //   System.OverflowException:
        //     The resulting System.TimeSpan is less than System.TimeSpan.MinValue or greater
        //     than System.TimeSpan.MaxValue.
        public static TimeSpan operator +(TimeSpan t1, TimeSpan t2)
        {
            return t1.Add(t2);
        }
        //
        // Summary:
        //     Indicates whether a specified System.TimeSpan is less than another specified
        //     System.TimeSpan.
        //
        // Parameters:
        //   t1:
        //     The first time interval to compare.
        //
        //   t2:
        //     The second time interval to compare.
        //
        // Returns:
        //     true if the value of t1 is less than the value of t2; otherwise, false.
        public static bool operator <(TimeSpan t1, TimeSpan t2)
        {
            return t1.ticks < t2.ticks;
        }
        //
        // Summary:
        //     Indicates whether a specified System.TimeSpan is less than or equal to another
        //     specified System.TimeSpan.
        //
        // Parameters:
        //   t1:
        //     The first time interval to compare.
        //
        //   t2:
        //     The second time interval to compare.
        //
        // Returns:
        //     true if the value of t1 is less than or equal to the value of t2; otherwise,
        //     false.
        public static bool operator <=(TimeSpan t1, TimeSpan t2)
        {
            return t1.ticks <= t2.ticks;
        }
        //
        // Summary:
        //     Indicates whether two System.TimeSpan instances are equal.
        //
        // Parameters:
        //   t1:
        //     The first time interval to compare.
        //
        //   t2:
        //     The second time interval to compare.
        //
        // Returns:
        //     true if the values of t1 and t2 are equal; otherwise, false.
        public static bool operator ==(TimeSpan t1, TimeSpan t2)
        {
            return t1.ticks == t2.ticks;
        }
        //
        // Summary:
        //     Indicates whether a specified System.TimeSpan is greater than another specified
        //     System.TimeSpan.
        //
        // Parameters:
        //   t1:
        //     The first time interval to compare.
        //
        //   t2:
        //     The second time interval to compare.
        //
        // Returns:
        //     true if the value of t1 is greater than the value of t2; otherwise, false.
        public static bool operator >(TimeSpan t1, TimeSpan t2)
        {
            return t1.ticks > t2.ticks;
        }
        //
        // Summary:
        //     Indicates whether a specified System.TimeSpan is greater than or equal to
        //     another specified System.TimeSpan.
        //
        // Parameters:
        //   t1:
        //     The first time interval to compare.
        //
        //   t2:
        //     The second time interval to compare.
        //
        // Returns:
        //     true if the value of t1 is greater than or equal to the value of t2; otherwise,
        //     false.
        public static bool operator >=(TimeSpan t1, TimeSpan t2)
        {
            return t1.ticks >= t2.ticks;
        }

        // Summary:
        //     Gets the days component of the time interval represented by the current System.TimeSpan
        //     structure.
        //
        // Returns:
        //     The day component of this instance. The return value can be positive or negative.
        public int Days { get { return (int)(ticks / TicksPerDay); } }

        [Inline, DexNative]
        private static int GetDays(long ticks) { return (int)(ticks / TicksPerDay); }
        //
        // Summary:
        //     Gets the hours component of the time interval represented by the current
        //     System.TimeSpan structure.
        //
        // Returns:
        //     The hour component of the current System.TimeSpan structure. The return value
        //     ranges from -23 through 23.
        public int Hours { get { return (int)(ticks % TicksPerDay / TicksPerHour); } }

        [Inline,DexNative]
        private static int GetHours(long ticks) { return (int)(ticks % TicksPerDay / TicksPerHour); }
        //
        // Summary:
        //     Gets the milliseconds component of the time interval represented by the current
        //     System.TimeSpan structure.
        //
        // Returns:
        //     The millisecond component of the current System.TimeSpan structure. The return
        //     value ranges from -999 through 999.
        public int Milliseconds { get { return (int)(ticks % TicksPerSecond / TicksPerMillisecond); } }

        //
        // Summary:
        //     Gets the minutes component of the time interval represented by the current
        //     System.TimeSpan structure.
        //
        // Returns:
        //     The minute component of the current System.TimeSpan structure. The return
        //     value ranges from -59 through 59.
        public int Minutes { get { return (int)(ticks % TicksPerHour / TicksPerMinute); } }

        [Inline, DexNative]
        public static int GetMinutes(long ticks) { return (int)(ticks % TicksPerHour / TicksPerMinute); }
        //
        // Summary:
        //     Gets the seconds component of the time interval represented by the current
        //     System.TimeSpan structure.
        //
        // Returns:
        //     The second component of the current System.TimeSpan structure. The return
        //     value ranges from -59 through 59.
        public int Seconds { get { return (int)(ticks % TicksPerMinute / TicksPerSecond); } }

        [Inline, DexNative]
        public static int GetSeconds(long ticks) { return (int)(ticks % TicksPerMinute / TicksPerSecond); }
        //
        // Summary:
        //     Gets the number of ticks that represent the value of the current System.TimeSpan
        //     structure.
        //
        // Returns:
        //     The number of ticks contained in this instance.
        public long Ticks { get { return ticks; } }
        //
        // Summary:
        //     Gets the value of the current System.TimeSpan structure expressed in whole
        //     and fractional days.
        //
        // Returns:
        //     The total number of days represented by this instance.
        public double TotalDays { get { return (double)ticks / TicksPerDay; } }
        //
        // Summary:
        //     Gets the value of the current System.TimeSpan structure expressed in whole
        //     and fractional hours.
        //
        // Returns:
        //     The total number of hours represented by this instance.
        public double TotalHours { get { return (double)ticks / TicksPerHour; } }
        //
        // Summary:
        //     Gets the value of the current System.TimeSpan structure expressed in whole
        //     and fractional milliseconds.
        //
        // Returns:
        //     The total number of milliseconds represented by this instance.
        public double TotalMilliseconds { get { return (double)ticks / TicksPerMillisecond; } }
        //
        // Summary:
        //     Gets the value of the current System.TimeSpan structure expressed in whole
        //     and fractional minutes.
        //
        // Returns:
        //     The total number of minutes represented by this instance.
        public double TotalMinutes { get { return (double)ticks / TicksPerMinute; } }
        //
        // Summary:
        //     Gets the value of the current System.TimeSpan structure expressed in whole
        //     and fractional seconds.
        //
        // Returns:
        //     The total number of seconds represented by this instance.
        public double TotalSeconds { get { return (double)ticks / TicksPerSecond; } }

        // Summary:
        //     Returns a new System.TimeSpan object whose value is the sum of the specified
        //     System.TimeSpan object and this instance.
        //
        // Parameters:
        //   ts:
        //     The time interval to add.
        //
        // Returns:
        //     A new object that represents the value of this instance plus the value of
        //     ts.
        //
        // Exceptions:
        //   System.OverflowException:
        //     The resulting System.TimeSpan is less than System.TimeSpan.MinValue or greater
        //     than System.TimeSpan.MaxValue.
        public TimeSpan Add(TimeSpan ts)
        {
            return new TimeSpan(ticks + ts.Ticks);
        }
        //
        // Summary:
        //     Compares two System.TimeSpan values and returns an integer that indicates
        //     whether the first value is shorter than, equal to, or longer than the second
        //     value.
        //
        // Parameters:
        //   t1:
        //     The first time interval to compare.
        //
        //   t2:
        //     The second time interval to compare.
        //
        // Returns:
        //     One of the following values.Value Description -1 t1 is shorter than t2. 0
        //     t1 is equal to t2. 1 t1 is longer than t2.
        public static int Compare(TimeSpan t1, TimeSpan t2)
        {
            if (t1.Ticks < t2.Ticks)
                return -1;
            if (t1.Ticks > t2.Ticks)
                return 1;
            return 0;
        }
        //
        // Summary:
        //     Compares this instance to a specified object and returns an integer that
        //     indicates whether this instance is shorter than, equal to, or longer than
        //     the specified object.
        //
        // Parameters:
        //   value:
        //     An object to compare, or null.
        //
        // Returns:
        //     One of the following values.Value Description -1 This instance is shorter
        //     than value. 0 This instance is equal to value. 1 This instance is longer
        //     than value.-or- value is null.
        //
        // Exceptions:
        //   System.ArgumentException:
        //     value is not a System.TimeSpan.
        public int CompareTo(object value)
        {
            if (value == null)
                return 1;

            if (!(value is TimeSpan))
            {
                throw new ArgumentException("Argument has to be a TimeSpan.", "value");
            }

            return Compare(this, (TimeSpan)value);
        }
        //
        // Summary:
        //     Compares this instance to a specified System.TimeSpan object and returns
        //     an integer that indicates whether this instance is shorter than, equal to,
        //     or longer than the System.TimeSpan object.
        //
        // Parameters:
        //   value:
        //     An object to compare to this instance.
        //
        // Returns:
        //     A signed number indicating the relative values of this instance and value.Value
        //     Description A negative integer This instance is shorter than value. Zero
        //     This instance is equal to value. A positive integer This instance is longer
        //     than value.
        public int CompareTo(TimeSpan value)
        {
            return Compare(this, value);
        }

        //
        // Summary:
        //     Returns a new System.TimeSpan object whose value is the absolute value of
        //     the current System.TimeSpan object.
        //
        // Returns:
        //     A new object whose value is the absolute value of the current System.TimeSpan
        //     object.
        //
        // Exceptions:
        //   System.OverflowException:
        //     The value of this instance is System.TimeSpan.MinValue.
        public TimeSpan Duration()
        {
            return new TimeSpan(Math.Abs(ticks));
        }
        //
        // Summary:
        //     Returns a value indicating whether this instance is equal to a specified
        //     object.
        //
        // Parameters:
        //   value:
        //     An object to compare with this instance.
        //
        // Returns:
        //     true if value is a System.TimeSpan object that represents the same time interval
        //     as the current System.TimeSpan structure; otherwise, false.
        public override bool Equals(object value)
        {
            if (!(value is TimeSpan))
                return false;

            return ticks == ((TimeSpan)value).ticks;
        }
        //
        // Summary:
        //     Returns a value indicating whether this instance is equal to a specified
        //     System.TimeSpan object.
        //
        // Parameters:
        //   obj:
        //     An object to compare with this instance.
        //
        // Returns:
        //     true if obj represents the same time interval as this instance; otherwise,
        //     false.
        public bool Equals(TimeSpan obj)
        {
            return obj.ticks == ticks;
        }
        //
        // Summary:
        //     Returns a value that indicates whether two specified instances of System.TimeSpan
        //     are equal.
        //
        // Parameters:
        //   t1:
        //     The first time interval to compare.
        //
        //   t2:
        //     The second time interval to compare.
        //
        // Returns:
        //     true if the values of t1 and t2 are equal; otherwise, false.
        public static bool Equals(TimeSpan t1, TimeSpan t2)
        {
            return t1.ticks == t2.ticks;
        }
        //
        // Summary:
        //     Returns a System.TimeSpan that represents a specified number of days, where
        //     the specification is accurate to the nearest millisecond.
        //
        // Parameters:
        //   value:
        //     A number of days, accurate to the nearest millisecond.
        //
        // Returns:
        //     An object that represents value.
        //
        // Exceptions:
        //   System.OverflowException:
        //     value is less than System.TimeSpan.MinValue or greater than System.TimeSpan.MaxValue.
        //     -or-value is System.Double.PositiveInfinity.-or-value is System.Double.NegativeInfinity.
        //
        //   System.ArgumentException:
        //     value is equal to System.Double.NaN.
        public static TimeSpan FromDays(double value)
        {
            return From(value, TicksPerDay);
        }
        //
        // Summary:
        //     Returns a System.TimeSpan that represents a specified number of hours, where
        //     the specification is accurate to the nearest millisecond.
        //
        // Parameters:
        //   value:
        //     A number of hours accurate to the nearest millisecond.
        //
        // Returns:
        //     An object that represents value.
        //
        // Exceptions:
        //   System.OverflowException:
        //     value is less than System.TimeSpan.MinValue or greater than System.TimeSpan.MaxValue.
        //     -or-value is System.Double.PositiveInfinity.-or-value is System.Double.NegativeInfinity.
        //
        //   System.ArgumentException:
        //     value is equal to System.Double.NaN.
        public static TimeSpan FromHours(double value)
        {
            return From(value, TicksPerHour);
        }
        //
        // Summary:
        //     Returns a System.TimeSpan that represents a specified number of milliseconds.
        //
        // Parameters:
        //   value:
        //     A number of milliseconds.
        //
        // Returns:
        //     An object that represents value.
        //
        // Exceptions:
        //   System.OverflowException:
        //     value is less than System.TimeSpan.MinValue or greater than System.TimeSpan.MaxValue.-or-value
        //     is System.Double.PositiveInfinity.-or-value is System.Double.NegativeInfinity.
        //
        //   System.ArgumentException:
        //     value is equal to System.Double.NaN.
        public static TimeSpan FromMilliseconds(double value)
        {
            return From (value, TicksPerMillisecond);
        }
        //
        // Summary:
        //     Returns a System.TimeSpan that represents a specified number of minutes,
        //     where the specification is accurate to the nearest millisecond.
        //
        // Parameters:
        //   value:
        //     A number of minutes, accurate to the nearest millisecond.
        //
        // Returns:
        //     An object that represents value.
        //
        // Exceptions:
        //   System.OverflowException:
        //     value is less than System.TimeSpan.MinValue or greater than System.TimeSpan.MaxValue.-or-value
        //     is System.Double.PositiveInfinity.-or-value is System.Double.NegativeInfinity.
        //
        //   System.ArgumentException:
        //     value is equal to System.Double.NaN.
        public static TimeSpan FromMinutes(double value)
        {
            return From(value, TicksPerMinute);
        }
        //
        // Summary:
        //     Returns a System.TimeSpan that represents a specified number of seconds,
        //     where the specification is accurate to the nearest millisecond.
        //
        // Parameters:
        //   value:
        //     A number of seconds, accurate to the nearest millisecond.
        //
        // Returns:
        //     An object that represents value.
        //
        // Exceptions:
        //   System.OverflowException:
        //     value is less than System.TimeSpan.MinValue or greater than System.TimeSpan.MaxValue.-or-value
        //     is System.Double.PositiveInfinity.-or-value is System.Double.NegativeInfinity.
        //
        //   System.ArgumentException:
        //     value is equal to System.Double.NaN.
        public static TimeSpan FromSeconds(double value)
        {
            return From(value, TicksPerSecond);
        }

        private static TimeSpan From(double value, long tickMultiplicator)
        {
            if (Double.IsNaN(value))
                throw new ArgumentException("Value cannot be NaN.", "value");

            if (Double.IsInfinity(value) || (value < MinValue.Ticks) || (value > MaxValue.Ticks))
                throw new OverflowException("Outside range [MinValue,MaxValue]");

            try
            {
                value = (value * (tickMultiplicator / TicksPerMillisecond));

                long val = (long)Math.Round(value, MidpointRounding.AwayFromZero);
                return new TimeSpan(val * TicksPerMillisecond);
            }
            catch (OverflowException)
            {
                throw new OverflowException("Resulting timespan is too big.");
            }
        }
        //
        // Summary:
        //     Returns a System.TimeSpan that represents a specified time, where the specification
        //     is in units of ticks.
        //
        // Parameters:
        //   value:
        //     A number of ticks that represent a time.
        //
        // Returns:
        //     An object that represents value.
        public static TimeSpan FromTicks(long value)
        {
            return new TimeSpan(value);
        }
        //
        // Summary:
        //     Returns a hash code for this instance.
        //
        // Returns:
        //     A 32-bit signed integer hash code.
        public override int GetHashCode()
        {
            return ticks.GetHashCode();
        }
        //
        // Summary:
        //     Returns a new System.TimeSpan object whose value is the negated value of
        //     this instance.
        //
        // Returns:
        //     A new object with the same numeric value as this instance, but with the opposite
        //     sign.
        //
        // Exceptions:
        //   System.OverflowException:
        //     The negated value of this instance cannot be represented by a System.TimeSpan;
        //     that is, the value of this instance is System.TimeSpan.MinValue.
        public TimeSpan Negate()
        {
            if (ticks == MinValue.Ticks)
                throw new OverflowException("This TimeSpan value is MinValue and cannot be negated.");

            return new TimeSpan(-ticks);
        }
        //
        // Summary:
        //     Converts the string representation of a time interval to its System.TimeSpan
        //     equivalent.
        //
        // Parameters:
        //   s:
        //     A string that specifies the time interval to convert.
        //
        // Returns:
        //     A time interval that corresponds to s.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     s is null.
        //
        //   System.FormatException:
        //     s has an invalid format.
        //
        //   System.OverflowException:
        //     s represents a number that is less than System.TimeSpan.MinValue or greater
        //     than System.TimeSpan.MaxValue.-or- At least one of the days, hours, minutes,
        //     or seconds components is outside its valid range.
        public static TimeSpan Parse(string s)
        {
            throw new NotImplementedException("System.TimeSpan.Parse");
        }

#if DOTNET_4
        //
        // Summary:
        //     Converts the string representation of a time interval to its System.TimeSpan
        //     equivalent by using the specified culture-specific format information.
        //
        // Parameters:
        //   input:
        //     A string that specifies the time interval to convert.
        //
        //   formatProvider:
        //     An object that supplies culture-specific formatting information.
        //
        // Returns:
        //     A time interval that corresponds to input, as specified by formatProvider.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     input is null.
        //
        //   System.FormatException:
        //     input has an invalid format.
        //
        //   System.OverflowException:
        //     input represents a number that is less than System.TimeSpan.MinValue or greater
        //     than System.TimeSpan.MaxValue.-or- At least one of the days, hours, minutes,
        //     or seconds components in input is outside its valid range.
        public static TimeSpan Parse(string input, IFormatProvider formatProvider);
        //
        // Summary:
        //     Converts the string representation of a time interval to its System.TimeSpan
        //     equivalent by using the specified format and culture-specific format information.
        //     The format of the string representation must match the specified format exactly.
        //
        // Parameters:
        //   input:
        //     A string that specifies the time interval to convert.
        //
        //   format:
        //     A standard or custom format string that defines the required format of input.
        //
        //   formatProvider:
        //     An object that provides culture-specific formatting information.
        //
        // Returns:
        //     A time interval that corresponds to input, as specified by format and formatProvider.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     input is null.
        //
        //   System.FormatException:
        //     input has an invalid format.
        //
        //   System.OverflowException:
        //     input represents a number that is less than System.TimeSpan.MinValue or greater
        //     than System.TimeSpan.MaxValue.-or- At least one of the days, hours, minutes,
        //     or seconds components in input is outside its valid range.
        public static TimeSpan ParseExact(string input, string format, IFormatProvider formatProvider);
        //
        // Summary:
        //     Converts the string representation of a time interval to its System.TimeSpan
        //     equivalent by using the specified array of format strings and culture-specific
        //     format information. The format of the string representation must match one
        //     of the specified formats exactly.
        //
        // Parameters:
        //   input:
        //     A string that specifies the time interval to convert.
        //
        //   formats:
        //     A array of standard or custom format strings that defines the required format
        //     of input.
        //
        //   formatProvider:
        //     An object that provides culture-specific formatting information.
        //
        // Returns:
        //     A time interval that corresponds to input, as specified by formats and formatProvider.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     input is null.
        //
        //   System.FormatException:
        //     input has an invalid format.
        //
        //   System.OverflowException:
        //     input represents a number that is less than System.TimeSpan.MinValue or greater
        //     than System.TimeSpan.MaxValue.-or- At least one of the days, hours, minutes,
        //     or seconds components in input is outside its valid range.
        public static TimeSpan ParseExact(string input, string[] formats, IFormatProvider formatProvider);
        //
        // Summary:
        //     Converts the string representation of a time interval to its System.TimeSpan
        //     equivalent by using the specified format, culture-specific format information,
        //     and styles. The format of the string representation must match the specified
        //     format exactly.
        //
        // Parameters:
        //   input:
        //     A string that specifies the time interval to convert.
        //
        //   format:
        //     A standard or custom format string that defines the required format of input.
        //
        //   formatProvider:
        //     An object that provides culture-specific formatting information.
        //
        //   styles:
        //     A bitwise combination of enumeration values that defines the style elements
        //     that may be present in input.
        //
        // Returns:
        //     A time interval that corresponds to input, as specified by format, formatProvider,
        //     and styles.
        //
        // Exceptions:
        //   System.ArgumentException:
        //     styles is an invalid System.Globalization.TimeSpanStyles value.
        //
        //   System.ArgumentNullException:
        //     input is null.
        //
        //   System.FormatException:
        //     input has an invalid format.
        //
        //   System.OverflowException:
        //     input represents a number that is less than System.TimeSpan.MinValue or greater
        //     than System.TimeSpan.MaxValue.-or- At least one of the days, hours, minutes,
        //     or seconds components in input is outside its valid range.
        public static TimeSpan ParseExact(string input, string format, IFormatProvider formatProvider, TimeSpanStyles styles);
        //
        // Summary:
        //     Converts the string representation of a time interval to its System.TimeSpan
        //     equivalent by using the specified formats, culture-specific format information,
        //     and styles. The format of the string representation must match one of the
        //     specified formats exactly.
        //
        // Parameters:
        //   input:
        //     A string that specifies the time interval to convert.
        //
        //   formats:
        //     A array of standard or custom format strings that define the required format
        //     of input.
        //
        //   formatProvider:
        //     An object that provides culture-specific formatting information.
        //
        //   styles:
        //     A bitwise combination of enumeration values that defines the style elements
        //     that may be present in input.
        //
        // Returns:
        //     A time interval that corresponds to input, as specified by formats, formatProvider,
        //     and styles.
        //
        // Exceptions:
        //   System.ArgumentException:
        //     styles is an invalid System.Globalization.TimeSpanStyles value.
        //
        //   System.ArgumentNullException:
        //     input is null.
        //
        //   System.FormatException:
        //     input has an invalid format.
        //
        //   System.OverflowException:
        //     input represents a number that is less than System.TimeSpan.MinValue or greater
        //     than System.TimeSpan.MaxValue.-or- At least one of the days, hours, minutes,
        //     or seconds components in input is outside its valid range.
        public static TimeSpan ParseExact(string input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles);
        //
        // Summary:
        //     Returns a new System.TimeSpan object whose value is the difference between
        //     the specified System.TimeSpan object and this instance.
        //
        // Parameters:
        //   ts:
        //     The time interval to be subtracted.
        //
        // Returns:
        //     A new time interval whose value is the result of the value of this instance
        //     minus the value of ts.
        //
        // Exceptions:
        //   System.OverflowException:
        //     The return value is less than System.TimeSpan.MinValue or greater than System.TimeSpan.MaxValue.
#endif
        public TimeSpan Subtract(TimeSpan ts)
        {
            return new TimeSpan(ticks - ts.Ticks);
        }
        //
        // Summary:
        //     Converts the value of the current System.TimeSpan object to its equivalent
        //     string representation.
        //
        // Returns:
        //     The string representation of the current System.TimeSpan value.
        private const char Null = '\0';

        public override string ToString()
        {
            return ToStandardString(Null, null);
        }

        public string ToString(IFormatProvider formatProvider)
        {
            return ToStandardString(Null, formatProvider);
        }

        private string ToStandardString(char nullOrG, IFormatProvider formatProvider)
        {
            StringBuilder sb = new StringBuilder(14);

            long negTicks = this.ticks;
            if (negTicks < 0)
            {
                sb.Append('-');
            }
            else
            {
                // we work with negative values, to avoid special handling of MinValue
                negTicks = -negTicks;
            }

            int days = -GetDays(negTicks);

            if (days != 0 || nullOrG == 'G')
            {
                sb.Append(days);
                sb.Append(nullOrG == Null ? '.' : ':');
            }

            int hours = -GetHours(negTicks);
            if (hours < 10) sb.Append("0");
            sb.Append(hours);
            sb.Append(':');

            int minutes = -GetMinutes(negTicks);
            if (minutes < 10) sb.Append("0");
            sb.Append(minutes);
            sb.Append(':');

            int seconds = -GetSeconds(negTicks);
            if (seconds < 10) sb.Append("0");
            sb.Append(seconds);

            int fractional = (int)(negTicks % TicksPerSecond);
            if (fractional != 0 || nullOrG == 'G')
            {
                if (nullOrG == Null || formatProvider == CultureInfo.InvariantCulture)
                {
                    sb.Append('.');
                }
                else
                {
                    var ni = formatProvider.ToNumberFormatInfo();
                    sb.Append(ni.NumberDecimalSeparator);
                }

                AppendFractional(sb, nullOrG, -fractional, 7);
            }

            return sb.ToString();
        }

        private static void AppendFractional(StringBuilder sb, char nullOrG, int fractional, int maxDigits)
        {
            int currentLength = sb.Length;

            // append the number.
            FormatHelper.Append(sb, fractional, 7);
            int fracLength = sb.Length - currentLength;

            // trim to requested length.
            if (fracLength > maxDigits)
                sb.Remove(currentLength + maxDigits, fracLength - maxDigits);

            // auto-trim trialing zeroes if requested.
            if (nullOrG == 'g')
            {
                // remove zeroes at the end.
                int len = 0, idx;
                for (idx = sb.Length - 1; idx > currentLength + 1; --idx, ++len)
                    if (sb[idx] != '0') break;
                if (len != 0) sb.Remove(idx, len);
            }
        }

        public string ToString(string format, IFormatProvider formatProvider)
        {
            bool isNullOEmpty = string.IsNullOrEmpty(format);

            if (isNullOEmpty || format == "g" || format == "G")
                return ToStandardString(isNullOEmpty ? Null : format[0], formatProvider);

            if (format == "c")
            {
                return ToStandardString(Null, CultureInfo.InvariantCulture);
            }

            var negTicks = ticks;
            if (negTicks > 0) // we work with negative values, to avoid special handling of MinValue
                negTicks = -negTicks;

            StringBuilder sb = new StringBuilder(format.Length + 5);

            DateTimeFormatting.TokenizeFormatString(format, (start, length, isQuote) =>
            {
                if (isQuote)
                {
                    sb.Append(format, start, length);
                }
                else switch (format[start])
                {
                    //if (val[0] == '-')
                    //{
                    //    if (ts.ticks < 0)
                    //        sb.Append('-');
                    //    return;
                    //}

                    case 'd':
                    {
                        FormatHelper.Append(sb, -GetDays(negTicks), length);
                        return;
                    }
                    case 'h':
                    {
                        if (length > 2) throw new FormatException();
                        FormatHelper.Append(sb, -GetHours(negTicks), length);
                        return;
                    }
                    case 'm':
                    {
                        if (length > 2) throw new FormatException();
                        FormatHelper.Append(sb, -GetMinutes(negTicks), length);
                        return;
                    }
                    case 's':
                    {
                        if (length > 2) throw new FormatException();
                        FormatHelper.Append(sb, -GetSeconds(negTicks), length);
                        return;
                    }
                    case 'f':
                    {
                        int fractional = -(int)(negTicks % TicksPerSecond);
                        AppendFractional(sb, Null, fractional, length);
                        return;
                    }
                    case 'F':
                    {
                        int fractional = -(int)(negTicks % TicksPerSecond);
                        if (fractional != 0)
                            AppendFractional(sb, Null, fractional, length);
                        return;
                    }
                    default:
                        throw new FormatException();
                }
            });

            return sb.ToString();
        }

#if DOTNET_4
        //
        // Summary:
        //     Converts the value of the current System.TimeSpan object to its equivalent
        //     string representation by using the specified format.
        //
        // Parameters:
        //   format:
        //     A standard or custom System.TimeSpan format string.
        //
        // Returns:
        //     The string representation of the current System.TimeSpan value in the format
        //     specified by the format parameter.
        //
        // Exceptions:
        //   System.FormatException:
        //     The format parameter is not recognized or is not supported.
        public string ToString(string format);
        //
        // Summary:
        //     Converts the value of the current System.TimeSpan object to its equivalent
        //     string representation by using the specified format and culture-specific
        //     formatting information.
        //
        // Parameters:
        //   format:
        //     A standard or custom System.TimeSpan format string.
        //
        //   formatProvider:
        //     An object that supplies culture-specific formatting information.
        //
        // Returns:
        //     The string representation of the current System.TimeSpan value, as specified
        //     by format and formatProvider.
        //
        // Exceptions:
        //   System.FormatException:
        //     The format parameter is not recognized or is not supported.
        public string ToString(string format, IFormatProvider formatProvider);
        //
        // Summary:
        //     Converts the string representation of a time interval to its System.TimeSpan
        //     equivalent and returns a value that indicates whether the conversion succeeded.
        //
        // Parameters:
        //   s:
        //     A string that specifies the time interval to convert.
        //
        //   result:
        //     When this method returns, contains an object that represents the time interval
        //     specified by s, or System.TimeSpan.Zero if the conversion failed. This parameter
        //     is passed uninitialized.
        //
        // Returns:
        //     true if s was converted successfully; otherwise, false. This operation returns
        //     false if the s parameter is null or System.String.Empty, has an invalid format,
        //     represents a time interval that is less than System.TimeSpan.MinValue or
        //     greater than System.TimeSpan.MaxValue, or has at least one days, hours, minutes,
        //     or seconds component outside its valid range.
        public static bool TryParse(string s, out TimeSpan result);
        //
        // Summary:
        //     Converts the string representation of a time interval to its System.TimeSpan
        //     equivalent by using the specified culture-specific formatting information,
        //     and returns a value that indicates whether the conversion succeeded.
        //
        // Parameters:
        //   input:
        //     A string that specifies the time interval to convert.
        //
        //   formatProvider:
        //     An object that supplies culture-specific formatting information.
        //
        //   result:
        //     When this method returns, contains an object that represents the time interval
        //     specified by input, or System.TimeSpan.Zero if the conversion failed. This
        //     parameter is passed uninitialized.
        //
        // Returns:
        //     true if input was converted successfully; otherwise, false. This operation
        //     returns false if the input parameter is null or System.String.Empty, has
        //     an invalid format, represents a time interval that is less than System.TimeSpan.MinValue
        //     or greater than System.TimeSpan.MaxValue, or has at least one days, hours,
        //     minutes, or seconds component outside its valid range.
        public static bool TryParse(string input, IFormatProvider formatProvider, out TimeSpan result);
        //
        // Summary:
        //     Converts the string representation of a time interval to its System.TimeSpan
        //     equivalent by using the specified format and culture-specific format information,
        //     and returns a value that indicates whether the conversion succeeded. The
        //     format of the string representation must match the specified format exactly.
        //
        // Parameters:
        //   input:
        //     A string that specifies the time interval to convert.
        //
        //   format:
        //     A standard or custom format string that defines the required format of input.
        //
        //   formatProvider:
        //     An object that supplies culture-specific formatting information.
        //
        //   result:
        //     When this method returns, contains an object that represents the time interval
        //     specified by input, or System.TimeSpan.Zero if the conversion failed. This
        //     parameter is passed uninitialized.
        //
        // Returns:
        //     true if input was converted successfully; otherwise, false.
        public static bool TryParseExact(string input, string format, IFormatProvider formatProvider, out TimeSpan result);
        //
        // Summary:
        //     Converts the specified string representation of a time interval to its System.TimeSpan
        //     equivalent by using the specified formats and culture-specific format information,
        //     and returns a value that indicates whether the conversion succeeded. The
        //     format of the string representation must match one of the specified formats
        //     exactly.
        //
        // Parameters:
        //   input:
        //     A string that specifies the time interval to convert.
        //
        //   formats:
        //     A array of standard or custom format strings that define the acceptable formats
        //     of input.
        //
        //   formatProvider:
        //     An object that provides culture-specific formatting information.
        //
        //   result:
        //     When this method returns, contains an object that represents the time interval
        //     specified by input, or System.TimeSpan.Zero if the conversion failed. This
        //     parameter is passed uninitialized.
        //
        // Returns:
        //     true if input was converted successfully; otherwise, false.
        public static bool TryParseExact(string input, string[] formats, IFormatProvider formatProvider, out TimeSpan result);
        //
        // Summary:
        //     Converts the string representation of a time interval to its System.TimeSpan
        //     equivalent by using the specified format, culture-specific format information,
        //     and styles, and returns a value that indicates whether the conversion succeeded.
        //     The format of the string representation must match the specified format exactly.
        //
        // Parameters:
        //   input:
        //     A string that specifies the time interval to convert.
        //
        //   format:
        //     A standard or custom format string that defines the required format of input.
        //
        //   formatProvider:
        //     An object that provides culture-specific formatting information.
        //
        //   styles:
        //     One or more enumeration values that indicate the style of input.
        //
        //   result:
        //     When this method returns, contains an object that represents the time interval
        //     specified by input, or System.TimeSpan.Zero if the conversion failed. This
        //     parameter is passed uninitialized.
        //
        // Returns:
        //     true if input was converted successfully; otherwise, false.
        public static bool TryParseExact(string input, string format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result);
        //
        // Summary:
        //     Converts the specified string representation of a time interval to its System.TimeSpan
        //     equivalent by using the specified formats, culture-specific format information,
        //     and styles, and returns a value that indicates whether the conversion succeeded.
        //     The format of the string representation must match one of the specified formats
        //     exactly.
        //
        // Parameters:
        //   input:
        //     A string that specifies the time interval to convert.
        //
        //   formats:
        //     A array of standard or custom format strings that define the acceptable formats
        //     of input.
        //
        //   formatProvider:
        //     An object that supplies culture-specific formatting information.
        //
        //   styles:
        //     One or more enumeration values that indicate the style of input.
        //
        //   result:
        //     When this method returns, contains an object that represents the time interval
        //     specified by input, or System.TimeSpan.Zero if the conversion failed. This
        //     parameter is passed uninitialized.
        //
        // Returns:
        //     true if input was converted successfully; otherwise, false.
        public static bool TryParseExact(string input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result);
#endif
    }
}


text:
package com.azure.resourcemanager.recoveryservicesbackup.generated;

import com.azure.core.util.BinaryData;
import com.azure.resourcemanager.recoveryservicesbackup.models.AzureVMAppContainerProtectableContainer;
import com.azure.resourcemanager.recoveryservicesbackup.models.BackupManagementType;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public final class AzureVMAppContainerProtectableContainerTests {
    @Test
    public void testDeserialize() {
        AzureVMAppContainerProtectableContainer model =
            BinaryData
                .fromString(
                    "{\"protectableContainerType\":\"VMAppContainer\",\"friendlyName\":\"qs\",\"backupManagementType\":\"DPM\",\"healthStatus\":\"aelcat\",\"containerId\":\"ju\"}")
                .toObject(AzureVMAppContainerProtectableContainer.class);
        Assertions.assertEquals("qs", model.friendlyName());
        Assertions.assertEquals(BackupManagementType.DPM, model.backupManagementType());
        Assertions.assertEquals("aelcat", model.healthStatus());
        Assertions.assertEquals("ju", model.containerId());
    }

    @Test
    public void testSerialize() {
        AzureVMAppContainerProtectableContainer model =
            new AzureVMAppContainerProtectableContainer()
                .withFriendlyName("qs")
                .withBackupManagementType(BackupManagementType.DPM)
                .withHealthStatus("aelcat")
                .withContainerId("ju");
        model = BinaryData.fromObject(model).toObject(AzureVMAppContainerProtectableContainer.class);
        Assertions.assertEquals("qs", model.friendlyName());
        Assertions.assertEquals(BackupManagementType.DPM, model.backupManagementType());
        Assertions.assertEquals("aelcat", model.healthStatus());
        Assertions.assertEquals("ju", model.containerId());
    }
}


text:
<!DOCTYPE html>

      <input type="text">

          <input type="text">

      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

Footer Inside Iframe