text:
The sample source codes on this page shows how to set navigation bookmarks in pdf with pdf sdk in C#. ByteScout Premium Suite: the bundle that includes twelve SDK products from ByteScout including tools and components for PDF, barcodes, spreadsheets, screen video recording. It can set navigation bookmarks in pdf with pdf sdk in C#.

This prolific sample source code in C# for ByteScout Premium Suite contains various functions and other necessary options you should do calling the API to set navigation bookmarks in pdf with pdf sdk. This C# sample code is all you need for your app. Just copy and paste the code, add references (if needs to) and you are all set! Want to see how it works with your data then code testing will allow the function to be tested and work properly.

The trial version of ByteScout Premium Suite can be downloaded for free from our website. It also includes source code samples for C# and other programming languages.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20Premium%20Suite%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20Premium%20Suite%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8)

<!-- code block begin -->

##### ****Bookmarks.NETCore.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
    <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
    <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
    <GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute>
    <GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute>
    <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
    <GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
    <GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
    <GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
    <GenerateAssemblyTrademarkAttribute>false</GenerateAssemblyTrademarkAttribute>
    <GenerateAssemblyCultureAttribute>false</GenerateAssemblyCultureAttribute>
    <GenerateAssemblyDescriptionAttribute>false</GenerateAssemblyDescriptionAttribute>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Windows.Compatibility" Version="2.0.0" />
  </ItemGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDF">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>c:\Program Files\Bytescout PDF SDK\netcoreapp2.0\Bytescout.PDF.dll</HintPath>
    </Reference>
  </ItemGroup>
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****Bookmarks.VS2005.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{474F52FF-3928-44EA-8F6F-379E9DAA23FF}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>Bookmarks</RootNamespace>
    <AssemblyName>Bookmarks</AssemblyName>
    <FileAlignment>512</FileAlignment>
    <ProductVersion>8.0.50727</ProductVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDF, Version=1.0.0.15, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Drawing" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****Bookmarks.VS2008.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{474F52FF-3928-44EA-8F6F-379E9DAA23FF}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>Bookmarks</RootNamespace>
    <AssemblyName>Bookmarks</AssemblyName>
    <TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <ProductVersion>9.0.30729</ProductVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDF, Version=1.0.0.15, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Drawing" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****Bookmarks.VS2010.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{474F52FF-3928-44EA-8F6F-379E9DAA23FF}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>Bookmarks</RootNamespace>
    <AssemblyName>Bookmarks</AssemblyName>
    <TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDF, Version=1.0.0.15, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Drawing" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****Bookmarks.VS2012.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{474F52FF-3928-44EA-8F6F-379E9DAA23FF}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>Bookmarks</RootNamespace>
    <AssemblyName>Bookmarks</AssemblyName>
    <TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDF, Version=1.0.0.15, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Drawing" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****Bookmarks.VS2013.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{474F52FF-3928-44EA-8F6F-379E9DAA23FF}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>Bookmarks</RootNamespace>
    <AssemblyName>Bookmarks</AssemblyName>
    <TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDF, Version=1.0.0.15, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Drawing" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****Bookmarks.VS2015.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{474F52FF-3928-44EA-8F6F-379E9DAA23FF}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>Bookmarks</RootNamespace>
    <AssemblyName>Bookmarks</AssemblyName>
    <TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDF, Version=1.0.0.15, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Drawing" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****Program.cs:**

```
using System.CodeDom;
using System.Diagnostics;
using Bytescout.PDF;

namespace Bookmarks
{
    /// <summary>
    /// This example demonstrates how to create document outlines (bookmarks).
    /// </summary>
    class Program
    {
        static void Main()
        {
            // Create new document
            Document pdfDocument = new Document();
            pdfDocument.RegistrationName = "demo";
            pdfDocument.RegistrationKey = "demo";

            Font font = new Font(StandardFonts.Times, 18);
            Brush brush = new SolidBrush();

            // Create pages
            for (int i = 0; i < 3; i++)
            {
                Page page = new Page(PaperFormat.A4);
                page.Canvas.DrawString(string.Format("Page {0}", i + 1), font, brush, 20, 20);
                pdfDocument.Pages.Add(page);
            }

            // Create outlines:

            Destination destination1 = new Destination(pdfDocument.Pages[0]);
            Outline outline1 = new Outline("Page 1", destination1);
            pdfDocument.Outlines.Add(outline1);

            // Example of sub-bookmark
            Destination destination2 = new Destination(pdfDocument.Pages[1]);
            Outline outline2 = new Outline("Page 2", destination2);
            pdfDocument.Outlines[0].Kids.Add(outline2);

            Destination destination3 = new Destination(pdfDocument.Pages[2]);
            Outline outline3 = new Outline("Page 3", destination3);
            pdfDocument.Outlines.Add(outline3);

            // Force PDF viewer to show Bookmarks panel at start up.
            pdfDocument.PageMode = PageMode.Outlines;

            // Save document to file
            pdfDocument.Save("result.pdf");

            // Cleanup
            pdfDocument.Dispose();

            // Open result document in default associated application (for demo purpose)
            ProcessStartInfo processStartInfo = new ProcessStartInfo("result.pdf");
            processStartInfo.UseShellExecute = true;
            Process.Start(processStartInfo);
        }
    }
}

```

<!-- code block end -->


text:
package org.apache.fontbox.afm;

/**
 * This class represents a ligature, which is an entry of the CharMetrics.
 *
 * @author Ben Litchfield
 */
public class Ligature
{
    private final String successor;
    private final String liga;

    public Ligature(String successor, String ligature)
    {
        this.successor = successor;
        this.liga = ligature;
    }

    /** Getter for property ligature.
     * @return Value of property ligature.
     */
    public String getLigature()
    {
        return liga;
    }

    /** Getter for property successor.
     * @return Value of property successor.
     */
    public String getSuccessor()
    {
        return successor;
    }

}

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <aws/servicediscovery/ServiceDiscovery_EXPORTS.h>
#include <aws/servicediscovery/ServiceDiscoveryRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace ServiceDiscovery
{
namespace Model
{

  /**
   */
  class AWS_SERVICEDISCOVERY_API GetOperationRequest : public ServiceDiscoveryRequest
  {
  public:
    GetOperationRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "GetOperation"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The ID of the operation that you want to get more information about.

     */
    inline const Aws::String& GetOperationId() const{ return m_operationId; }

    /**
     *
The ID of the operation that you want to get more information about.

     */
    inline bool OperationIdHasBeenSet() const { return m_operationIdHasBeenSet; }

    /**
     *
The ID of the operation that you want to get more information about.

     */
    inline void SetOperationId(const Aws::String& value) { m_operationIdHasBeenSet = true; m_operationId = value; }

    /**
     *
The ID of the operation that you want to get more information about.

     */
    inline void SetOperationId(Aws::String&& value) { m_operationIdHasBeenSet = true; m_operationId = std::move(value); }

    /**
     *
The ID of the operation that you want to get more information about.

     */
    inline void SetOperationId(const char* value) { m_operationIdHasBeenSet = true; m_operationId.assign(value); }

    /**
     *
The ID of the operation that you want to get more information about.

     */
    inline GetOperationRequest& WithOperationId(const Aws::String& value) { SetOperationId(value); return *this;}

    /**
     *
The ID of the operation that you want to get more information about.

     */
    inline GetOperationRequest& WithOperationId(Aws::String&& value) { SetOperationId(std::move(value)); return *this;}

    /**
     *
The ID of the operation that you want to get more information about.

     */
    inline GetOperationRequest& WithOperationId(const char* value) { SetOperationId(value); return *this;}

  private:

    Aws::String m_operationId;
    bool m_operationIdHasBeenSet;
  };

} // namespace Model
} // namespace ServiceDiscovery
} // namespace Aws


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>test</title>

  test

  test
  test


text:
#ifndef PageDebuggerAgent_h
#define PageDebuggerAgent_h

#include "core/CoreExport.h"
#include "core/inspector/InspectorDebuggerAgent.h"

using blink::TypeBuilder::Debugger::ExceptionDetails;
using blink::TypeBuilder::Debugger::ScriptId;
using blink::TypeBuilder::Runtime::RemoteObject;

namespace blink {

class DocumentLoader;
class InspectedFrames;
class MainThreadDebugger;

class CORE_EXPORT PageDebuggerAgent final
    : public InspectorDebuggerAgent {
    WTF_MAKE_NONCOPYABLE(PageDebuggerAgent);
    USING_FAST_MALLOC_WILL_BE_REMOVED(PageDebuggerAgent);
public:
    static PassOwnPtrWillBeRawPtr<PageDebuggerAgent> create(MainThreadDebugger*, InspectedFrames*, InjectedScriptManager*);
    ~PageDebuggerAgent() override;
    DECLARE_VIRTUAL_TRACE();

    void enable(ErrorString*) final;
    void disable(ErrorString*) final;
    void restore() final;
    void compileScript(ErrorString*, const String& expression, const String& sourceURL, bool persistScript, int executionContextId, TypeBuilder::OptOutput<TypeBuilder::Debugger::ScriptId>*, RefPtr<TypeBuilder::Debugger::ExceptionDetails>&) override;
    void runScript(ErrorString*, const TypeBuilder::Debugger::ScriptId&, int executionContextId, const String* objectGroup, const bool* doNotPauseOnExceptionsAndMuteConsole, RefPtr<TypeBuilder::Runtime::RemoteObject>& result, RefPtr<TypeBuilder::Debugger::ExceptionDetails>&) override;

    void didStartProvisionalLoad(LocalFrame*);
    void didClearDocumentOfWindowObject(LocalFrame*);

private:
    PageDebuggerAgent(MainThreadDebugger*, InspectedFrames*, InjectedScriptManager*);
    void muteConsole() override;
    void unmuteConsole() override;

    // V8DebuggerAgent::Client implemntation.
    bool canExecuteScripts() const;

    InspectedFrames* m_inspectedFrames;
    RawPtrWillBeMember<InjectedScriptManager> m_injectedScriptManager;
    HashMap<String, String> m_compiledScriptURLs;
};

} // namespace blink

#endif // !defined(PageDebuggerAgent_h)


text:
import {observable, computed} from 'mobx';
import BusinessModel from '../models/BusinessModel';
import OfferStore from '../stores/OfferStore';
import CouponModel from '../models/CouponModel'
import ClientStore from '../stores/ClientStore';
import CouponStore from '../stores/CouponStore';
import {hashHistory } from 'react-router'
import * as firebase from 'firebase';

const LOGIN_PROVIDERS = {
	FACEBOOK: 'facebook',
	GOOGLE: 'google'
}

export default class BuisnessStore {
	@observable business = null;
	@observable initialize = false;
	offerStore = null;
	clientStore = null;
	couponStore = null;

	constructor() {
		this.offerStore = new OfferStore();
		this.clientStore = new ClientStore();
		this.couponStore = new CouponStore();
		this.startObserve()

	}

	init(business){
		this.business = business;
		this.offerStore.init(this.business);
		this.clientStore.init(this.business);
		this.couponStore.init(this.business);
		this.initialize = true;

	}

	startObserve(){

		firebase.auth().onAuthStateChanged((user) => {
			if(!this.disableAuthObserver) {
				if (user && !this.business) {
					return this.login(user, user.refreshToken)
				} else {
					this.initialize = true;

				}
			}
		})
	}

	@computed get isLoggedIn(){
		return !!this.business ;
	}

	@computed get isInitialized(){
		return !!this.initialize ;
	}

	getProviderData(accessToken){

		return FB.api('/me', 'get', { access_token: accessToken, fields: 'id,last_name,first_name,gender,picture,email' }, (response) => {
			return response;
		});

	}

	handleLoginSuccess(result) {
		var { user, credential } = result;
		this.disableAuthObserver = true
		return Promise.resolve()
		.then(() => {
			if(credential) {
				return FB.api('/me', 'get', { access_token: credential.accessToken, fields: 'id,last_name,first_name,gender,picture,email' }, (providerData) => {
					return this.login(user, providerData)
				});
			}
		})
		.then(() => {
			this.disableAuthObserver = false
		})

	}

	login(currentUser, providerData){
		var isFirstTime = null
		return this.getBusiness(currentUser.uid)
			.then((business) => {
				if(!business) {
					this.addNewBusiness(currentUser, providerData)
						.then((business) => {
							this.init(business)
                             hashHistory.push('/settings');
						})

				}
				else {
					var businessModel = new BusinessModel();
					businessModel.convertFromDB(business);
					businessModel.store = this;
					this.init(businessModel);
                    // hashHistory.push('/offers');

				}
			})
	}

	logout(){
		return firebase.auth().signOut().then(() =>  {
            this.business = null;
            this.offerStore = new OfferStore();
            this.clientStore = new ClientStore();
            this.couponStore = new CouponStore();
			hashHistory.push('/');

			return;
		})

	}

	getBusiness(id){
		return firebase.database().ref('/business/' + id).once('value').then(function(snapshot) {
			return  snapshot.val();
		});

	}

	save(businessModel){

        var businessModelDB = businessModel.convertToDB();
        return Promise.all([
            firebase.database().ref('/business').child(businessModelDB.id).child('address').set(businessModelDB.address || ""),
            firebase.database().ref('/business').child(businessModelDB.id).child('businessType').set(businessModelDB.businessType || ""),
            firebase.database().ref('/business').child(businessModelDB.id).child('description').set(businessModelDB.description || ""),
            firebase.database().ref('/business').child(businessModelDB.id).child('email').set(businessModelDB.email || ""),
            firebase.database().ref('/business').child(businessModelDB.id).child('facebook').set(businessModelDB.facebook || ""),
            firebase.database().ref('/business').child(businessModelDB.id).child('firstName').set(businessModelDB.firstName || ""),
            firebase.database().ref('/business').child(businessModelDB.id).child('imageUrl').set(businessModelDB.imageUrl || ""),
            firebase.database().ref('/business').child(businessModelDB.id).child('phone').set(businessModelDB.phone || ""),
            firebase.database().ref('/business').child(businessModelDB.id).child('picture').set(businessModelDB.picture || ""),
            firebase.database().ref('/business').child(businessModelDB.id).child('title').set(businessModelDB.title || ""),
            firebase.database().ref('/business').child(businessModelDB.id).child('website').set(businessModelDB.website || "")]

        ).then(() => {
            return firebase.database().ref('coupons').orderByChild("businessId").equalTo(businessModel.id).once("value").then((snapshot) => {
                    var couponsObj = snapshot.val();
                    if(couponsObj) {
                        for (var key in couponsObj) {
                            businessModelDB = businessModel.convertToDB();
                            if (couponsObj.hasOwnProperty(key)) {
                                var coupon = couponsObj[key];
                                firebase.database().ref('coupons').child(coupon.id).child('bussineData').set(businessModelDB)

                            }
                        }
                    }
                })
            })

	}

	addNewBusiness(currentUser, providerData) {
		var business = new BusinessModel(currentUser);
		business.picture = providerData.picture || ""
		business.firstName = providerData.first_name || ""
		business.lastName = providerData.last_name || ""
		business.email = providerData.email || ""
		var businessModelDB = business.convertToDB();
		return firebase.database().ref('/business').child(currentUser.uid).set(businessModelDB)
			.then(() => {
				business.store = this;
				return business;
			})
	}

	toJS() {
		return this.clients.map(client => client.toJS());
	}

	static fromJS(array) {
		// store.clients = array.map(item => ClientModel.fromJS(clientStore, item));
		return store;
	}
}


text:
<?php

namespace Jasig;

require_once(dirname(__FILE__).'/Exception.php');

/**
 * An Exception for errors related to fetching or validating proxy tickets.
 */
class CAS_ProxyTicketException
	extends \BadMethodCallException
	implements CAS_Exception
{

	/**
	 * Constructor
	 *
	 * @param string $message
	 * @param optional int $code
	 * @param optional Exception $previous
	 * @return void
	 */
	public function __construct ($message, $code = PHPCAS_SERVICE_PT_FAILURE) {
		// Warn if the code is not in our allowed list
		$ptCodes = array(
			PHPCAS_SERVICE_PT_FAILURE,
			PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE,
			PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE,
		);
		if (!in_array($code, $ptCodes)) {
			trigger_error('Invalid code '.$code.' passed. Must be one of PHPCAS_SERVICE_PT_FAILURE, PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, or PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE.');
		}

		parent::__construct($message, $code);
	}
}


text:
package com.luzhishen.easypackage.facade.controllers;

import java.util.List;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.luzhishen.easypackage.facade.constant.ErrorCode;
import com.luzhishen.easypackage.facade.entity.App;
import com.luzhishen.easypackage.facade.model.Result;
import com.luzhishen.easypackage.facade.service.TaskService;

@Path("/data")
@LoginCheckRequired
public class DataController {
    private static final Logger logger = LoggerFactory
            .getLogger(DataController.class);

    @Autowired
    private TaskService taskService;

    @Get("getBranchList")
    public String getAllBranch(Invocation inv, @Param("appId") Integer appId) {
        App app = null;
        if ((app = taskService.findApp(appId)) == null) {
            return "@" + Result.newInstance(ErrorCode.InvalidParam);
        }
        List<String> branchList = taskService.getBranchList(app.getId());
        Result result = Result.newInstance(ErrorCode.Success, branchList);
        logger.debug("result:{}", result);
        return "@" + result;
    }

    @Get("getVersionName")
    public String getVersionName(Invocation inv, @Param("appId") Integer appId,
            @Param("branchName") String branchName) {
        return "@" + Result.newInstance(ErrorCode.Success, "1.2.3");
    }

    /**
     * 从数据库中读取频道信息并不慢,不用在页面用Ajax异步获取
     *
     * @param inv
     * @param appId
     * @return
     */
    @Deprecated
    @Get("getChannelList")
    public String getChannelList(Invocation inv, @Param("appId") Integer appId) {
        App app = null;
        if ((app = taskService.findApp(appId)) == null) {
            return "@" + Result.newInstance(ErrorCode.InvalidParam);
        }
        return "@"
                + Result.newInstance(ErrorCode.Success,
                        taskService.findChannelList(app.getId()));
    }
}


text:
function init(){

  setTimeout(
        function() {
          $("body").css("background", "rgba(214, 214, 214, 0.89)");
          $("body").css("color", "black");
          $(".loading_wrap").hide();
          $(".container").show();
          $("header").show();
          $("footer").show();
      }, 5000);
}

$(function(){
  loadProvincia(init);
});

$(function(){
  $("form").validate();
  $("form").on("submit",function(e){
    showMiniLoading();
    e.preventDefault();
    if($(this).valid()){
      var request = $.ajax({
        url: "/persona/json/new/",
        type: "POST",
        data: $( this ).serialize(),
        dataType: "json"
      });

      request.done(function( msg ) {
        $(".alert p").text(msg.mensaje);
        if(msg.respuesta){
          $(".alert").hide();
          window.location = "../?status=true&operation=new";
        }else{
          $(".alert").removeClass("alert-success");
          $(".alert").addClass("alert-danger");
          $(".alert").show();
          $('html, body').animate({scrollTop : 0},800);
          hideMiniLoading();
        }
      });

      request.fail(function( msg ) {
        $(".alert p").text("Ocurrió un error al realizar el guardado. Intente nuevamente en un instante.");
        $(".alert").removeClass("alert-success");
        $(".alert").addClass("alert-danger");
        $(".alert").show();
        $('html, body').animate({scrollTop : 0},800);
        hideMiniLoading();
      });
    }else{
      hideMiniLoading();
    }
  });
  $("#domicilio_provincia").on("change",function(){
    loadLocalidad($(this).val());
    showMiniLoading();
  });
});

function loadProvincia(callback){

  $.getJSON("/persona/json/list/provincia/", function(data){
    $.each(data, function(index, item){
      $("#domicilio_provincia").append('<option value="'+item.pk+'" >'+item.fields.nombre+'</option>');
    });
    var id_provincia = data[0].pk;
    loadLocalidad(id_provincia);
    if(callback){
      callback.call();
    }
  });
}

function loadLocalidad(id_provincia){
  $("#domicilio_localidad").empty();
  $.getJSON("/persona/json/list/localidad/" + id_provincia  + "/", function(data){
      $.each(data, function(index, item){
        $("#domicilio_localidad").append('<option value="'+item.pk+'" >'+item.fields.nombre+'</option>');
      });
      hideMiniLoading();
    });
}


text:
from collections import MutableSequence
from collections import MutableMapping
from contextlib import contextmanager
import os
import shutil
import tempfile
import hashlib
import re
import logger
import logging

log = logging.getLogger()
log.setLevel(logging.DEBUG)
log.addHandler(logger.RMStreamHandler())

re_url_tail = re.compile('[^\/]+$')
re_url_head = re.compile('^[^\/]+')
re_url_long_tail = re.compile('\/.+$')
re_url_long_head = re.compile('^.+\/')

CHUNK_SIZE = 65536

class FileObject(object):
    def __init__(self, path, mode=0o600, temporary=False, parent=None):
        '''
        Create new file or use already existing one

        @param path: Path to file
        @type path: L{str}
        @param parent: Parent resource
        @type parent: L{DirectoryObject}
        @param mode: Mode bits of file
        @type mode: L{int}
        @param temporary: Is this file has to be deleted when script is done?
        @type temporary: L{bool}
        '''

        self._parent = None
        self.parent = parent
        self._path = os.path.abspath(path)
        self.temporary = temporary
        self.file_name = re_url_tail.search(self.path).group(0)
        self.file_path = re_url_long_head.search(self.path).group(0)

        if os.path.exists(self.path):
            self.mode = mode
        else:
            self._mode = mode
            self.create()

    def __del__(self):
        if self.temporary and os.path.exists(self.path):
            self.remove()

    def __repr__(self):
        return "{}({})".format(
            self.__class__.__name__, repr(self.path)
        )

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.remove()

    @property
    def path(self):
        return self._path

    @path.setter
    def path(self, value):
        new_abspath = os.path.abspath(value)
        if new_abspath != self.path:
            self.__init__(new_abspath, self.parent, self.mode, self.temporary)

    @path.deleter
    def path(self):
        del self._path

    @property
    def mode(self):
        self._mode = os.stat(self.path).st_mode & 0o777
        return self._mode

    @mode.setter
    def mode(self, value):
        self.chmod(value)

    @mode.deleter
    def mode(self):
        del self._mode

    @property
    def parent(self):
        return self._parent

    @parent.setter
    def parent(self, value):
        if isinstance(value, DirectoryObject) and value != self._parent:
            self._parent = value
            self.parent.append(self)

    @parent.deleter
    def parent(self):
        del self._parent

    def unparent(self):
        '''Remove FileObject from parent and set parent to None'''

        if self.parent:
            self.parent.pop(self.parent.index(self))
            self._parent = None

    def create(self):
        '''Create file on the system'''

        try:
            if not os.path.exists(self.path):
                f = open(self.path, 'w')
                f.close()
                self.chmod(self._mode)
        except IOError as exc:
            log.error("Can't create file")
            raise exc

    def remove(self):
        '''Remove file from the system'''

        try:
            os.remove(self.path)
            self.unparent()
        except OSError as exc:
            log.error("Can't remove file")
            raise exc

    def chmod(self, mode):
        '''
        Change mode bits of file

        @param mode: Mode bits of the the file
        @type mode: L{int}
        '''

        try:
            os.chmod(self.path, mode)
            self._mode = mode
        except OSError as exc:
            if exc.errno == 1:
                log.error("Can't change file permissions under current user")
                raise exc
            else:
                log.error("Can't change file permissions")
                raise exc

    def move(self, dst):
        '''
        Move file to destination

        @param dst: Destination path with new file name included
        @type dst: L{str}
        '''

        abs_dst = os.path.abspath(dst)
        try:
            os.rename(self.path, abs_dst)
            self._path = abs_dst
        except OSError as exc:
            log.error("Can't move file")
            raise exc

    def copy(self, dst, same_parent=True):
        '''
        Copy file to destination

        @param dst: Destination path with file name included
        @type dst: L{str}
        @param same_parent: Is the new file has same parent?
        @type same_parent: L{bool}
        @return: New FileObject binded with new file
        '''

        abs_dst = os.path.abspath(dst)
        try:
            shutil.copy2(self.path, abs_dst)
        except IOError as exc:
            log.error("Can't copy file")
            raise exc

        return FileObject(abs_dst, mode, self.temporary,
                          self.parent if same_parent else None)

    def md5(self):
        '''Get md5 hash sum of the file'''

        md5_sum = hashlib.md5()
        with open(self.path, 'rb') as f:
            while True:
                resources = f.read(CHUNK_SIZE)
                if not resources:
                    break
                md5_sum.update(resources)

        return md5_sum.hexdigest()

    def sha1(self):
        '''Get sha1 hash sum of the file'''

        sha1_sum = hashlib.sha1()
        with open(self.path, 'rb') as f:
            while True:
                resources = f.read(CHUNK_SIZE)
                if not resources:
                    break
                sha1_sum.update(resources)

        return sha1_sum.hexdigest()

class DirectoryObject(MutableSequence, object):
    def __init__(self, path, mode=0o700, temporary=False, parent=None):
        '''
        Create new directory or use already existing one

        @param path: Path to directory
        @type path: L{str}
        @param parent: Parent resource
        @type parent: L{DirectoryObject}
        @param mode: Mode bits of directory
        @type mode: L{int}
        @param temporary: Is this directory has to be deleted
        when script is done?
        @type temporary: L{bool}
        '''

        self._parent = None
        self.parent = parent
        self._path = os.path.abspath(path)
        self.temporary = temporary
        self.dir_name = re_url_tail.search(self.path).group(0)
        self.dir_path = re_url_long_head.search(self.path).group(0)
        self.resources = []

        if os.path.exists(self.path):
            self.mode = mode
        else:
            self._mode = mode
            self.create()

    # Collection methods start

    def __getitem__(self, index):
        return self.resources[index]

    def __setitem__(self, index, value):
        self.resources[index] = value

    def __delitem__(self, index):
        del self.resources[index]

    def __iter__(self):
        return iter(self.resources)

    def __len__(self):
        return len(self.resources)

    # Collection methods end

    def __del__(self):
        if self.temporary and os.path.exists(self.path):
            self.remove()

    def __repr__(self):
        return "{}({})".format(
            self.__class__.__name__, repr(self.path)
        )

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.remove()

    @property
    def path(self):
        return self._path

    @path.setter
    def path(self, value):
        new_abspath = os.path.abspath(value)
        if new_abspath != self.path:
            self.__init__(new_abspath, self.parent, self.mode, self.temporary)

    @path.deleter
    def path(self):
        del self._path

    @property
    def mode(self):
        self._mode = os.stat(self.path).st_mode & 0o777
        return self._mode

    @mode.setter
    def mode(self, value):
        self.chmod(value)

    @mode.deleter
    def mode(self):
        del self._mode

    @property
    def parent(self):
        return self._parent

    @parent.setter
    def parent(self, value):
        if isinstance(value, DirectoryObject) and value != self._parent:
            self._parent = value
            self.parent.append(self)

    @parent.deleter
    def parent(self):
        del self._parent

    def unparent(self):
        '''Remove DirectoryObject from parent and set parent to None'''

        if self.parent:
            self.parent.pop(self.parent.index(self))
            self._parent = None

    def create(self):
        '''Create directory on the system'''

        try:
            if not os.path.exists(self.path):
                os.mkdir(self.path, self._mode)
        except OSError as exc:
            log.error("Can't create directory")
            raise exc

    def remove(self):
        '''Remove directory from the system'''

        try:
            shutil.rmtree(self.path)
            self.unparent()
            for el in self.resources:
                el.parent = None
        except IOError as exc:
            log.error("Can't remove directory")
            raise exc

    def chmod(self, mode):
        '''
        Change mode bits of the directory

        @param mode: Mode bits of the file
        @type mode: L{int}
        '''

        try:
            os.chmod(self.path, mode)
            self._mode = mode
        except OSError as exc:
            if exc.errno == 1:
                log.error("Can't change directory "
                          "permissions under current user")
                raise exc
            else:
                log.error(exc)
                raise exc

    def move(self, dst):
        '''
        Move directory to destination

        @param dst: Destination path with new file name included
        @type dst: L{str}
        '''

        abs_dst = os.path.abspath(dst)
        try:
            os.rename(self.path, abs_dst)
            self._path = abs_dst
        except OSError as exc:
            raise exc

    def copy(self, dst, same_parent=True):
        '''
        Copy directory to destination

        @param dst: Destination path with directory name included
        @type dst: L{str}
        @param same_parent: Is the new directory has same parent?
        @type same_parent: L{bool}
        @return: New DirectoryObject binded with new directory
        '''

        abs_dst = os.path.abspath(dst)
        try:
            shutil.copytree(self.path, abs_dst)
        except IOError as exc:
            log.error("Can't copy directory")
            raise exc

        return DirectoryObject(abs_dst, self.mode, self.temporary,
                               self.parent if same_parent else None)

    # Collection methods start

    def append(self, resource):
        '''Append a resource object into collection'''

        if isinstance(resource, FileObject) or \
            isinstance(resource, DirectoryObject) and \
                self.index(resource) is None:
            self.resources.append(resource)
            resource._parent = self

    def insert(self, index, resource):
        '''Insert a resource object into collection'''

        if isinstance(resource, FileObject) or \
            isinstance(resource, DirectoryObject) and \
                self.index(resource) is None:
            self.resources.insert(index, resource)
            resource._parent = self

    def index(self, resource=None, path=None):
        '''Return the index of resource'''

        for el_idx, el in enumerate(self.resources):
            if el == resource or path == el.path:
                return el_idx

    def pop(self, idx):
        '''Return resource on "idx" index and delete it then'''

        self.resources[idx]._parent = None
        return self.resources.pop(idx)

    # Collection methods end

class AliasedDirectoryObject(MutableMapping, DirectoryObject, object):
    def __init__(self, path, mode=0o700, temporary=False, parent=None):
        self.aliases = dict()
        DirectoryObject.__init__(self, path, mode, temporary, parent)

    # Collection methods start

    def __getitem__(self, key):
        return self.resources[self.aliases[key]]

    def __setitem__(self, key, value):
        self.aliases[key] = self.resources.index(value)

    def __delitem__(self, key):
        del self.aliases[key]

    def __iter__(self):
        return iter(self.aliases)

    def __len__(self):
        return len(self.aliases)

    # Collection methods end

    def pop(self, idx):
        '''Return resource on "idx" index and delete it then'''

        self.resources[idx]._parent = None
        return self.resources.pop(idx)

class ResourceManager(object):
    default_aliases = ["Mercury", "Venus", "Earth", "Mars", "Jupiter",
                       "Saturn", "Uranus", "Neptune", "Plutone"]
    alias_n = {"file": 0, "dir": 0}

    def __init__(self, base_path="/tmp/resource-manager/", mode=0o700,
                 temporary=False, rand_prefix=False):
        '''
        Initialize ResourceManger within the prefix path

        @param base_path: Base path of the resources
        @type base_path: L{str}
        @param mode: Mode bits of directory
        @type mode: L{int}
        @param temporary: Is this ResourceManager has to be deleted
        with all the resources under it after script is done?
        @type temporary: L{bool}
        @param rand_prefix: Is the prefix have to be created randomly
        with tempfile?
        @type rand_prefix: L{bool}
        '''

        self.base_path = os.path.abspath(base_path)
        self.temporary = temporary
        DirectoryObject(self.base_path, mode)
        self.prefix_path = tempfile.mkdtemp(prefix=self.base_path + "/") \
            if rand_prefix else self.base_path
        self.resources = AliasedDirectoryObject(self.prefix_path, mode,
                                                temporary)
        self.current_directory = self.resources

    def __del__(self):
        if self.temporary and os.path.exists(self.prefix_path):
            self.remove()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.remove()

    @staticmethod
    def _prepare(path):
        '''
        Pre-create row of the directories for resource

        @param path: Initial path. Tail - name of file/directory, head - path.
        @type path: L{str}
        '''

        prefix = re_url_long_head.search(path).group(0)
        if not os.path.exists(prefix):
            try:
                os.makedirs(prefix)
            except OSError as exc:
                log.error("Can't create prefix for path")
                raise exc

    def resource(self, alias):
        '''
        Return FileObject/DirectoryObject resource if it's in there

        @param alias: Alias name of the resource
        @type alias: L{str}
        @return: FileObject/DirectoryObject resource
        '''

        if alias in self.current_directory:
            if not os.path.exists(self.current_directory[alias].path):
                log.warning("There is no such resource at {}".
                            format(self.current_directory[alias].path))

            return self.current_directory[alias]

    def file(self, alias):
        '''
        Return FileObject resource if it's in there

        @param alias: Alias name of the resource
        @type alias: L{str}
        @return: FileObject resource
        '''

        if alias in self.current_directory and \
                isinstance(self.current_directory[alias], FileObject):
            if not os.path.exists(self.current_directory[alias].path):
                log.warning("There is no such file at {}".
                            format(self.current_directory[alias]))

            return self.current_directory[alias]

    def dir(self, alias):
        '''
        Return DirectoryObject resource if it's in there

        @param alias: Alias name of the resource
        @type alias: L{str}
        @return: DirectoryObject resource
        '''

        if alias in self.current_directory and \
                isinstance(self.current_directory[alias], DirectoryObject):
            if not os.path.exists(self.current_directory[alias].path):
                log.warning("There is no such directory at {}".
                            format(self.current_directory[alias]))

            return self.current_directory[alias]

    def cd(self, alias):
        '''
        Switch prefix path

        @param alias: Alias of new prefix path
        @type alias: L{str}
        '''

        if self.dir(alias) is not None:
            self.prefix_path = self.dir(alias).path
            self.current_directory = self.dir(alias)
        else:
            log.info("There is no such alias '{}'".format(alias))

    def back(self):
        '''Switch prefix path to parent'''

        if self.current_directory.parent:
            self.prefix_path = self.abspath(self.current_directory.parent.path)
            self.current_directory = self.current_directory.parent

    @contextmanager
    def open(self, alias, mode="r"):
        '''Open file at relative path'''

        if self.file(alias) is not None:
            try:
                f = open(self.file(alias).path, mode)
                yield f
                f.close()
            except IOError as exc:
                log.error("Can't open file")
                raise exc

    def remove(self):
        '''CAUTION: Remove all the resources under prefix path'''

        try:
            shutil.rmtree(self.resources.path)
        except IOError as exc:
            log.error("Can't remove prefix path")
            raise exc

    def exists(self, path=""):
        '''
        Check if resource exists at relative path

        @param path: Relative path
        @type path: L{str}
        '''

        return os.path.exists(self.abspath(path))

    def abspath(self, path=""):
        '''
        Return absolute path instead of relative one

        @param path: Relative or absolute path
        @type path: L{str}
        '''
        if path.startswith("/"):
            return os.path.abspath(path)
        else:
            return os.path.abspath(os.path.join(self.prefix_path, path))

    def mkfile(self, alias=None, path=None, mode=0o600, temporary=False):
        '''
        Make the file within prefix path

        @param alias: Alias name of the file to make
        @type alias: L{str}
        @param path: Path with the file name included
        @type path: L{str}
        @param mode: Mode bits of file
        @type mode: L{int}
        '''

        if alias is None:
            _alias = self.generate_alias("file")
        else:
            _alias = alias
        if path is None:
            _path = _alias
        else:
            _path = path

        if self.resource(_alias):
            log.info("File hasn't been created. "
                     "There is already such an alias '{}'".format(_alias))
        else:
            abs_path = self.abspath(_path)
            self._prepare(abs_path)
            self.current_directory[_alias] = FileObject(abs_path, mode, temporary,
                                                self.current_directory)

    def mkdir(self, alias=None, path=None, mode=0o700, temporary=False):
        '''
        Make the directory within prefix path

        @param alias: Alias name of the directory to make
        @type alias: L{str}
        @param path: Path with the directory name included
        @type path: L{str}
        @param mode: Mode bits of directory
        @type mode: L{int}
        '''

        if alias is None:
            _alias = self.generate_alias("dir")
        else:
            _alias = alias
        if path is None:
            _path = _alias
        else:
            _path = path

        if self.resource(_alias):
            log.info("Directory hasn't been created. "
                     "There is already such an alias '{}'".format(_alias))
        else:
            abs_path = self.abspath(_path)
            self._prepare(abs_path)
            self.current_directory[_alias] = \
                AliasedDirectoryObject(abs_path, mode, temporary,
                                       self.current_directory)

    def chmod(self, alias, mode):
        '''
        Change mode bits of the resource

        @param alias: Alias name of the resource
        @type alias: L{str}
        @param mode: Mode bits of the resource
        @type mode: L{int}
        '''

        if self.resource(alias) is not None:
            self.current_directory[alias].chmod(mode)

    def rm(self, alias):
        '''
        Remove the resource

        @param alias: Alias name of the resource to remove
        @type alias: L{str}
        '''

        if self.resource(alias) is not None:
            self.current_directory[alias].remove()
            del self.current_directory[alias]

    def cp(self, alias, dst):
        '''
        Make a copy of resource

        @param alias: Alias name of the resource to copy
        @type alias: L{str}
        @param dst: Destination path with the resource name included
        @type dst: L{str}
        '''

        if self.resource(alias) is not None:
            self._prepare(self.abspath(dst))
            self.current_directory[alias].copy(self.abspath(dst))

    def mv(self, alias, dst):
        '''
        Move the resource

        @param alias: Alias name of the resource to move
        @type alias: L{str}
        @param dst: Destination path with the resource name included
        @type dst: L{str}
        '''

        if self.resource(alias) is not None:
            self._prepare(self.abspath(dst))
            self.current_directory[alias].move(self.abspath(dst))

    def ls(self):
        '''List all the resources under prefix'''

        if not self.current_directory:
            return "No one resource has been created yet"

        res = ""
        dash = " ------- "

        max_len = len(max(self.current_directory.keys(), key=len))
        max_tabs = max_len / 8
        max_tabs += 1 if max_len % 8 else 0

        for key, val in self.current_directory.iteritems():
            tabs_n = max_tabs - len(key) / 8
            tabs = "\t" * tabs_n
            type = "[File]\t\t" if isinstance(val, FileObject) \
                else "[Directory]\t"
            res += "{0}{3}{4}{2}{1}\n".format(key, val.path, dash * 5,
                                              tabs, type)
        print res

    def generate_alias(self, type):
        '''
        Generate alias

        @param type: Type of the alias (file/dir)
        @type type: L{str}
        @return: Generated alias
        '''

        x = self.alias_n[type] / len(self.default_aliases)
        idx = self.alias_n[type] - x * len(self.default_aliases)

        new_alias = self.default_aliases[idx]
        if type == "dir":
            new_alias += "Dir"
        elif type == "file":
            new_alias += "File"
        if x:
            new_alias += str(x)
        self.alias_n[type] += 1

        return new_alias


text:
package io.github.mayunfei.imdemo;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.huawei.android.pushagent.PushManager;
import com.tencent.connect.dataprovider.Constants;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConnListener;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMFriendshipSettings;
import com.tencent.imsdk.TIMGroupEventListener;
import com.tencent.imsdk.TIMGroupManager;
import com.tencent.imsdk.TIMGroupMemberInfo;
import com.tencent.imsdk.TIMGroupSettings;
import com.tencent.imsdk.TIMGroupTipsElem;
import com.tencent.imsdk.TIMLogLevel;
import com.tencent.imsdk.TIMLogListener;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMOfflinePushToken;
import com.tencent.imsdk.TIMRefreshListener;
import com.tencent.imsdk.TIMSNSChangeInfo;
import com.tencent.imsdk.TIMSdkConfig;
import com.tencent.imsdk.TIMUserConfig;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMUserStatusListener;
import com.tencent.imsdk.ext.group.TIMGroupAssistantListener;
import com.tencent.imsdk.ext.group.TIMGroupCacheInfo;
import com.tencent.imsdk.ext.group.TIMUserConfigGroupExt;
import com.tencent.imsdk.ext.message.TIMUserConfigMsgExt;
import com.tencent.imsdk.ext.sns.TIMFriendGroup;
import com.tencent.imsdk.ext.sns.TIMFriendshipProxyListener;
import com.tencent.imsdk.ext.sns.TIMUserConfigSnsExt;
import com.tencent.imsdk.ext.ugc.IMUGCUploadListener;
import com.tencent.qcloud.presentation.business.InitBusiness;
import com.tencent.qcloud.presentation.business.LoginBusiness;
import com.tencent.qcloud.presentation.event.FriendshipEvent;
import com.tencent.qcloud.presentation.event.GroupEvent;
import com.tencent.qcloud.presentation.event.MessageEvent;
import com.tencent.qcloud.presentation.event.RefreshEvent;
import com.tencent.qcloud.tlslibrary.activity.ImgCodeActivity;
import com.tencent.qcloud.tlslibrary.service.TLSService;
import com.tencent.qcloud.tlslibrary.service.TlsBusiness;
import com.xiaomi.mipush.sdk.MiPushClient;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

import modle.UserInfo;
import tencent.tls.platform.TLSErrInfo;
import tencent.tls.platform.TLSPwdLoginListener;
import tencent.tls.platform.TLSUserInfo;

public class MainActivity extends AppCompatActivity implements TLSPwdLoginListener, TIMCallBack {

    private static final String TAG = "MainActivity";
    private String tag = "888 ";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
    }

    private void login() {

//        String id = TLSService.getInstance().getLastUserIdentifier();
//        UserInfo.getInstance().setId(id);
//        UserInfo.getInstance().setUserSig(TLSService.getInstance().getUserSig(id));
//        if (isUserLogin()) {
            //已经登录
            navToHome();
//        } else {
//            TLSService.getInstance().TLSPwdLogin("yunfei9959", "yunfei123", this);
//        }
    }

    public boolean isUserLogin() {
        return UserInfo.getInstance().getId() != null && (!TLSService.getInstance().needLogin(UserInfo.getInstance().getId()));
    }

    @Override
    public void OnPwdLoginSuccess(TLSUserInfo tlsUserInfo) {
        Log.i(TAG, "登录成功 " );
        TLSService.getInstance().setLastErrno(0);
        navToHome();
    }

    @Override
    public void OnPwdLoginReaskImgcodeSuccess(byte[] bytes) {

        ImgCodeActivity.fillImageview(bytes);
    }

    @Override
    public void OnPwdLoginNeedImgcode(byte[] bytes, TLSErrInfo tlsErrInfo) {
        Log.i(TAG,"OnPwdLoginNeedImgcode " + tlsErrInfo.Msg);
    }

    @Override
    public void OnPwdLoginFail(TLSErrInfo tlsErrInfo) {
        Log.i(TAG, "登录失败 " + tlsErrInfo.Msg);
    }

    @Override
    public void OnPwdLoginTimeout(TLSErrInfo tlsErrInfo) {
        Log.i(TAG, "登录失败 超时 " + tlsErrInfo.ExtraMsg + " "+tlsErrInfo.describeContents()+ " " + tlsErrInfo.Msg + " " +tlsErrInfo.Title );
    }

    public void navToHome() {
        //登录之前要初始化群和好友关系链缓存
        TIMUserConfig userConfig = new TIMUserConfig();
        userConfig.setUserStatusListener(new TIMUserStatusListener() {
            @Override
            public void onForceOffline() {
                Log.d(TAG, "receive force offline message");
//                Intent intent = new Intent(SplashActivity.this, DialogActivity.class);
//                startActivity(intent);
            }

            @Override
            public void onUserSigExpired() {
                Log.d(TAG, "onUserSigExpired");
                //票据过期,需要重新登录
//                new NotifyDialog().show(getString(R.string.tls_expire), getSupportFragmentManager(), new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
////                            logout();
//                    }
//                });
            }
        })
                .setConnectionListener(new TIMConnListener() {
                    @Override
                    public void onConnected() {
                        Log.i(TAG, "onConnected");
                    }

                    @Override
                    public void onDisconnected(int code, String desc) {
                        Log.i(TAG, "onDisconnected");
                    }

                    @Override
                    public void onWifiNeedAuth(String name) {
                        Log.i(TAG, "onWifiNeedAuth");
                    }
                });

        //设置刷新监听
        RefreshEvent.getInstance().init(userConfig);
        userConfig = FriendshipEvent.getInstance().init(userConfig);
        userConfig = GroupEvent.getInstance().init(userConfig);
        userConfig = MessageEvent.getInstance().init(userConfig);
        TIMManager.getInstance().setUserConfig(userConfig);
        LoginBusiness.loginIm("yunfei", "eJxlj9FOgzAUhu95iqa3GteWVZjJLnSZGbhdaBmJVw3SwspGKVDcmPHdVVwiief2*-7zn-PhAABgtGY3SZpWnbbc9kZCcAcggtd-0BgleGK524h-UJ6MaiRPMiubAWJKKUFo7CghtVWZuhh9pzOpRrwVez6U-C6YfqeniGAyVlQ*wM3yeREsvGz70vmhCE5F2XpeMXsi8RsL2aHK7S4oRHRbd-423k8e79XDTkSVrN10VWu5pMkmOpij9svVmvb4HIeznCHm48lV-Hqcz0eVVpXy8hGixMM*GR-0LptWVXoQCMIUExf9DHQ*nS-ISV2d", this);
//        LoginBusiness.loginIm("gongao", "eJxlj11PgzAYhe-5FQ3XxrWldamJF7hCZJHh1DnnTcNHwTIsBIoyjf9dxSWSeG6f531PzocFALDvr*9O4zSte22EOTTSBufAhvbJH2walYnYCKfN-kE5NKqVIs6NbEeIKKUYwqmjMqmNytXRKGpdxPWEd9lejCW-D8j3NYEY4amiihGG3mYR*H656B58vuvPeBSxFWRpTKKt7q*WlcdLPPj0nc5W0T50XeW55eOQ7LzuRgUs2IakWq7hzKlCA59yeblOEv7MNodbjQ1-u5hUGvUij4sgxXPEyHxCX2XbqVqPAoaIIuzAn9jWp-UFDARcdw__", this);
    }

    /**
     * TODO
     * imsdk登录失败后回调
     */
    @Override
    public void onError(int i, String s) {
        Log.e("错误",s);
    }

    @Override
    public void onSuccess() {
//初始化程序后台后消息推送
//        PushUtil.getInstance();
        //初始化消息监听
        MessageEvent.getInstance();
//        String deviceMan = android.os.Build.MANUFACTURER;
        //注册小米和华为推送
//        if (deviceMan.equals("Xiaomi") && shouldMiInit()){
//            MiPushClient.registerPush(getApplicationContext(), "2882303761517480335", "5411748055335");
//        }else if (deviceMan.equals("HUAWEI")){
//            PushManager.requestToken(this);
//        }

//        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//        Log.d(TAG, "refreshed token: " + refreshedToken);
//
//        if(!TextUtils.isEmpty(refreshedToken)) {
//            TIMOfflinePushToken param = new TIMOfflinePushToken(169, refreshedToken);
//            TIMManager.getInstance().setOfflinePushToken(param, null);
//        }
//        MiPushClient.clearNotification(getApplicationContext());
//        TIMGroupManager.CreateGroupParam groupParam = new TIMGroupManager.CreateGroupParam("ChatRoom","扯淡用");
//        TIMGroupManager.getInstance().createGroup(groupParam, new IMUGCUploadListener<String>() {
//            @Override
//            public void onProgress(int i, long l, long l1) {
//
//            }
//
//            @Override
//            public void onError(int i, String s) {
//            Log.e(TAG,s);
//            }
//
//            @Override
//            public void onSuccess(String s) {
//                Log.e(TAG,s);
//            }
//        });

        Intent intent = new Intent(this, ChatRoomActivity.class);
        startActivity(intent);
        finish();

        //TODO 获取公共群ID
    }
}


text:
require 'test_helper'

class PrecioproductosHelperTest < ActionView::TestCase
end