text:
Every ByteScout tool includes simple example C# source codes that you can get here or in the folder with installed ByteScout product. ByteScout PDF Suite can add file attachment annotation in pdf with pdf sdk. It can be applied from C#. ByteScout PDF Suite is the set that includes 6 SDK products to work with PDF from generating rich PDF reports to extracting data from PDF documents and converting them to HTML. This bundle includes PDF (Generator) SDK, PDF Renderer SDK, PDF Extractor SDK, PDF to HTML SDK, PDF Viewer SDK and PDF Generator SDK for Javascript.

This prolific sample source code in C# for ByteScout PDF Suite contains various functions and other necessary options you should do calling the API to add file attachment annotation in pdf with pdf sdk. Just copy and paste the code into your C# application's code and follow the instructions. Applying C# application mostly includes various stages of the software development so even if the functionality works please test it with your data and the production environment.

Our website gives trial version of ByteScout PDF Suite for free. It also includes documentation and source code samples.

## REQUEST FREE TECH SUPPORT

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

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20PDF%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 -->

##### ****FileAttachmentAnnotation.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" />
    <None Include="sample_attachment.txt">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </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 -->

##### ****FileAttachmentAnnotation.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>FileAttachmentAnnotationExample</RootNamespace>
    <AssemblyName>FileAttachmentAnnotationExample</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>
  <ItemGroup>
    <Content Include="sample_attachment.txt">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </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 -->

##### ****FileAttachmentAnnotation.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>FileAttachmentAnnotationExample</RootNamespace>
    <AssemblyName>FileAttachmentAnnotationExample</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>
  <ItemGroup>
    <Content Include="sample_attachment.txt">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </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 -->

##### ****FileAttachmentAnnotation.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>FileAttachmentAnnotationExample</RootNamespace>
    <AssemblyName>FileAttachmentAnnotationExample</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>
  <ItemGroup>
    <Content Include="sample_attachment.txt">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </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 -->

##### ****FileAttachmentAnnotation.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>FileAttachmentAnnotationExample</RootNamespace>
    <AssemblyName>FileAttachmentAnnotationExample</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>
  <ItemGroup>
    <Content Include="sample_attachment.txt">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </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 -->

##### ****FileAttachmentAnnotation.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>FileAttachmentAnnotationExample</RootNamespace>
    <AssemblyName>FileAttachmentAnnotationExample</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>
  <ItemGroup>
    <Content Include="sample_attachment.txt">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </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 -->

##### ****FileAttachmentAnnotation.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>FileAttachmentAnnotationExample</RootNamespace>
    <AssemblyName>FileAttachmentAnnotationExample</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>
  <ItemGroup>
    <Content Include="sample_attachment.txt">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </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.Diagnostics;
using Bytescout.PDF;

namespace FileAttachmentAnnotationExample
{
    /// <summary>
    /// This example demonstrates how to attach a file to PDF document.
    /// </summary>
    class Program
    {
        static void Main()
        {
            // Create new document
            Document pdfDocument = new Document();
            pdfDocument.RegistrationName = "demo";
            pdfDocument.RegistrationKey = "demo";
            // Add page
            Page page = new Page(PaperFormat.A4);
            pdfDocument.Pages.Add(page);

            // Attach file
            FileAttachmentAnnotation fileAttachment = new FileAttachmentAnnotation("sample_attachment.txt", 20, 20, 20, 20);
            fileAttachment.Icon = FileAttachmentAnnotationIcon.Paperclip;
            page.Annotations.Add(fileAttachment);

            // Instruct PDF viewer application to show attachments pane on startup
            pdfDocument.PageMode = PageMode.Attachment;

            // 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 -->

<!-- code block begin -->

##### ****sample_attachment.txt:**

```
sample_attachment.txt

1234567890
abcdefghijklmnopqrstuvwxyz
```

<!-- code block end -->


text:
package scala.xml

import org.junit.Test
import org.junit.Assert.assertEquals

class NodeBufferTest {

  @Test
  def testToString: Unit = {
    val nodeBuffer = new NodeBuffer
    assertEquals("NodeBuffer()", nodeBuffer.toString)
  }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2022 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.skyframe;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.devtools.build.lib.actions.PackageRoots;
import com.google.devtools.build.lib.buildtool.SymlinkForest;
import com.google.devtools.build.lib.cmdline.PackageIdentifier;
import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.server.FailureDetails;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.skyframe.TopLevelStatusEvents.AspectAnalyzedEvent;
import com.google.devtools.build.lib.skyframe.TopLevelStatusEvents.TopLevelTargetAnalyzedEvent;
import com.google.devtools.build.lib.util.AbruptExitException;
import com.google.devtools.build.lib.util.DetailedExitCode;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.Root;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

/**
 * An implementation of PackageRoots that allows incremental updating of the packageRootsMap.
 *
 * <p>This class is also in charge of planting the necessary symlinks.
 */
public class IncrementalPackageRoots implements PackageRoots {

  // We only keep track of PackageIdentifier from external repos here as a memory optimization:
  // packages belong to the main repository all share the same root, which is singleSourceRoot.
  private final Map<PackageIdentifier, Root> threadSafeExternalRepoPackageRootsMap;
  // Top level events originate from within Skyframe, so duplications are expected.
  private final Set<Object> handledTopLevelEvents = Sets.newConcurrentHashSet();
  private final Set<Path> plantedExternalRepoLinks = Sets.newConcurrentHashSet();
  private final Path execroot;
  private final Root singleSourceRoot;
  private final EventBus eventBus;
  private final String prefix;
  private final boolean useSiblingRepositoryLayout;

  private IncrementalPackageRoots(
      Path execroot,
      Root singleSourceRoot,
      EventBus eventBus,
      String prefix,
      boolean useSiblingRepositoryLayout) {
    this.threadSafeExternalRepoPackageRootsMap = Maps.newConcurrentMap();
    this.execroot = execroot;
    this.singleSourceRoot = singleSourceRoot;
    this.prefix = prefix;
    this.eventBus = eventBus;
    this.useSiblingRepositoryLayout = useSiblingRepositoryLayout;
  }

  public static IncrementalPackageRoots createAndRegisterToEventBus(
      Path execroot,
      Root singleSourceRoot,
      EventBus eventBus,
      String prefix,
      boolean useSiblingRepositoryLayout) {
    IncrementalPackageRoots incrementalPackageRoots =
        new IncrementalPackageRoots(
            execroot, singleSourceRoot, eventBus, prefix, useSiblingRepositoryLayout);
    eventBus.register(incrementalPackageRoots);
    return incrementalPackageRoots;
  }

  /** Eagerly plant the symlinks to the directories under the single source root. */
  public void eagerlyPlantSymlinksToSingleSourceRoot() throws AbruptExitException {
    try {
      SymlinkForest.eagerlyPlantSymlinkForestSinglePackagePath(
          execroot, singleSourceRoot.asPath(), prefix, useSiblingRepositoryLayout);
    } catch (IOException e) {
      throwAbruptExitException(e);
    }
  }

  /** There is currently no use case for this method, and it should not be called. */
  @Override
  public Optional<ImmutableMap<PackageIdentifier, Root>> getPackageRootsMap() {
    throw new UnsupportedOperationException(
        "IncrementalPackageRoots does not provide the package roots map directly.");
  }

  @Override
  public PackageRootLookup getPackageRootLookup() {
    return packageId ->
        packageId.getRepository().isMain()
            ? singleSourceRoot
            : threadSafeExternalRepoPackageRootsMap.get(packageId);
  }

  @AllowConcurrentEvents
  @Subscribe
  public void addTargetPackage(TopLevelTargetAnalyzedEvent event) throws AbruptExitException {
    if (handledTopLevelEvents.add(event)) {
      registerAndPlantSymlinksForExternalPackages(
          event.transitivePackagesForSymlinkPlanting().toList());
    }
  }

  @AllowConcurrentEvents
  @Subscribe
  public void addAspectPackage(AspectAnalyzedEvent event) throws AbruptExitException {
    if (handledTopLevelEvents.add(event)) {
      registerAndPlantSymlinksForExternalPackages(
          event.transitivePackagesForSymlinkPlanting().toList());
    }
  }

  private void registerAndPlantSymlinksForExternalPackages(Iterable<Package> packages)
      throws AbruptExitException {
    for (Package pkg : packages) {
      PackageIdentifier pkgId = pkg.getPackageIdentifier();
      if (isExternalRepository(pkgId) && pkg.getSourceRoot().isPresent()) {
        threadSafeExternalRepoPackageRootsMap.put(
            pkg.getPackageIdentifier(), pkg.getSourceRoot().get());
        try {
          SymlinkForest.plantSingleSymlinkForExternalRepo(
              pkgId.getRepository(),
              pkg.getSourceRoot().get().asPath(),
              execroot,
              useSiblingRepositoryLayout,
              plantedExternalRepoLinks);
        } catch (IOException e) {
          throwAbruptExitException(e);
        }
      }
    }
  }

  private static void throwAbruptExitException(IOException e) throws AbruptExitException {
    throw new AbruptExitException(
        DetailedExitCode.of(
            FailureDetail.newBuilder()
                .setMessage("Failed to prepare the symlink forest")
                .setSymlinkForest(
                    FailureDetails.SymlinkForest.newBuilder()
                        .setCode(FailureDetails.SymlinkForest.Code.CREATION_FAILED))
                .build()),
        e);
  }

  private static boolean isExternalRepository(PackageIdentifier pkgId) {
    return !pkgId.getRepository().isMain();
  }

  public void shutdown() {
    eventBus.unregister(this);
  }
}


text:
package models

import play.api._

import play.api.mvc._

import scala.concurrent.Await
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.duration._
import scala.language.postfixOps
import scala.concurrent.Future

// Reactive Mongo imports
import reactivemongo.api._

// Reactive Mongo plugin
import play.modules.reactivemongo._
import play.modules.reactivemongo.json.collection.JSONCollection

// Play Json imports
import play.api.libs.json._

import play.api.Play.current

import play.api.libs.iteratee._
import play.api.libs.EventSource

import models.Attributes._

object DataStore extends Controller with MongoController {

	val all: JsObject = new JsObject(Seq.empty)

	def attrIDColl: JSONCollection = db.collection[JSONCollection]("AttributeIDList")

	def attrIDList = attrIDColl.find(all).cursor[AttrID].toList

//	def behavIDList = attrIDColl.find(Json.obj("typ" -> "beh")).cursor[AttrID].toList

	def binAttrIDList = attrIDColl.find(Json.obj("typ" -> "bin")).cursor[AttrID].toList

	def strAttrIDList = attrIDColl.find(Json.obj("typ" -> "str")).cursor[AttrID].toList

	def insertAttrID(attr: AttrID) = attrIDColl.insert(attr)

	def speciesDescColl: JSONCollection = db.collection[JSONCollection]("SpeciesDescription")

	def speciesDescList = speciesDescColl.find(all).cursor[SpeciesDesc].toList

	def insertSpecies(desc: SpeciesDesc) = speciesDescColl.insert(desc)

	def stringAttrDataColl: JSONCollection = db.collection[JSONCollection]("StringAttributesData")

	def stringAttrDataList = stringAttrDataColl.find(all).cursor[StringAttrData].toList

	def StringAttrFut(id: AttrID) = stringAttrDataColl.find(Json.obj("id" ->id.toJson)).
																	cursor[StringAttrData].
																	headOption map (_.get.attr)
	implicit val timeout = Timeout(25 seconds)

	def StringAttrNow(id: AttrID) = Await.result(StringAttrFut(id), timeout.duration)

//	implicit val strLookUp = StrLookup(StringAttrNow)

	def weightSystemColl: JSONCollection = db.collection[JSONCollection]("WeightSystem")

	def weightSystemList = weightSystemColl.find(all).cursor[WeightSystem].toList

	def weightMap(ref: String) = weightSystemColl.find(Json.obj("ref" -> Json.toJson(ref))).
																	cursor[WeightSystem].toList.map(_.head).map(_.weights)

	def abundanceDataColl: JSONCollection = db.collection[JSONCollection]("AbundanceData")

	def abundanceDataList = abundanceDataColl.find(all).cursor[AbundanceData].toList

	def abundanceDataNow = Await.result(abundanceDataList, timeout.duration)

//	def abundanceJsonList = Json.toJson(Await.result(abundanceDataColl.find(all).cursor[JsValue].toList, timeout.duration))

	def abundanceJsonList = abundanceDataColl.find(all).cursor[JsValue].toList map ((l: List[JsValue] ) => Json.toJson(l))

	def abundanceMap(ref: String) = abundanceDataColl.find(Json.obj("ref" -> Json.toJson(ref))).
																	cursor[AbundanceData].toList.map(_.head).map(_.abundance)

	def abundanceInsert(abDat: AbundanceData) = abundanceDataColl.insert(abDat)

	// val brdRace = models.BirdRace.Bangalore2011.upload

	def wikiDataColl: JSONCollection = db.collection[JSONCollection]("WikiData")

	def wikiDataBirds = wikiDataColl.find(all).cursor[JsObject].toList.map (Json.toJson(_))

	def WikiFut = Future({println(WikiRead.birdsJson); WikiRead.birdsJson})

	def wikiUpload = WikiFut flatMap ((birds: List[JsObject]) =>
	  			Future.sequence(birds.map((bird: JsObject) => wikiDataColl.insert(bird))))

	def birdDescColl: JSONCollection = db.collection[JSONCollection]("BirdDescriptions")

    def addDesc(desc: JsObject) = {
	  birdDescColl.find(desc).cursor[JsObject].toList.map{(l)=>
	    if (l.isEmpty) birdDescColl.insert(desc)}
//	  birdDescColl.insert(desc)
	}

	def saveDesc(desc: JsObject) = {
	  birdDescColl.save(desc)
	  channel.push(desc)
	  println("boing")
	}

	def removDesc(id: JsObject) = birdDescColl.remove(id)

    def birdDescs = birdDescColl.find(all).cursor[JsObject].toList.map(Json.toJson(_))

    val (boingout, channel) = Concurrent.broadcast[JsValue]
}


text:
package hmi.graphics.collada;

import hmi.xml.XMLFormatting;
import hmi.xml.XMLTokenizer;

import java.io.IOException;
import java.util.StringTokenizer;

/**
 * Vertex-Weight bounds.
 * @author Job Zwiers
 */
public class V extends ColladaElement {

   //private static final int NR_OF_INTS_PER_LINE = 16;

   private int[] indices;
   //public float[] weights;
   private static final int NR_OF_INDICES_PER_LINE = 20;

   public V() {
      super();
   }

   public V(Collada collada, XMLTokenizer tokenizer) throws IOException {
      super(collada);
      readXML(tokenizer);
   }

//   /**
//    * returns indices    array
//    */
//   public int[] getIndices() {
//      return indices;
//   }

   /**
    * Returns indices[i]
    */
   public int getIndex(int i) {
      return indices[i];
   }

   /**
    * return number of indices
    */
   public int getNrIndices() {
      return indices.length;
   }

   @Override
   public StringBuilder appendContent(StringBuilder buf, XMLFormatting fmt) {
    appendNewLine(buf, fmt);
    if (indices == null || indices.length == 0) return buf;
      int tabCounter = NR_OF_INDICES_PER_LINE;
      buf.append(indices[0]);tabCounter--;
      for (int i=1; i<indices.length; i++) {
         if (tabCounter == 0) {
            buf.append('\n');
            appendSpaces(buf, fmt);
            tabCounter = NR_OF_INDICES_PER_LINE;
         }
         buf.append(' '); buf.append(indices[i]);
         tabCounter--;
      }
      return buf;
   }

   @Override
   public void decodeContent(XMLTokenizer tokenizer) throws IOException {
      String vertexWeightPairs = tokenizer.takeCharData();
      StringTokenizer strTokenizer = new StringTokenizer(vertexWeightPairs, " \t\n\r\f");
      int nrOfTokens = strTokenizer.countTokens();
      if (nrOfTokens%2 != 0) {
         getCollada().warning("Vertex_weights/V with odd number of elements");
          //throw new RuntimeException("Collada V element with odd number of elements");
      }
     // int nrOfPairs = nrOfTokens/2;
      indices = new int[nrOfTokens];
      //weights = new float[nrOfPairs];
      for (int i=0; i<nrOfTokens; i++) {
         indices[i] = Integer.parseInt(strTokenizer.nextToken());
      }
//      int pt = 0;
//      while (strTokenizer.hasMoreTokens() ) {
//         indices[pt] = Integer.parseInt(strTokenizer.nextToken());
//         weights[pt++] = Float.parseFloat(strTokenizer.nextToken());
//      }
   }

   /*
    * The XML Stag for XML encoding
    */
   private static final String XMLTAG = "v";

   /**
    * The XML Stag for XML encoding
    */
   public static String xmlTag() { return XMLTAG; }

   /**
    * returns the XML Stag for XML encoding
    */
   @Override
   public String getXMLTag() {
      return XMLTAG;
   }

}


text:
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
module KMC.Theories where

import           Control.Applicative
import           Data.Monoid

import           KMC.RangeSet (RangeSet)
import qualified KMC.RangeSet as RS

-- Silence unused import warnings on migration to base>=4.8
import           Prelude

{----------------------------------------------------------------------}
{- Boolean algebras                                                   -}
{----------------------------------------------------------------------}

class Boolean b where
  top :: b
  bot :: b
  neg :: b -> b
  conj :: b -> b -> b
  disj :: b -> b -> b

  minus :: b -> b -> b
  minus b1 b2 = b1 `conj` neg b2

-- | An effective Boolean algebra is a Boolean algebra whose elements can be
-- interpreted as predicates on some domain.
class SetLike b dom | b -> dom where
  member :: dom -> b -> Bool

-- | An effective Boolean algebra over lists is uniform if every set
-- interpretation contains lists of equal length
class SetLike b [a] => UniformListSet b a | b -> a where
  -- | Get the uniform list length of all members of the set interpretation of
  -- the given element
  listLength :: b -> Int

-- | An Enumerable is a set-like boolean algebra for which we can enumerate all
-- members by consecutive non-negative integers.
class SetLike b dom => Enumerable b dom | b -> dom where
  indexOf :: dom -> b -> Int
  lookupIndex :: Int -> b -> dom
  size :: b -> Int

-- | Compute the coarsest partitioning of a list of elements of a decidable boolean algebra.
--   For a subset S of a boolean algebra, another subset P is a partition of S iff
--   (i) for all a, b in P, if a /= b, then a /\ b = 0
--   (ii) For all b in S, there are p_1, ..., p_m in P such that b = p_1 \/ ... \/ p_m
--
-- If P,Q are partitions of a subset S, then Q is coarser than P if P is a partition of Q.
-- TODO: Prove that the greedy approach employed in the algorithm below is actually correct.
coarsestPartition :: (Boolean b, PartialOrder b) => [b] -> [b]
coarsestPartition elems =
  case findOverlap elems of
    Just (x, y, elems') ->
      let xy' = x `minus` y
          yx' = y `minus` x
          i   = x `conj` y
          f p = if p `eq` bot then [] else [p]
       in
      coarsestPartition (f xy' ++ f yx' ++ f i ++ elems')
    Nothing -> elems
  where
    findOverlapWith _ [] = Nothing
    findOverlapWith b (x:xs)
      | not ((b `conj` x) `eq` bot) = Just (x, xs)
      | Just (y, xs') <- findOverlapWith b xs = Just (y, x:xs')
      | otherwise = Nothing

    findOverlap [] = Nothing
    findOverlap (x:xs)
      | Just (y, xs') <- findOverlapWith x xs = Just (x, y, xs')
      | Just (x', y, xs') <- findOverlap xs = Just (x', y, x:xs')
      | otherwise = Nothing

{----------------------------------------------------------------------}
{- Functions, terms                                                   -}
{----------------------------------------------------------------------}

class Function t where
  type Dom t :: *
  type Rng t :: *
  eval    :: t -> Dom t -> Rng t
  isConst :: t -> Maybe (Rng t)
  inDom   :: Dom t -> t -> Bool
  domain  :: t -> [Dom t]

-- | Monoidal functions:
--     (i)   are functions between monoids
--     (ii)  have a monoid structure
--     (iii) are compatible with the monoid structure. f(x)g(y) = (fg)(xy)
class (Monoid t, Monoid (Dom t), Monoid (Rng t), Function t) => MonFunction t where

{----------------------------------------------------------------------}
{- Partial orders                                                     -}
{----------------------------------------------------------------------}

class PartialOrder a where
  lte :: a -> a -> Bool

  comparable :: a -> a -> Bool
  comparable x y = (x `lte` y) || (y `lte` x)

  gte :: a -> a -> Bool
  gte = flip lte

  lt :: a -> a -> Bool
  lt x y = lte x y && not (eq x y)

  gt :: a -> a -> Bool
  gt = flip lt

  eq :: a -> a -> Bool
  eq x y = lte x y && lte y x

{----------------------------------------------------------------------}
{- Various nice shorthands.                                           -}
{----------------------------------------------------------------------}

-- | Convenience class: a predicate must always be an instance of `Ord`,
-- `Boolean`, and `PartialOrder`.
class (Ord pred, Boolean pred, PartialOrder pred) => Predicate pred where

class (Ord var, Show var, Eq var) => Variable var where

-- Finite alphabet
class (Ord delta, Show delta, Eq delta, Enum delta, Bounded delta) => Alphabet delta where

{----------------------------------------------------------------------}
{- Function combinators                                               -}
{----------------------------------------------------------------------}
-- | Adjoins a new epsilon element to a set of monoid-valued functions
data EpsFunc f = JustFunc f | EpsFunc deriving (Eq, Ord)

instance (Function t, Enum (Dom t), Bounded (Dom t), Monoid (Rng t))
         => Function (EpsFunc t) where
  type Dom (EpsFunc t) = Dom t
  type Rng (EpsFunc t) = Rng t
  eval EpsFunc _ = mempty
  eval (JustFunc f) x = eval f x
  isConst EpsFunc = Just mempty
  isConst (JustFunc f) = isConst f
  inDom _ EpsFunc = True
  inDom x (JustFunc f) = inDom x f
  domain EpsFunc = [minBound .. maxBound]
  domain (JustFunc f) = domain f

{----------------------------------------------------------------------}
{- Instances                                                          -}
{----------------------------------------------------------------------}

-- | A list of functions into a monoid forms a function from a list of domain
-- elements into the same monoid.
instance (Function t, Monoid (Rng t)) => Function [t] where
  type Dom [t] = [Dom t]
  type Rng [t] = Rng t
  eval []     []     = mempty
  eval (f:fs) (x:xs) = eval f x `mappend` eval fs xs
  eval _      _      = error "arity mismatch"

  isConst fs = mconcat <$> mapM isConst fs
  inDom xs fs = all id $ zipWith inDom xs fs
  domain [] = [[]]
  domain (f:fs) = do
    a <- domain f
    as <- domain fs
    return $ a:as

instance (Function t, Monoid (Rng t)) => MonFunction [t]

instance (Ord a, Enum a, Bounded a) => Boolean (RangeSet a) where
  top  = RS.universe
  bot  = RS.empty
  neg  = RS.complement
  conj = RS.intersection
  disj = RS.union

instance (Ord a) => SetLike (RangeSet a) a where
  member = RS.member

instance (Ord a, Enum a) => Enumerable (RangeSet a) a where
  indexOf = RS.indexOf
  lookupIndex = RS.lookupIndex
  size = RS.size

instance (Ord a) => PartialOrder (RangeSet a) where
    lte = RS.isSubsetOf
    eq = (==)

instance (Boolean a, Boolean b) => Boolean (a, b) where
    top = (top, top)
    bot = (bot, bot)
    neg (x, y) = (neg x, neg y)
    conj (x, y) (x', y') = (x `conj` x', y `conj` y')
    disj (x, y) (x', y') = (x `disj` x', y `disj` y')

instance (SetLike a doma, SetLike b domb) => SetLike (a, b) (doma, domb) where
    member (x, y) (l, r) = (x `member` l) && (y `member` r)

instance (PartialOrder a, PartialOrder b) => PartialOrder (a, b) where
    lte (x, y) (x', y') = (x `lte` x') && (y `lte` y')

instance (Ord a, Enum a, Bounded a) => Predicate (RangeSet a) where

data Prefix a = Prefix [a] deriving (Eq, Ord, Show)

instance (Eq a) => PartialOrder (Prefix a) where
    eq = (==)
    lte (Prefix xs) (Prefix ys) = prefixOf xs ys
        where
          prefixOf [] _ = True
          prefixOf (x:l) (y:r) = (x == y) && prefixOf l r
          prefixOf _ _ = False


text:
#include <aws/forecast/model/ScalingType.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace ForecastService
  {
    namespace Model
    {
      namespace ScalingTypeMapper
      {

        static const int Auto_HASH = HashingUtils::HashString("Auto");
        static const int Linear_HASH = HashingUtils::HashString("Linear");
        static const int Logarithmic_HASH = HashingUtils::HashString("Logarithmic");
        static const int ReverseLogarithmic_HASH = HashingUtils::HashString("ReverseLogarithmic");

        ScalingType GetScalingTypeForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == Auto_HASH)
          {
            return ScalingType::Auto;
          }
          else if (hashCode == Linear_HASH)
          {
            return ScalingType::Linear;
          }
          else if (hashCode == Logarithmic_HASH)
          {
            return ScalingType::Logarithmic;
          }
          else if (hashCode == ReverseLogarithmic_HASH)
          {
            return ScalingType::ReverseLogarithmic;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<ScalingType>(hashCode);
          }

          return ScalingType::NOT_SET;
        }

        Aws::String GetNameForScalingType(ScalingType enumValue)
        {
          switch(enumValue)
          {
          case ScalingType::Auto:
            return "Auto";
          case ScalingType::Linear:
            return "Linear";
          case ScalingType::Logarithmic:
            return "Logarithmic";
          case ScalingType::ReverseLogarithmic:
            return "ReverseLogarithmic";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace ScalingTypeMapper
    } // namespace Model
  } // namespace ForecastService
} // namespace Aws


text:
package me.infuzion.chat.server;

import me.infuzion.chat.server.api.IChatClient;
import me.infuzion.chat.server.api.IChatRoom;
import me.infuzion.chat.server.api.IChatRoomManager;

import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("WeakerAccess")
public class ChatRoomManager implements IChatRoomManager {
    private final List<IChatRoom> IChatRooms = new ArrayList<>();

    public ChatRoomManager() {
        IChatRooms.add(new ChatRoom("default"));
        ChatRoom.setChatRoomManager(this);
    }

    @Override
    public void addChatRoom(IChatRoom IChatRoom) {
        IChatRooms.add(IChatRoom);
    }

    @Override
    public void addClient(IChatClient client) {
        addClient(client, IChatRooms.get(0));

    }

    @Override
    public void addClient(IChatClient client, IChatRoom room) {
        room.addClient(client);
        client.setChatRoom(room);
        if (!IChatRooms.contains(room)) {
            IChatRooms.add(room);
        }
    }

    @Override
    public void addClient(IChatClient client, String roomName) {
        IChatRoom IChatRoom = fromString(roomName);
        if (IChatRoom != null) {
            addClient(client, IChatRoom);
        }
    }

    @Override
    public IChatRoom fromString(String string) {
        for (IChatRoom e : IChatRooms) {
            if (e.getName().equalsIgnoreCase(string)) {
                return e;
            }
        }
        return null;
    }

    @Override
    public void sendMessageAll(String message, IChatClient client) {
        for (IChatRoom e : IChatRooms) {
            sendMessageAll(message, client, e);
        }
    }

    @Override
    public void sendMessageAll(String message, IChatClient client, IChatRoom IChatRoom) {
        IChatRoom.sendMessage(message, client);
    }

    @Override
    public void moveClient(IChatClient client, IChatRoom newRoom) {
        removeClient(client);
        addClient(client, newRoom);
    }

    @Override
    public void removeClient(IChatClient IChatClient) {
        IChatRooms.stream().filter(e -> e.getClients().contains(IChatClient)).forEach(e -> e.removeClient(IChatClient));
    }

    @Override
    public void kickClient(IChatClient IChatClient, String message) {
        removeClient(IChatClient);
        IChatClient.kick(message);
    }

    @Override
    public void kickClient(IChatClient IChatClient) {
        kickClient(IChatClient, "an unspecified reason.");
    }

    @Override
    public IChatRoom createChatRoom(String name) {
        ChatRoom r = new ChatRoom(name);
        addChatRoom(r);
        return r;
    }

    @Override
    public List<IChatRoom> getChatRooms() {
        return IChatRooms;
    }
}


text:
require "spec_helper"

describe Ibandit::Constants do
  Ibandit::Constants::PSEUDO_IBAN_COUNTRY_CODES.each do |country_code|
    context country_code do
      it "has padding character" do
        padding =
          Ibandit::Constants::PSEUDO_IBAN_PADDING_CHARACTER_FOR[country_code]
        expect(padding).to_not be_nil
        expect(padding.length).to eq(1)
      end
    end
  end
end


text:
package io.divide.client.web;

import rx.Observer;

public abstract class ConnectionListener {

    public abstract void onEvent(boolean connected);

    protected Observer<Boolean> getObserver(){ return connectionObserver; }

    private Observer<Boolean> connectionObserver = new Observer<Boolean>() {

        @Override public void onCompleted() { }

        @Override public void onError(Throwable throwable) { }

        @Override
        public void onNext(Boolean aBoolean) {
            onEvent(aBoolean);
        }
    };

}


text:
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';

export default createSvgIcon(
  <React.Fragment><path fillOpacity=".3" d="M22 8V2L2 22h16V8h4z" /><path d="M20 10v8h2v-8h-2zm-8 12V12L2 22h10zm8 0h2v-2h-2v2z" /></React.Fragment>
, 'SignalCellularConnectedNoInternet1BarOutlined');


text:
//---------------------------------------------------------------------
// <copyright file="OperationReaderAtomTests.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.Taupo.OData.Reader.Tests.Atom
{
    #region Namespaces
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Microsoft.OData.Core;
    using Microsoft.Test.Taupo.Astoria.Contracts.OData;
    using Microsoft.Test.Taupo.Common;
    using Microsoft.Test.Taupo.Execution;
    using Microsoft.Test.Taupo.OData.Common;
    using Microsoft.Test.Taupo.OData.Reader.Tests;
    using Microsoft.Test.Taupo.OData.Reader.Tests.Common;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    #endregion Namespaces

    /// <summary>
    /// Tests reading of m:action and m:function in ATOM.
    /// </summary>
    [TestClass, TestCase]
    public class OperationReaderAtomTests : ODataReaderTestCase
    {
        [InjectDependency]
        public PayloadReaderTestDescriptor.Settings Settings { get; set; }

        [TestMethod, TestCategory("Reader.Atom"), Variation(Description = "Verifies correct reading of m:action and m:function without metadata.")]
        public void ODataOperationReadTest()
        {
            EntityInstance entryWithOperations = PayloadBuilder.Entity();
            entryWithOperations.Add(new ServiceOperationDescriptor { IsAction = true, Metadata = "http://odata.org/operationMetadata", Title = "operation title", Target = "http://odata.org/operationTarget" });
            entryWithOperations.Add(new ServiceOperationDescriptor { IsFunction = true, Metadata = "http://odata.org/operationMetadata", Title = "operation title", Target = "http://odata.org/operationTarget" });

            var validCases = new[]
                {
                    new
                    {
                        // action and function in atom namespace
                        payloadElement = PayloadBuilder.Entity(),
                        Xml = "<$operation metadata='http://odata.org/operationMetadata' title='operation title' target='http://odata.org/operationTarget'/>"
                    },
                    new
                    {
                        // action and function with additional attributes
                        payloadElement = entryWithOperations,
                        Xml = "<m:$operation metadata='http://odata.org/operationMetadata' title='operation title' target='http://odata.org/operationTarget' nonamespace='nonsattribute' m:random='random'/>"
                    },
                    new
                    {
                        // action and function with content
                        payloadElement = entryWithOperations,
                        Xml = "<m:$operation metadata='http://odata.org/operationMetadata' title='operation title' target='http://odata.org/operationTarget'><randomElement/> random text</m:$operation>"
                    },
                    new
                    {
                        // action and function with additional attributes in with the same local name but in a different namespace
                        payloadElement = entryWithOperations,
                        Xml = @"<m:$operation metadata='http://odata.org/operationMetadata' title='operation title' target='http://odata.org/operationTarget'
                                            m:rel='ignored' m:target='ignored' m:title='ignored' m:metadata='ignored' />"
                    },
                    new
                    {
                        // action and function after extra XML element
                        payloadElement = entryWithOperations,
                        Xml = "<randomElement>SomeText</randomElement><m:$operation metadata='http://odata.org/operationMetadata' title='operation title' target='http://odata.org/operationTarget' />"
                    },
                    new
                    {
                        // action and function before extra XML element
                        payloadElement = entryWithOperations,
                        Xml = "<m:$operation metadata='http://odata.org/operationMetadata' title='operation title' target='http://odata.org/operationTarget' /><randomElement>SomeText</randomElement>"
                    }
                };

            var errorCases = new[]
                {
                    new OperationReaderErrorTestCase
                    {
                        Xml = "<m:$operation/>",
                        GetExpectedException = (arg) => ODataExpectedExceptions.ODataException("ODataAtomEntryAndFeedDeserializer_OperationMissingMetadataAttribute", arg),
                    },
                    new OperationReaderErrorTestCase
                    {
                        Xml = "<m:$operation target='http://odata.org'/>",
                        GetExpectedException = (arg) => ODataExpectedExceptions.ODataException("ODataAtomEntryAndFeedDeserializer_OperationMissingMetadataAttribute", arg),
                    },
                    new OperationReaderErrorTestCase
                    {
                        Xml = "<m:$operation m:metadata='/operationMetadata' target='http://odata.org'/>",
                        GetExpectedException = (arg) => ODataExpectedExceptions.ODataException("ODataAtomEntryAndFeedDeserializer_OperationMissingMetadataAttribute", arg),
                    },
                    new OperationReaderErrorTestCase
                    {
                        Xml = "<m:$operation metadata='/operationMetadata'/>",
                        GetExpectedException = (arg) => ODataExpectedExceptions.ODataException("ODataAtomEntryAndFeedDeserializer_OperationMissingTargetAttribute", arg),
                    },
                    new OperationReaderErrorTestCase
                    {
                        Xml = "<m:$operation metadata='/operationMetadata' m:target='random text'/>",
                        GetExpectedException = (arg) => ODataExpectedExceptions.ODataException("ODataAtomEntryAndFeedDeserializer_OperationMissingTargetAttribute", arg),
                    },
                };

            IEnumerable<PayloadReaderTestDescriptor> testDescriptors = validCases.Select(
                vc => new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = vc.payloadElement.DeepCopy()
                        .XmlRepresentation("<entry xmlns:m='http://docs.oasis-open.org/odata/ns/metadata'>" +
                                            vc.Xml.Replace("$operation", "action") +
                                            vc.Xml.Replace("$operation", "function") +
                                            "</entry>")
                })
                .Concat(errorCases.Select( // concat error cases for m:action
                    ec => new PayloadReaderTestDescriptor(this.Settings)
                    {
                        PayloadElement = PayloadBuilder.Entity()
                                    .XmlRepresentation("<entry>" +
                                                        ec.Xml.Replace("$operation", "action") +
                                                        "</entry>"),
                        ExpectedException = ec.GetExpectedException("action"),
                    }))
                .Concat(errorCases.Select( // concat error cases for m:function
                    ec => new PayloadReaderTestDescriptor(this.Settings)
                    {
                        PayloadElement = PayloadBuilder.Entity()
                                    .XmlRepresentation("<entry>" +
                                                        ec.Xml.Replace("$operation", "function") +
                                                        "</entry>"),
                        ExpectedException = ec.GetExpectedException("function"),
                    }));

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                ODataVersionUtils.AllSupportedVersions,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, maxProtocolVersion, testConfiguration) =>
                {
                    if (maxProtocolVersion < testConfiguration.Version)
                    {
                        // This would fail anyway (no need to test it).
                        return;
                    }

                    if (testConfiguration.IsRequest)
                    {
                        testDescriptor = new PayloadReaderTestDescriptor(testDescriptor);
                        testDescriptor.ExpectedException = null;
                        testDescriptor.ExpectedResultNormalizers.Add(tc => RemoveOperationsNormalizer.Normalize);
                    }

                    testDescriptor.RunTest(testConfiguration.CloneAndApplyMaxProtocolVersion(maxProtocolVersion));
                });
        }

        private class OperationReaderErrorTestCase
        {
            public string Xml { get; set; }
            public Func<string, ExpectedException> GetExpectedException { get; set; }
        }
    }
}


text:
title: Printing Content
page_title: Printing Content - RadSplitter
description: Check our Web Forms article about Printing Content.
slug: splitter/panes/printing-content
tags: printing,content
published: True
position: 3
---

# Printing Content

You can print the content of a **RadPane** control using its [client-side API]({%slug splitter/client-side-programming/radpane-object%}). The **RadPane** client-side object has a **print()** method that prints the content of the pane.

* If the content of the pane comes [from an external source]({%slug splitter/panes/displaying-external-content%}), the URL must be from the same domain as the splitter parent page. Otherwise, the pane cannot print its content due to security restrictions of the browser.

* If the pane is not displaying external content, you can specify a stylesheet which will be used to format the printed content.

## Example

The following example demonstrates how to print the content of a pane:

````ASP.NET
<telerik:RadSplitter RenderMode="Lightweight" id="RadSplitter1" runat="server" height="200">
 <telerik:RadPane id="InternalContentPane" runat="server" width="120">
   <p>Founded in 2002, Telerik Corporation is a leading vendor
	  of User Interface (UI) components for ASP.NET and Windows Forms.
	  Building on our expertise in interface development
	  and Microsoft technologies,
	  Telerik helps customers build applications with unparalleled richness,
	  responsiveness and interactivity. Created with passion,
	  Telerik products help thousands of developers every day to be more
	  productive and deliver reliable applications under budget and on time.
   </p>
 </telerik:RadPane>
 <telerik:RadSplitBar id="RadSplitbar1" runat="server"/>
 <telerik:RadPane id="ExternalContentPane" runat="server" width="300"
	ContentUrl="Default.html" />
</telerik:RadSplitter>
<a href="javascript:PrintPane('<%= InternalContentPane.ClientID %>');">
 Print the content of 'Internal Content Pane'</a><br />
<a href="javascript:PrintPane('<%= ExternalContentPane.ClientID %>');">
 Print the content of 'External Content Pane'</a>
<script type="text/javascript">
	function PrintPane(paneID)
	{
		var splitter = $find('<%= RadSplitter1.ClientID%>');
		var pane = splitter.GetPaneById(paneID);
		if (!pane) return;
		var cssFileAbsPath = 'http://localhost/printStyles.css';
		var arrExtStylsheetFiles = [cssFileAbsPath];
		pane.Print(arrExtStylsheetFiles);
	}
</script>
````

## Printing Telerik controls in the content of a RadPane

If there are Telerik controls in the content of a **RadPane** you should add the CSS files that decorate the controls to the array, containing the external stylesheets. Below you can find a modified version of the **PrintPane** function that includes the Telerik controls CSS files, linked on the page, and adds them to the **arrExtStylsheetFiles** array.

````JavaScript
<script type="text/javascript">
	function PrintPane(paneID) {
		var splitter = $find('<%= RadSplitter1.ClientID%>');
		var pane = splitter.GetPaneById(paneID);
		if (!pane) return;

		var arrExtStylsheetFiles = getTelerikCssLinks();

		pane.Print(arrExtStylsheetFiles);
	}

	function getTelerikCssLinks() {
		var result = new Array();

		var links = document.getElementsByTagName("LINK"); //get all link elements on the page

		for (var i = 0; i < links.length; i++) {
			if (links[i].getAttribute("class") == "Telerik_stylesheet")//check if the link element is a Telerik Stylesheet
				result.push(links[i].getAttribute("href", 2)); //add link href attribute to the result
		}

		return result;
	}
</script>
````

## See Also

 * [Overview]({%slug splitter/client-side-programming/overview%})


text:
"""A simple script to setup influxdb user and roles. At some point this should
   become a more full featured module.  Also this assumes that none of the
   python based influxdb clients are available on this system.
"""

import json
import sys

from oslo_utils.encodeutils import safe_decode
from oslo_utils.encodeutils import safe_encode
from six.moves import urllib
import six.moves.urllib.parse as urlparse

ADMIN = 'root'
ADMIN_PASS = 'root'
DBNAME = 'mon'
USERS = {}
USERS['mon_api'] = 'password'
USERS['mon_persister'] = 'password'

URL = 'http://127.0.0.1:8086'

SHARDSPACE_NAME = 'persister_all'
REPLICATION = 1
RETENTION = '90d'

def format_response(req):
    try:
        json_value = json.loads(req.read())
        if (len(json_value['results'][0]) > 0 and
                'series' in json_value['results'][0] and
                'values' in json_value['results'][0]['series'][0]):
            return json_value['results'][0]['series'][0]['values']
        else:
            return []
    except KeyError:
        print("Query returned a non-successful result: {0}".format(json_value['results']))
        raise

def influxdb_get(uri, query, db=None):
    """Runs a query via HTTP GET and returns the response as a Python list."""

    getparams = {"q": query}
    if db:
        getparams['db'] = db

    try:
        params = urlparse.urlencode(getparams)
        uri = "{}&{}".format(uri, params)
        req = urllib.request.urlopen(uri)
        return format_response(req)

    except KeyError:
        sys.exit(1)

def influxdb_get_post(uri, query, db=None):
    """Runs a query using HTTP GET or POST and returns the response as a Python list.
       At some InfluxDB release several ops changed from using GET to POST. For example,
       CREATE DATABASE. To maintain backward compatibility, this function first trys the
       query using POST and if that fails it retries again using GET.
    """

    query_params = {"q": query}
    if db:
        query_params['db'] = db

    try:
        encoded_params = safe_encode(urlparse.urlencode(query_params))
        try:
            req = urllib.request.urlopen(uri, encoded_params)
            return format_response(req)

        except urllib.error.HTTPError:
            uri = "{}&{}".format(uri, encoded_params)
            req = urllib.request.urlopen(uri)
            return format_response(req)

    except KeyError:
        sys.exit(1)

def main(argv=None):
    """If necessary, create the database, retention policy, and users"""
    auth_str = '?u=%s&p=%s' % (ADMIN, ADMIN_PASS)
    api_uri = "{0}/query{1}".format(URL, auth_str)

    # List current databases
    dbs = influxdb_get(uri=api_uri, query="SHOW DATABASES")
    if [DBNAME] not in dbs:
        print("Creating database '{}'".format(DBNAME))
        influxdb_get_post(uri=api_uri, query="CREATE DATABASE {0}".format(DBNAME))
        print("...created!")

    # Check retention policy
    policies = influxdb_get(uri=api_uri,
                            query="SHOW RETENTION POLICIES ON {0}".format(DBNAME))
    if not any(pol[0] == SHARDSPACE_NAME for pol in policies):
        # Set retention policy
        policy = ("CREATE RETENTION POLICY {0} ON {1} DURATION {2} "
                  "REPLICATION {3} DEFAULT".format(SHARDSPACE_NAME,
                                                   DBNAME,
                                                   RETENTION,
                                                   REPLICATION)
                  )
        influxdb_get_post(uri=api_uri, db=DBNAME, query=policy)

    # Create the users
    users = influxdb_get(uri=api_uri, query="SHOW USERS", db=DBNAME)
    for name, password in USERS.items():
        if not any(user[0] == name for user in users):
            influxdb_get_post(uri=api_uri,
                              query=safe_decode("CREATE USER {0} WITH PASSWORD '{1}'"
                                                .format(name, password)),
                              db=DBNAME)

if __name__ == "__main__":
    sys.exit(main())


text:
package org.sakaiproject.tool.assessment.jsf.renderer;

import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.component.UIOutput;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.Renderer;
import java.util.*;
import java.text.*;
/**
 *
Description:

 *
Render the HTML code for a Tigris color picker popup.

 *
Organization: Sakai Project

 * @author Ed Smiley
 * @version $id: $
 *
 * @todo add resource for strings
 */

public class DatePickerPopupRenderer extends Renderer
{
  // these should be coming from a resource
  // value in alt tags, these are not yet internationalized
  public static final String PREV_MONTH = "previous month";
  public static final String NEXT_MONTH = "next month";
  public static final String PREV_YEAR = "previous year";
  public static final String NEXT_YEAR = "next year";

  public boolean supportsComponentType(UIComponent component)
  {
    return (component instanceof UIOutput);
  }

  public void decode(FacesContext context, UIComponent component)
  {
  }

  public void encodeBegin(FacesContext context, UIComponent component)
    throws IOException
  {
    ;
  }

  public void encodeChildren(FacesContext context, UIComponent component)
    throws IOException
  {
    ;
  }

  // warning: considerable hand modification...
  /* *** GENERATOR FILE: c:\Navigo\webapp\html\c.html*** */
  /* *** IF SOURCE DOCUMENT CHANGES YOU NEED TO REGENERATE THIS METHOD*** */
  /**
   *
Faces render output method .

   *
Method Generator: org.sakaiproject.tool.assessment.devtoolsRenderMaker

   *
   *  @param context   FacesContext for the current request
   *  @param component UIComponent being rendered
   *
   * @throws IOException if an input/output error occurs
   */
    public void encodeEnd(FacesContext context, UIComponent component)
        throws IOException {
      // get the calendar for the Locale, so this will be localized
      DateFormatSymbols dfs = new DateFormatSymbols();
      String[] days = dfs.getShortWeekdays();
      String[] months = dfs.getMonths();
      String jan = months[Calendar.JANUARY];
      String feb = months[Calendar.FEBRUARY];
      String mar = months[Calendar.MARCH];
      String apr = months[Calendar.APRIL];
      String may = months[Calendar.MAY];
      String jun = months[Calendar.JUNE];
      String jul = months[Calendar.JULY];
      String aug = months[Calendar.AUGUST];
      String sep = months[Calendar.SEPTEMBER];
      String oct = months[Calendar.OCTOBER];
      String nov = months[Calendar.NOVEMBER];
      String dec = months[Calendar.DECEMBER];
      String mon = days[Calendar.MONDAY];
      String tue = days[Calendar.TUESDAY];
      String wed = days[Calendar.WEDNESDAY];
      String thu = days[Calendar.THURSDAY];
      String fri = days[Calendar.FRIDAY];
      //String sat = days[Calendar.SATURDAY];
      String sun = days[Calendar.SUNDAY];

      String contextPath = context.getExternalContext().getRequestContextPath();

      ResponseWriter writer = context.getResponseWriter();

      writer.write("\n");

      writer.write("\n");
//      writer.write("\n");
//      writer.write(
//        "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN>");
//      writer.write("\n");
      writer.write("\n");
      writer.write("<title>Select Date, Please.</title>\n");
      writer.write("\n");
      writer.write("\n");
      writer.write("\n");
      writer.write("\n");
      // replaced these lines with document.write so dom balanced in XHTML
//        writer.write("
\n");
//        writer.write("
\n");
//        writer.write("
\n");
//        writer.write("

\n");
//        writer.write("
\n");
      writer.write("\n");
//        writer.write("
\n");
//        writer.write("

\n");
//        writer.write("
\n");
//        writer.write("\n");
      // replaced these lines with document.write so DOM balanced in XHTML
//        writer.write("
	\n");
//        writer.write("

	\n");
//        writer.write("
\n");
      writer.write("\n");
      writer.write("\n");
      writer.write("\n");
  }
}


text:
<?php
/*
Plugin Name: Play Store App List
Description: Adds widget which contains a list of android apps. Each item contains links directly to the Play Store.
Version:     1.0.0
Author:      Yannick Signer
Author URI:  http://www.halcyon.ch
License:     Apache 2.0
License URI: http://www.apache.org/licenses/LICENSE-2.0
*/

class wpb_widget extends WP_Widget {

function __construct() {
parent::__construct(
'wpb_widget',

__('Play Store App List Widget', 'wpb_widget_domain'),

array( 'description' => __( 'Adds widget which contains a list of android apps. Each item contains links directly to the Play Store.', 'wpb_widget_domain' ), )
);
}

public function widget( $args, $instance ) {
  $title = apply_filters( 'widget_title', $instance['title'] );
  $pkgnames = explode(";", $instance['pkgnames']);
  echo $args['before_widget'];

  if (!empty( $title )){
    echo $args['before_title'] . $title . $args['after_title'];
  }

  echo '
';
  echo '
';

  foreach ($pkgnames as $value) {
    $obj = json_decode(file_get_contents("http://halcyon.ch/icon_service/index.php?pkg=" . $value));

    echo '';
    echo '
';
    echo 'src.'" height="60" width="60" style="float: left;margin: 0 15px 0 0;" />';
    echo '
'.$obj->package.'
';
    echo '
'.$obj->name.'
';
    echo '
';
    echo '';
  }

  echo '
';
  echo '
';

  echo $args['after_widget'];
}

public function form( $instance ) {
  if (isset($instance[ 'title' ])) {
    $title = $instance[ 'title' ];
  }
  else {
    $title = __( 'New title', 'wpb_widget_domain' );
  }

  if (isset($instance[ 'pkgnames' ])) {
    $pkgnames = $instance[ 'pkgnames' ];
  }
  else {
    $pkgnames = __( '', 'wpb_widget_domain' );
  }

?>

<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />

<label for="<?php echo $this->get_field_id( 'pkgnames' ); ?>"><?php _e( 'Packagenames:' ); ?>
<input class="widefat" id="<?php echo $this->get_field_id( 'pkgnames' ); ?>" name="<?php echo $this->get_field_name( 'pkgnames' ); ?>" type="text" value="<?php echo esc_attr( $pkgnames ); ?>" />

<?php
}

public function update( $new_instance, $old_instance ) {
  $instance = array();
  $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
  $instance['pkgnames'] = ( ! empty( $new_instance['pkgnames'] ) ) ? strip_tags( $new_instance['pkgnames'] ) : '';
  return $instance;
}

}

function wpb_load_widget() {
	register_widget( 'wpb_widget' );
}
add_action( 'widgets_init', 'wpb_load_widget' );

?>


text:
package ca.deca.decaontarioapp.ui;

import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.TypedValue;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

import ca.deca.decaontarioapp.R;
import ca.deca.decaontarioapp.utils.singletons.DataSingleton;
import ca.deca.decaontarioapp.utils.singletons.PrefSingleton;
import de.greenrobot.event.EventBus;

/**
 * Created by Reno on 14-12-31.
 * A base Activity that is extended by every Activity for common theme and cache execution
 */
public class BaseActivity extends ActionBarActivity implements View.OnTouchListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Initialize my singletons for use throughout the application
        PrefSingleton.getInstance().Initialize(this);
        DataSingleton.getInstance().Initialize(this);

        // Now do the usual activity methods
        super.onCreate(savedInstanceState);

        initTheme();
    }

    /**
     *  If on the correct build version, sets the status bar to be a slightly darker color
     *  than the Primary Color of the theme.
     */
    private void initTheme() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            TypedValue typedValue = new TypedValue();
            Resources.Theme theme = getTheme();
            theme.resolveAttribute(R.attr.colorPrimaryDark, typedValue, true);
            int color = typedValue.data;
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(color);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // Needed else the selector is laggy to update colors
        // This sends the ACTION_DOWN much quicker, making extremely fast response times
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                v.setPressed(true);
                break;
        }
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Needed to help ensure efficiency of returning back when back is pressed
        int id = item.getItemId();
        if (id == android.R.id.home) {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // We want to make sure our cache wasn't deleted when the app was Paused
        DataSingleton.getInstance().verifyCache();
    }

    @Override
    public void onStart() {
        super.onStart();
        // Register for EventBus notifications
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        // Stop the EventBus listener before we stop the Activity
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    public void onEventMainThread(DataSingleton.EVENTBUS_EVENT event) {
        // This is here so that a class that does not override will not crash when
        // an event comes through
    }
}


text:
Innloggingsklasse

Dette feltet skal inneholde navnet på en påloggings klasse, definert i filen
<tt> login.conf </ tt>. Sjekk FreeBSD manual-siden på <tt> login.conf </ tt>
for mer informasjon om innloggings klasser.


text:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/cause_toggle_background" />
    <item android:drawable="@drawable/cause_environment" />
</layer-list>


text:
class GURL;

// This class is responsible for showing/hiding the interstitial page that
// occurs when a new domain is visited and it looks suspiciously like another
// more popular domain.
class LookalikeUrlBlockingPage
    : public security_interstitials::SecurityInterstitialPage {
 public:
  // Interstitial type, used in tests.
  static const security_interstitials::SecurityInterstitialPage::TypeID
      kTypeForTesting;

  LookalikeUrlBlockingPage(
      content::WebContents* web_contents,
      const GURL& request_url,
      ukm::SourceId source_id,
      LookalikeUrlMatchType match_type,
      std::unique_ptr<
          security_interstitials::SecurityInterstitialControllerClient>
          controller);

  ~LookalikeUrlBlockingPage() override;

  // SecurityInterstitialPage method:
  security_interstitials::SecurityInterstitialPage::TypeID GetTypeForTesting()
      override;

  // Allow easier reporting of UKM when no interstitial is shown.
  static void RecordUkmEvent(ukm::SourceId source_id,
                             LookalikeUrlMatchType match_type,
                             LookalikeUrlBlockingPageUserAction user_action);

 protected:
  // SecurityInterstitialPage implementation:
  void CommandReceived(const std::string& command) override;
  bool ShouldCreateNewNavigation() const override;
  void PopulateInterstitialStrings(
      base::DictionaryValue* load_time_data) override;
  void OnInterstitialClosing() override;
  bool ShouldDisplayURL() const override;
  int GetHTMLTemplateId() override;

 private:
  friend class LookalikeUrlNavigationThrottleBrowserTest;

  // Values added to get our shared interstitial HTML to play nice.
  void PopulateStringsForSharedHTML(base::DictionaryValue* load_time_data);

  // Record UKM iff we haven't already reported for this page.
  void ReportUkmIfNeeded(LookalikeUrlBlockingPageUserAction action);

  ukm::SourceId source_id_;
  LookalikeUrlMatchType match_type_;

  DISALLOW_COPY_AND_ASSIGN(LookalikeUrlBlockingPage);
};

#endif  // CHROME_BROWSER_LOOKALIKES_LOOKALIKE_URL_BLOCKING_PAGE_H_


text:
package io.github.hapjava.characteristics.impl.common;

import io.github.hapjava.characteristics.CharacteristicEnum;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

/** 0 "Single Press" 1 "Double Press" 2 "Long Press" 3-255 "Reserved" */
public enum ProgrammableSwitchEnum implements CharacteristicEnum {
  SINGLE_PRESS(0),
  DOUBLE_PRESS(1),
  LONG_PRESS(3);

  private static final Map<Integer, ProgrammableSwitchEnum> reverse;

  static {
    reverse =
        Arrays.stream(ProgrammableSwitchEnum.values())
            .collect(Collectors.toMap(ProgrammableSwitchEnum::getCode, t -> t));
  }

  public static ProgrammableSwitchEnum fromCode(Integer code) {
    return reverse.get(code);
  }

  private final int code;

  ProgrammableSwitchEnum(int code) {
    this.code = code;
  }

  @Override
  public int getCode() {
    return code;
  }
}


text:
import { lazyComponent } from '@waldur/core/lazyComponent';
import { StateDeclaration } from '@waldur/core/types';

const AuthLoginCompleted = lazyComponent(
  () =>
    import(/* webpackChunkName: "AuthLoginCompleted" */ './AuthLoginCompleted'),
  'AuthLoginCompleted',
);

const OauthLoginCompleted = lazyComponent(
  () =>
    import(
      /* webpackChunkName: "OauthLoginCompleted" */ './OauthLoginCompleted'
    ),
  'OauthLoginCompleted',
);

const SAML2DiscoveryCompleted = lazyComponent(
  () =>
    import(
      /* webpackChunkName: "SAML2DiscoveryCompleted" */ './SAML2DiscoveryCompleted'
    ),
  'SAML2DiscoveryCompleted',
);

const AuthLoginFailed = lazyComponent(
  () => import(/* webpackChunkName: "AuthLoginFailed" */ './AuthLoginFailed'),
  'AuthLoginFailed',
);

const AuthLogoutCompleted = lazyComponent(
  () =>
    import(
      /* webpackChunkName: "AuthLogoutCompleted" */ './AuthLogoutCompleted'
    ),
  'AuthLogoutCompleted',
);

const AuthLogoutFailed = lazyComponent(
  () => import(/* webpackChunkName: "AuthLogoutFailed" */ './AuthLogoutFailed'),
  'AuthLogoutFailed',
);

export const states: StateDeclaration[] = [
  {
    name: 'home.login_completed',
    url: '/login_completed/:token/:method/',
    component: AuthLoginCompleted,
    data: {
      anonymous: true,
    },
  },

  {
    name: 'home.oauth_login_completed',
    url: '/oauth_login_completed/:provider/',
    component: OauthLoginCompleted,
    data: {
      anonymous: true,
    },
  },

  {
    name: 'home.saml2_discovery_completed',
    url: '/saml2_discovery_completed/',
    component: SAML2DiscoveryCompleted,
    data: {
      anonymous: true,
    },
  },

  {
    name: 'home.login_failed',
    url: '/login_failed/',
    component: AuthLoginFailed,
    data: {
      erred: true,
    },
  },

  {
    name: 'home.logout_completed',
    url: '/logout_completed/',
    component: AuthLogoutCompleted,
  },

  {
    name: 'home.logout_failed',
    url: '/logout_failed/',
    component: AuthLogoutFailed,
    data: {
      erred: true,
    },
  },
];


text:
#ifndef _PCI_H
#define _PCI_H

#include <blt/types.h>

typedef struct
{
	/* normal header stuff */
	uint16 vendor_id;
	uint16 device_id;

	uint16 command;
	uint16 status;

	uint8 revision_id;
	uint8 interface;
	uint8 sub_class;
	uint8 base_class;

	uint8 cache_line_size;
	uint8 latency_timer;
	uint8 header_type;
	uint8 bist;

	/* device info */
	uint8 bus;
	uint8 dev;
	uint8 func;
	uint8 _pad;

	/* base registers */
	uint32 base[6];
	uint32 size[6];

} pci_cfg;

int pci_find(pci_cfg *cfg, uint16 vendor_id, uint16 device_id);

uint32 pci_read(int bus, int dev, int func, int reg, int bytes);
void pci_write(int bus, int dev, int func, int reg, uint32 v, int bytes);

#endif


text:
package org.ardverk.concurrent;

import java.util.concurrent.TimeUnit;

public interface AsyncProcessSubmitService extends SubmitService {

  /**
   * Submits the given {@link AsyncProcess} for execution.
   */
  public <T> AsyncFuture<T> submit(AsyncProcess<T> process);

  /**
   * Submits the given {@link AsyncProcess} for execution.
   */
  public <T> AsyncFuture<T> submit(AsyncProcess<T> process,
      long timeout, TimeUnit unit);
}


text:
overtake
========

Check config files for CDN updates by way of the
[jsDelivr API](https://github.com/jsdelivr/api). Supports
[jsDelivr](http://jsdelivr.com), [CDNJS](https://cdnjs.com) and
[Google Hosted Libraries](https://developers.google.com/speed/libraries), as
well as some advanced features such as
[version aliasing](https://github.com/jsdelivr/jsdelivr#version-aliasing) and
[single requests for multiple files](https://github.com/jsdelivr/jsdelivr#load-multiple-files-with-single-http-request).

Usage
-----

### Command Line

    $ overtake config.js index.html

    [config.js] [jsdelivr]: "underscore.string" can be updated from 2.3.0 to 2.3.3
    [config.js] [cdnjs]: "codemirror" can be updated from 4.0.3 to 4.1.0
    [index.html] [cdnjs]: "jquery.nanoscroller" can be updated from 0.7.6 to 0.8.0

### Module

```javascript
var overtake = require('overtake');
overtake.check_file('config.js').done(function(updates) {

 /*
  * [
  *   { file: 'config.js', cdn: 'jsdelivr', pkg: 'underscore.string', ver: '2.3.0', latest: '2.3.3' },
  *   { file: 'config.js', cdn: 'cdnjs', pkg: 'codemirror', ver: '4.0.3', latest: '4.1.0' },
  *   { file: 'index.html', cdn: 'cdnjs', pkg: 'jquery.nanoscroller', ver: '0.7.6', latest: '0.8.0' }
  * ]
  */

});
```

### Gulp

```javascript
gulp.task('cdn', function(done) {
  var filenames = [];
  overtake.opts.update_msg = '  [%s] [%s] [%s] %s => %s';

  gulp.src([
    './config/*',
  ], { read: false })
  .on('data', function(file) { filenames.push(file.path); })
  .on('end', function() {
    overtake.check_files(filenames, true).done(function(updates) {
      // or, pass `false` to `print` above, and do something with
      // the `updates` array here

      done();
    });
  });
});
```

Methods
-------

`overtake.check_file({String} filename, {Boolean} print)` `=>` `Promise`

Check a file named by `filename` for CDN updates. Returns a promise which
resolves to an array of updates, or rejects on failure.

`overtake.check_files({Array} filenames, {Boolean} print)` `=>` `Promise`

Check multiple files for CDN updates. Returns a promise which
resolves to an array of updates, or rejects on failure.

`overtake.check_contents({String} contents, {String} source, {Boolean} print)` `=>` `Promise`

Check the contents of a config file for CDN updates.  Returns a promise in the
same manner as `overtake.check_file`.

License
-------
Released under the terms of the
[MIT license](http://tldrlegal.com/license/mit-license). See **LICENSE**.


text:
package com.github.thbrown.softballsim.tools;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import com.github.thbrown.softballsim.Msg;
import com.github.thbrown.softballsim.data.gson.DataPlayer;
import com.github.thbrown.softballsim.data.gson.DataStats;
import com.github.thbrown.softballsim.lineup.BattingLineup;
import com.github.thbrown.softballsim.lineup.StandardBattingLineup;
import com.github.thbrown.softballsim.optimizer.impl.montecarloexhaustive.HitGenerator;
import com.github.thbrown.softballsim.optimizer.impl.montecarloexhaustive.MonteCarloMultiGameSimulationTask;
import com.github.thbrown.softballsim.optimizer.impl.montecarloexhaustive.TaskResult;
import com.github.thbrown.softballsim.util.GsonAccessor;
import com.github.thbrown.softballsim.util.Logger;
import org.junit.Test;

public class SingleGameSimulation {

  @Test
  public void simulateSingleGame() {

    Logger.log("STARTING");

    // Get stats from file
    String statsFileLocation = "./stats/exampleData.json";
    String json = null;
    File file = new File(statsFileLocation);
    try {
      if (file.isDirectory()) {
        File[] filesInDirectory = file.listFiles();
        List<File> filesOnly = Arrays.stream(filesInDirectory).filter(f -> f.isFile()).collect(Collectors.toList());
        if (filesOnly.size() == 1) {
          json = new String(Files.readAllBytes(Paths.get(filesOnly.get(0).getCanonicalPath())));
        } else {
          throw new RuntimeException(
              "There were " + filesOnly.size() + " files in the stats-path directory specified ("
                  + file.getAbsolutePath()
                  + "), but this application expects only one, or a path direclty to the stats file");
        }
      } else {
        json = new String(Files.readAllBytes(Paths.get(statsFileLocation)));
      }
    } catch (IOException e) {
      throw new RuntimeException(Msg.BAD_PATH.args(statsFileLocation), e);
    }
    DataStats stats = GsonAccessor.getInstance().getCustom().fromJson(json, DataStats.class);

    // Build the lineup
    List<DataPlayer> playerList = new ArrayList<>();

    playerList.add(stats.getPlayerById("00000000000002"));
    playerList.add(stats.getPlayerById("0000000000000y"));
    playerList.add(stats.getPlayerById("00000000000001"));
    playerList.add(stats.getPlayerById("00000000000003"));
    playerList.add(stats.getPlayerById("0000000000000f"));
    playerList.add(stats.getPlayerById("00000000000004"));

    // Simulate a games
    final int GAMES = 1000000;
    BattingLineup lineup = new StandardBattingLineup(playerList);
    HitGenerator hitGenerator = new HitGenerator(playerList);

    // Run on the current thread
    MonteCarloMultiGameSimulationTask task =
        new MonteCarloMultiGameSimulationTask(lineup, GAMES, 7, hitGenerator);
    TaskResult result = task.run();
    Logger.log(result.getScore());
    Logger.log(result.getLineup());

  }

}


text:
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE AllowAmbiguousTypes #-}

--------------------------------------------------------------------
-- |
-- Module      :  IOException wrappers
-- Copyright   :  (C) Marek Kidon 2016
-- License     :  BSD-style (see the file LICENSE)
-- Maintainer  :  Marek 'Tr1p0d' Kidon <marek.kidon@itcommunity.cz>
-- Stability   :  experimental
-- Portability :  non-portable
--
-- This module provides wrappers for IOException to make
-- Thows signatures more readable.
--------------------------------------------------------------------
module Network.Connections.Internal.Types.Exception where

import Control.Exception (Exception)
import Control.Exception.Errno
    ( ConnectionRefusedError
    , HostUnreachableError
    )
import Control.Monad (Monad)
import Control.Monad.Catch (MonadCatch, catch)
import qualified Control.Monad.TaggedException as E (Throws)
import qualified Control.Monad.TaggedException.Internal.Throws as E
    (Throws(Throws))
import Data.Function ((.), flip, id)

import Prelude (undefined)

catch'
    ::
    ( Exception e
    , MonadCatch m
    , FromThrows (E.Throws (e `Catch` es) m a)
    )
    => E.Throws es m a
    -> (e -> m a)
    -> EvalThrows (E.Throws (e `Catch` es) m a)
catch' = (evalThrows .) . catch''
  where
    catch''
        :: (Exception e, MonadCatch m)
        => E.Throws es m a
        -> (e -> m a)
        -> E.Throws (e `Catch` es) m a
    catch'' (E.Throws ma) = E.Throws . catch ma

handle'
    ::
    ( Exception e
    , MonadCatch m
    , FromThrows (E.Throws (e `Catch` es) m a)
    )
    => (e -> m a)
    -> E.Throws es m a
    -> EvalThrows (E.Throws (e `Catch` es) m a)
handle' = flip catch'

class FromThrows a where
    type EvalThrows a :: *

    evalThrows :: a -> EvalThrows a

instance Monad m => FromThrows (E.Throws '[] m a) where
    type EvalThrows (E.Throws '[] m a) = m a

    evalThrows (E.Throws ma) = ma

instance Monad m => FromThrows (E.Throws '[e] m a) where
    type EvalThrows (E.Throws '[e] m a) = E.Throws '[e] m a

    evalThrows = id

instance Monad m => FromThrows (E.Throws '[e, e1] m a) where
    type EvalThrows (E.Throws '[e, e1] m a) = E.Throws '[e, e1] m a

    evalThrows = id

type family (e1 :: *) `Catch` (e2 :: [*]) where
    e1 `Catch` (e1 ': es) = es
    e1 `Catch` '[] = '[]
    e1 `Catch` (e2 ': es) = e2 ': (e1 `Catch` es)

computation :: E.Throws [HostUnreachableError, ConnectionRefusedError] m ()
computation = undefined

handler :: HostUnreachableError -> m ()
handler = undefined

handler' :: ConnectionRefusedError -> m ()
handler' = undefined


text:
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://docbook.org/ns/docbook"
  xmlns:xi="http://www.w3.org/2001/XInclude"
  xmlns:xlink="http://www.w3.org/1999/xlink"
  xmlns:linkend="http://www.w3.org/1999/linkend"
  xmlns:xref="http://www.w3.org/1999/xref"
  xmlns:wadl="http://wadl.dev.java.net/2009/02"
  version="5.0-extension RackBook-2.0"
  xml:id="api.openstack.org-orchestration-v1" status="CURRENT">
  <info xreflabel="api-ref-orchestration-v1.html">
    <title>OpenStack Orchestration API v1 (CURRENT)</title>
    <copyright>
      <year>2010-2016</year>
    </copyright>
    <legalnotice role="apache2">
      <para/>
    </legalnotice>
    <annotation>
      <xi:include href="itemizedlist-service-list.xml"/>
    </annotation>
  </info>
  <xi:include href="ch_orchestration-v1.xml"/>
</book>


text:
<?php
/**
 * User: scil
 * Date: 2018/8/20
 * Time: 10:15
 */

namespace LaravelFly\Server\Traits;

use swoole_atomic;

trait ShareInteger
{
    /**
     * @var [\swoole_atomic] save shared actomic info across processes
     */
    var $integerMemory = [];

    public function newIntegerMemory(string $name, swoole_atomic $atom): swoole_atomic
    {
        return $this->integerMemory[$name] = $atom;
    }

    /**
     * @param string $name
     * @return int|null
     */
    public function getIntegerMemory(string $name): ?int
    {
        if (array_key_exists($name, $this->integerMemory)) {
            return $this->integerMemory[$name]->get();
        }
        return null;
    }

    function setIntegerMemory(string $name, $value, $when = null)
    {
        if (array_key_exists($name, $this->integerMemory)) {
            if ($when) {
                return $this->integerMemory[$name]->cmpset($when, (int)$value);
            }
            $this->integerMemory[$name]->set((int)$value);
        }
    }

    function addIntegerMemory(string $name, $value)
    {
        if (array_key_exists($name, $this->integerMemory))
            $this->integerMemory[$name]->add((int)$value);
    }

    function subIntegerMemory(string $name, $value)
    {
        if (array_key_exists($name, $this->integerMemory))
            $this->integerMemory[$name]->sub((int)$value);
    }
}


text:
@implementation RXARCCategoryMethodParentObject
- (void)print
{
    NSLog(@"RXARCCategoryMethodParentObject");
}
@end


text:
import Ember from 'ember';
import {
  moduleForComponent,
  test
} from 'ember-qunit';

moduleForComponent('input-credit-card-zipcode', {});

test('it renders', function(assert) {
  assert.expect(2);

  var component = this.subject();
  assert.equal(component._state, 'preRender');

  this.render();
  assert.equal(component._state, 'inDOM');
});

test('should accept 9 digits ', function(assert) {
  var component = this.subject();
  this.render();

  Ember.run(function() {
    component.set('zipcode', '946062370');
  });

  // Ember.run(function() {
  //   component.$().trigger({type: 'keypress', which: 52, keyCode: 52});
  // });

  Ember.run(function() {
    var value = component.get('value');
    assert.equal(value, '94606-2370');
  });
});


text:
Lua::Lua() {
    L = luaL_newstate();
    luaL_openlibs(L);
}

Lua::~Lua() {
    lua_close(L);
}

void Lua::doFile(const std::string &filename) {
    LuaStackFrame frame{L};

    const char *name = filename.c_str();
    checkLoadResult(luaL_loadfile(L, name), name);
    pcallWrapper(0, 0, name);
}

void Lua::doString(const std::string &code) {
    LuaStackFrame frame{L};

    static const char *name = "lua string literal";
    checkLoadResult(luaL_loadstring(L, code.c_str()), name);
    pcallWrapper(0, 0, name);
}

void Lua::checkLoadResult(int result, const char *name) {
    if (result == 0) {
        return;
    }

    std::stringstream buf;
    if (result == LUA_ERRFILE) {
        buf << "Failed to open " << name;
    } else if (result == LUA_ERRSYNTAX) {
        buf << "Syntax error in " << name;
        buf << std::endl << lua_tostring(L, -1);
    } else {
        buf << "Out of memory or other error while loading " << name;
    }
    throw LuaException(buf.str().c_str());
}

void Lua::pcallWrapper(int nargs, int nresults, const char *name) {
    int result = lua_pcall(L, nargs, nresults, 0);
    if (result != 0) {
        std::stringstream buf;
        if (result == LUA_ERRRUN) {
            buf << "Error while calling " << name << std::endl << lua_tostring(L, -1);
        } else {
            buf << "Out of memory or unknown error while calling " << name;
        }
        throw LuaException(buf.str().c_str());
    }
}