text:
import { DestinyAccount } from 'app/accounts/destiny-account';
import { setItemHashTag, setItemTag } from 'app/inventory/actions';
import { setSettingAction } from 'app/settings/actions';
import { BungieMembershipType, DestinyClass } from 'bungie-api-ts/destiny2';
import copy from 'fast-copy';
import { DeleteLoadoutUpdateWithRollback } from './api-types';
import { finishedUpdates, prepareToFlushUpdates } from './basic-actions';
import { dimApi, DimApiState, initialState as apiInitialState } from './reducer';

const currentAccount: DestinyAccount = {
  membershipId: '98765',
  destinyVersion: 2,
  displayName: 'Foobar',
  originalPlatformType: BungieMembershipType.TigerPsn,
  platformLabel: 'PlayStation',
  platforms: [BungieMembershipType.TigerPsn],
};
const currentAccountKey = '98765-d2';

const initialState: DimApiState = {
  ...apiInitialState,
  apiPermissionGranted: true,
};

describe('setSetting', () => {
  it('changes settings', () => {
    const state = initialState;

    const updatedState = dimApi(state, setSettingAction('showNewItems', true));

    expect(updatedState.settings.showNewItems).toBe(true);
    expect(updatedState.updateQueue).toEqual([
      {
        action: 'setting',
        payload: {
          showNewItems: true,
        },
        before: {
          showNewItems: false,
        },
      },
    ]);
  });
});

describe('setItemTag', () => {
  it('sets tags if there were none before', () => {
    const state = initialState;

    const updatedState = dimApi(
      state,
      setItemTag({ itemId: '1234', tag: 'favorite' }),
      currentAccount
    );

    expect(updatedState.profiles[currentAccountKey].tags['1234'].tag).toBe('favorite');
    expect(copy(updatedState.updateQueue)).toEqual([
      {
        action: 'tag',
        payload: {
          id: '1234',
          tag: 'favorite',
        },
        platformMembershipId: currentAccount.membershipId,
        destinyVersion: currentAccount.destinyVersion,
      },
    ]);
  });

  it('clears set tags', () => {
    const state = initialState;

    let updatedState = dimApi(
      state,
      setItemTag({ itemId: '1234', tag: 'favorite' }),
      currentAccount
    );

    updatedState = dimApi(
      updatedState,
      setItemTag({ itemId: '1234', tag: undefined }),
      currentAccount
    );

    expect(updatedState.profiles[currentAccountKey].tags['1234']).toBeUndefined();
    expect(copy(updatedState.updateQueue)).toEqual([
      {
        action: 'tag',
        payload: {
          id: '1234',
          tag: 'favorite',
        },
        platformMembershipId: currentAccount.membershipId,
        destinyVersion: currentAccount.destinyVersion,
      },
      {
        action: 'tag',
        payload: {
          id: '1234',
          tag: null,
        },
        before: {
          id: '1234',
          tag: 'favorite',
        },
        platformMembershipId: currentAccount.membershipId,
        destinyVersion: currentAccount.destinyVersion,
      },
    ]);
  });
});

describe('setItemHashTag', () => {
  it('sets tags if there were none before', () => {
    const state = initialState;

    const updatedState = dimApi(
      state,
      setItemHashTag({ itemHash: 1234, tag: 'favorite' }),
      currentAccount
    );

    expect(updatedState.itemHashTags[1234].tag).toBe('favorite');
    expect(copy(updatedState.updateQueue)).toEqual([
      {
        action: 'item_hash_tag',
        payload: {
          hash: 1234,
          tag: 'favorite',
        },
        platformMembershipId: currentAccount.membershipId,
        destinyVersion: currentAccount.destinyVersion,
      },
    ]);
  });

  it('clears set tags', () => {
    const state = initialState;

    let updatedState = dimApi(
      state,
      setItemHashTag({ itemHash: 1234, tag: 'favorite' }),
      currentAccount
    );

    updatedState = dimApi(
      updatedState,
      setItemHashTag({ itemHash: 1234, tag: undefined }),
      currentAccount
    );

    expect(updatedState.itemHashTags[1234]).toBeUndefined();
    expect(copy(updatedState.updateQueue)).toEqual([
      {
        action: 'item_hash_tag',
        payload: {
          hash: 1234,
          tag: 'favorite',
        },
        platformMembershipId: currentAccount.membershipId,
        destinyVersion: currentAccount.destinyVersion,
      },
      {
        action: 'item_hash_tag',
        payload: {
          hash: 1234,
          tag: null,
        },
        before: {
          hash: 1234,
          tag: 'favorite',
        },
        platformMembershipId: currentAccount.membershipId,
        destinyVersion: currentAccount.destinyVersion,
      },
    ]);
  });
});

describe('prepareToFlushUpdates', () => {
  it('can coalesce settings', () => {
    const state: DimApiState = {
      ...initialState,
      updateQueue: [
        // Turn new items on
        {
          action: 'setting',
          payload: {
            showNewItems: true,
          },
          before: {
            showNewItems: false,
          },
        },
        // Modify another setting
        {
          action: 'setting',
          payload: {
            itemSize: 50,
          },
          before: {
            itemSize: 48,
          },
        },
        // Turn new items back off
        {
          action: 'setting',
          payload: {
            showNewItems: false,
          },
          before: {
            showNewItems: true,
          },
        },
      ],
    };

    const updatedState = dimApi(state, prepareToFlushUpdates());

    expect(updatedState.updateInProgressWatermark).toBe(1);
    // Expect that showNewItems change is eliminated, and there's only one update
    const expected = [
      {
        action: 'setting',
        payload: {
          itemSize: 50,
        },
        before: {
          itemSize: 48,
        },
      },
    ];
    expect(copy(updatedState.updateQueue)).toEqual(expected);
  });

  it('can handle multiple profile updates', () => {
    const state: DimApiState = {
      ...initialState,
      updateQueue: [
        // Turn new items on
        {
          action: 'setting',
          payload: {
            showNewItems: true,
          },
          before: {
            showNewItems: false,
          },
        },
        // Save a tag for D2
        {
          action: 'tag',
          payload: {
            id: '1234',
            tag: 'favorite',
          },
          before: {
            id: '1234',
          },
          platformMembershipId: '3456',
          destinyVersion: 2,
        },
        // Save a tag for D1, same profile
        {
          action: 'tag',
          payload: {
            id: '1231903',
            tag: 'keep',
          },
          before: {
            id: '1231903',
          },
          platformMembershipId: '3456',
          destinyVersion: 1,
        },
        // Save a tag for D2, same profile
        {
          action: 'tag',
          payload: {
            id: '76543',
            tag: 'junk',
          },
          before: {
            id: '76543',
          },
          platformMembershipId: '3456',
          destinyVersion: 2,
        },
      ],
    };

    const updatedState = dimApi(state, prepareToFlushUpdates());

    expect(updatedState.updateInProgressWatermark).toBe(3);
    // Expect that the queue is rearranged to have the D2 account updates together
    const expected = [
      // Turn new items on
      {
        action: 'setting',
        payload: {
          showNewItems: true,
        },
        before: {
          showNewItems: false,
        },
      },
      // Save a tag for D2
      {
        action: 'tag',
        payload: {
          id: '1234',
          tag: 'favorite',
        },
        before: {
          id: '1234',
        },
        platformMembershipId: '3456',
        destinyVersion: 2,
      },
      // Save a tag for D2
      {
        action: 'tag',
        payload: {
          id: '76543',
          tag: 'junk',
        },
        before: {
          id: '76543',
        },
        platformMembershipId: '3456',
        destinyVersion: 2,
      },
      // Save a tag for D1
      {
        action: 'tag',
        payload: {
          id: '1231903',
          tag: 'keep',
        },
        before: {
          id: '1231903',
        },
        platformMembershipId: '3456',
        destinyVersion: 1,
      },
    ];
    expect(copy(updatedState.updateQueue)).toEqual(expected);
  });

  it('can handle multiple profile updates with settings last', () => {
    const state: DimApiState = {
      ...initialState,
      updateQueue: [
        // Save a tag for D2
        {
          action: 'tag',
          payload: {
            id: '1234',
            tag: 'favorite',
          },
          before: {
            id: '1234',
          },
          platformMembershipId: '3456',
          destinyVersion: 2,
        },
        // Save a tag for D2, same profile
        {
          action: 'tag',
          payload: {
            id: '76543',
            tag: 'junk',
          },
          before: {
            id: '76543',
          },
          platformMembershipId: '3456',
          destinyVersion: 2,
        },
        // Turn new items on
        {
          action: 'setting',
          payload: {
            showNewItems: true,
          },
          before: {
            showNewItems: false,
          },
        },
      ],
    };

    const updatedState = dimApi(state, prepareToFlushUpdates());

    expect(updatedState.updateInProgressWatermark).toBe(3);
    // Expect that the queue is rearranged to have the D2 account updates together
    const expected = [
      // Save a tag for D2
      {
        action: 'tag',
        payload: {
          id: '1234',
          tag: 'favorite',
        },
        before: {
          id: '1234',
        },
        platformMembershipId: '3456',
        destinyVersion: 2,
      },
      // Save a tag for D2
      {
        action: 'tag',
        payload: {
          id: '76543',
          tag: 'junk',
        },
        before: {
          id: '76543',
        },
        platformMembershipId: '3456',
        destinyVersion: 2,
      },
      // Turn new items on
      {
        action: 'setting',
        payload: {
          showNewItems: true,
        },
        before: {
          showNewItems: false,
        },
      },
    ];
    expect(copy(updatedState.updateQueue)).toEqual(expected);
  });

  it('can handle loadouts', () => {
    const state: DimApiState = {
      ...initialState,
      updateQueue: [
        // Save a loadout for D2
        {
          action: 'loadout',
          payload: {
            id: '1234',
            name: 'foo',
            classType: DestinyClass.Warlock,
            equipped: [],
            unequipped: [],
            clearSpace: false,
          },
          before: {
            id: '1234',
            name: 'before foo',
            classType: DestinyClass.Unknown,
            equipped: [],
            unequipped: [],
            clearSpace: false,
          },
          platformMembershipId: '3456',
          destinyVersion: 2,
        },
        // Update the name
        {
          action: 'loadout',
          payload: {
            id: '1234',
            name: 'foo',
            classType: DestinyClass.Warlock,
            equipped: [],
            unequipped: [],
            clearSpace: false,
          },
          before: {
            id: '1234',
            name: 'foobar',
            classType: DestinyClass.Warlock,
            equipped: [],
            unequipped: [],
            clearSpace: false,
          },
          platformMembershipId: '3456',
          destinyVersion: 2,
        },
        // Delete it
        {
          action: 'delete_loadout',
          payload: '1234',
          before: {
            id: '1234',
            name: 'foo',
            classType: DestinyClass.Warlock,
            equipped: [],
            unequipped: [],
            clearSpace: false,
          },
          platformMembershipId: '3456',
          destinyVersion: 2,
        } as DeleteLoadoutUpdateWithRollback,
      ],
    };

    const updatedState = dimApi(state, prepareToFlushUpdates());

    expect(updatedState.updateInProgressWatermark).toBe(1);

    // Down to a single delete, with the original loadout as the before
    const expected = [
      {
        action: 'delete_loadout',
        payload: '1234',
        before: {
          id: '1234',
          name: 'before foo',
          classType: DestinyClass.Unknown,
          equipped: [],
          unequipped: [],
          clearSpace: false,
        },
        platformMembershipId: '3456',
        destinyVersion: 2,
      },
    ];
    expect(copy(updatedState.updateQueue)).toEqual(expected);
  });

  it('can handle tag stuff', () => {
    const state: DimApiState = {
      ...initialState,
      updateQueue: [
        {
          action: 'tag',
          payload: {
            id: '1234',
            tag: 'favorite',
          },
          before: {
            id: '1234',
            tag: 'junk',
          },
          platformMembershipId: '3456',
          destinyVersion: 2,
        },
        {
          action: 'tag',
          payload: {
            id: '1234',
            notes: 'woohoo',
          },
          before: {
            id: '1234',
            tag: 'favorite',
          },
          platformMembershipId: '3456',
          destinyVersion: 2,
        },
        {
          action: 'tag',
          payload: {
            id: '1234',
            tag: null,
          },
          before: {
            id: '1234',
            tag: 'favorite',
            notes: 'woohoo',
          },
          platformMembershipId: '3456',
          destinyVersion: 2,
        },
      ],
    };

    const updatedState = dimApi(state, prepareToFlushUpdates());

    expect(updatedState.updateInProgressWatermark).toBe(1);
    const expected = [
      {
        action: 'tag',
        payload: {
          id: '1234',
          tag: null,
          notes: 'woohoo',
        },
        before: {
          id: '1234',
          tag: 'junk',
        },
        platformMembershipId: '3456',
        destinyVersion: 2,
      },
    ];
    expect(copy(updatedState.updateQueue)).toEqual(expected);
  });
});

describe('finishedUpdates', () => {
  it('can mark success', () => {
    const state: DimApiState = {
      ...initialState,
      updateQueue: [
        {
          action: 'setting',
          payload: {
            showNewItems: true,
          },
          before: {
            showNewItems: false,
          },
        },
        // Save a tag for D2
        {
          action: 'tag',
          payload: {
            id: '1234',
            tag: 'favorite',
          },
          before: {
            id: '1234',
          },
          platformMembershipId: '3456',
          destinyVersion: 2,
        },
      ],
      updateInProgressWatermark: 2,
    };
    const updatedState = dimApi(
      state,
      finishedUpdates([{ status: 'Success' }, { status: 'Success' }])
    );

    expect(updatedState.updateInProgressWatermark).toBe(0);
    expect(updatedState.updateQueue).toEqual([]);
  });
});


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: src/proto/grpc/testing/metrics.proto

namespace Grpc\Testing;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Request message containing the gauge name
 *
 * Generated from protobuf message grpc.testing.GaugeRequest
 */
class GaugeRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Generated from protobuf field string name = 1;
     */
    private $name = '';

    public function __construct() {
        \GPBMetadata\Src\Proto\Grpc\Testing\Metrics::initOnce();
        parent::__construct();
    }

    /**
     * Generated from protobuf field string name = 1;
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Generated from protobuf field string name = 1;
     * @param string $var
     * @return $this
     */
    public function setName($var)
    {
        GPBUtil::checkString($var, True);
        $this->name = $var;

        return $this;
    }

}

redpajama_set_name: RedPajamaGithub


text:
class PreprocessinatorHelper

  constructor :configurator, :test_includes_extractor, :task_invoker, :file_finder, :file_path_utils

  def preprocess_includes(test, preprocess_includes_proc)
    if (@configurator.project_use_test_preprocessor)
      preprocessed_includes_list = @file_path_utils.form_preprocessed_includes_list_filepath(test)
      preprocess_includes_proc.call( @file_finder.find_test_from_file_path(preprocessed_includes_list) )
      @test_includes_extractor.parse_includes_list(preprocessed_includes_list)
    else
      @test_includes_extractor.parse_test_file(test)
    end
  end

  def assemble_mocks_list(test)
    return @file_path_utils.form_mocks_source_filelist( @test_includes_extractor.lookup_raw_mock_list(test) )
  end

  def preprocess_mockable_headers(mock_list, preprocess_file_proc)
    if (@configurator.project_use_test_preprocessor)
      preprocess_files_smartly(
        @file_path_utils.form_preprocessed_mockable_headers_filelist(mock_list),
        preprocess_file_proc ) { |file| @file_finder.find_header_file(file) }
    end
  end

  def preprocess_test_file(test, preprocess_file_proc)
    return if (!@configurator.project_use_test_preprocessor)

    preprocess_file_proc.call(test)
  end

  private ############################

  def preprocess_files_smartly(file_list, preprocess_file_proc)
    if (@configurator.project_use_deep_dependencies)
      @task_invoker.invoke_test_preprocessed_files(file_list)
    else
      file_list.each { |file| preprocess_file_proc.call( yield(file) ) }
    end
  end

end


text: from .wtforms import *


text:
'use strict';

module.exports = {
  up: function(queryInterface, DataTypes) {
    return queryInterface
      .addColumn('Tiers', 'maxQuantityPerUser', { type: DataTypes.INTEGER })
      .then(() =>
        queryInterface.addColumn('Tiers', 'goal', { type: DataTypes.INTEGER }),
      )
      .then(() =>
        queryInterface.addColumn('Tiers', 'type', {
          type: DataTypes.STRING,
          defaultValue: 'TICKET',
        }),
      );
  },

  down: function(queryInterface) {
    return queryInterface
      .removeColumn('Tiers', 'maxQuantityPerUser')
      .then(() => queryInterface.removeColumn('Tiers', 'goal'))
      .then(() => queryInterface.removeColumn('Tiers', 'type'));
  },
};


text:
The sample source codes on this page will demonstrate you how to make gs1 datamatrix barcode in C#. ByteScout Barcode SDK helps with gs1 datamatrix barcode in C#. ByteScout Barcode SDK is the robost SDK that generates high quality barcode images and pdf. Can generate all popular types of barcodes from QR Code, Code 39, Code 128, UPC, GS1, GS-128, PDF417, Datamatrix to more exotic barcode types. Fully customizable fonts, colors, print sizes. Includes special functions to ensure output quality, and tools for adding barcodes to new or existing pdf files and images.

This rich sample source code in C# for ByteScout Barcode SDK includes the number of functions and options you should do calling the API to implement gs1 datamatrix barcode. This C# sample code should be copied and pasted into your application's code editor. Then just compile and run it to see how it works. Enjoy writing a code with ready-to-use sample C# codes to implement gs1 datamatrix barcode using ByteScout Barcode SDK.

Our website provides free trial version of ByteScout Barcode SDK. It comes along with all these source code samples with the goal to help you with your C# application implementation.

## REQUEST FREE TECH SUPPORT

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

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20Barcode%20SDK%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=REnj3A-oSPI](https://www.youtube.com/watch?v=REnj3A-oSPI)

<!-- code block begin -->

##### ****CreateBarCode.VS2005.csproj:**

```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>8.0.50727</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{A657F388-7D2A-4C05-9E04-6F6FAFF16F0C}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>CreateBarCode</RootNamespace>
    <AssemblyName>CreateBarCode</AssemblyName>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <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' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.BarCode, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\..\..\Bytescout.BarCode\Bytescout.BarCode.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****CreateBarCode.VS2008.csproj:**

```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>9.0.21022</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{A657F388-7D2A-4C05-9E04-6F6FAFF16F0C}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>CreateBarCode</RootNamespace>
    <AssemblyName>CreateBarCode</AssemblyName>
    <OldToolsVersion>2.0</OldToolsVersion>
    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <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' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.BarCode, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\..\..\Bytescout.BarCode\Bytescout.BarCode.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****CreateBarCode.VS2010.csproj:**

```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{A657F388-7D2A-4C05-9E04-6F6FAFF16F0C}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>CreateBarCode</RootNamespace>
    <AssemblyName>CreateBarCode</AssemblyName>
    <OldToolsVersion>3.5</OldToolsVersion>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <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' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.BarCode, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\..\..\Bytescout.BarCode\Bytescout.BarCode.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

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

```
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

using Bytescout.BarCode;

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create new barcode
            Barcode barcode = new Barcode();

            // Set symbology
            barcode.Symbology = SymbologyType.GS1_DataMatrix;

            // Set GS1 barcode value
            barcode.Value = "(01)03453120000011(17)291030(10)ABC123";

 	    // you may also set the value without brackets and the SDK will automatically add brackets where needed
	    // also some values may include "|" character as the additional separator (for example, GS1 Australian Post)
	    // barcode.Value = "01034531200000111729103010ABC123"; // it will be converted into "(01)03453120000011(17)291030(10)ABC123" automatically

	    // you may also optionally check if this value is valid according to GS1 subtype rules
	    // bool isValidValue = barcode.ValueIsValidGS1(barcode.Value));

            // Save barcode to image
            barcode.SaveImage("result.png");

            // Show image in default image viewer
            Process.Start("result.png");
        }
    }
}

```

<!-- code block end -->


text:
'use strict';

angular.module('baseApp')
  .controller('accountsController', ['$scope', '$http', '$q', function($scope, $http, $q) {
  var vm = this;
  vm.init = init;
  vm.accounts = [];
  vm.initOK = initOK;
  function initOK(results) {
      Parse.Cloud.run('listAccounts',{},{
      success: function(result){
          console.log(result);
      },
      error: function(error) {
        // alert("Error: " + error.code + " " + error.message);
    }});

     // alert("Successfully retrieved " + results.length);
     console.log(results[0].get('balance'));
     vm.accounts = results;
     /*for (var account in vm.accounts) {
       vm.accounts[account].iban = vm.accounts[account].get('iban');
       vm.accounts[account].name = vm.accounts[account].get('name');
       vm.accounts[account].balance = vm.accounts[account].get('balance');
     }*/

     for (var i = 0; i < vm.accounts.length; i++) {
       vm.accounts[i].iban = vm.accounts[i].get('iban');
       vm.accounts[i].name = vm.accounts[i].get('name');
       vm.accounts[i].balance = vm.accounts[i].get('balance');
     }
     console.log(vm.accounts);
     $scope.$digest();
  }
  function init(){
    var accountsDfd = $q.defer();
    var account = Parse.Object.extend("account");
    var query = new Parse.Query(account);

    query.containedIn("iban", Parse.User.current().get('accounts'));
    // ["1001"]
    query.find({
      success: vm.initOK,
      error: function(error) {
        // alert("Error: " + error.code + " " + error.message);
      }
    });

  }

/*
  var ArticleDfd = $q.defer();
  var Article = Parse.Object.extend('Article');
  var queryArticle = new Parse.Query(Article);
  queryArticle.equalTo('name', 'Angular and Parse Working Together');
  queryArticle.find().then(function (data) {
  	ArticleDfd.resolve(data);
  }, function (error) {
  	ArticleDfd.reject(data);
  });
  ArticleDfd.promise
  .then(function (article) {
  	$scope.currentArticle = article;
  })
  .catch(function (error) {
  	//do something with the error
  });

*/

}]);


text:
#ifndef itkImageRegionSplitterSlowDimension_h
#define itkImageRegionSplitterSlowDimension_h

#include "itkImageRegionSplitterBase.h"

namespace itk
{

/** \class ImageRegionSplitterSlowDimension
 * \brief Divide an image region along the slowest dimension
 *
 * ImageRegionSplitterSlowDimension divides an ImageRegion into smaller regions.
 * ImageRegionSplitterSlowDimension is the default splitter for many situations.
 *
 * This ImageRegionSplitterSlowDimension class divides a region along the
 * outermost or slowest dimension. If the outermost dimension has size
 * 1 (i.e. a volume with a single slice), the ImageRegionSplitter will
 * divide the region along the next outermost dimension. If that
 * dimension has size 1, the process continues with the next outermost
 * dimension.
 *
 * \sa ImageRegionSplitterDirection
 *
 * \ingroup ITKSystemObjects
 * \ingroup DataProcessing
 * \ingroup ITKCommon
 */

class ITKCommon_EXPORT ImageRegionSplitterSlowDimension : public ImageRegionSplitterBase
{
public:
  ITK_DISALLOW_COPY_AND_MOVE(ImageRegionSplitterSlowDimension);

  /** Standard class type aliases. */
  using Self = ImageRegionSplitterSlowDimension;
  using Superclass = ImageRegionSplitterBase;
  using Pointer = SmartPointer<Self>;
  using ConstPointer = SmartPointer<const Self>;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(ImageRegionSplitterSlowDimension, ImageRegionSplitterBase);

protected:
  ImageRegionSplitterSlowDimension();

  unsigned int
  GetNumberOfSplitsInternal(unsigned int         dim,
                            const IndexValueType regionIndex[],
                            const SizeValueType  regionSize[],
                            unsigned int         requestedNumber) const override;

  unsigned int
  GetSplitInternal(unsigned int   dim,
                   unsigned int   i,
                   unsigned int   numberOfPieces,
                   IndexValueType regionIndex[],
                   SizeValueType  regionSize[]) const override;
};
} // end namespace itk

#endif


text:
// <copyright file="IccTypeSignature.cs" company="James Jackson-South">
// Copyright (c) James Jackson-South and contributors.
// Licensed under the Apache License, Version 2.0.
// </copyright>

namespace ImageSharp
{
    /// <summary>
    /// Type Signature
    /// </summary>
    public enum IccTypeSignature : uint
    {
        /// <summary>
        /// Unknown type signature
        /// </summary>
        Unknown,

        /// <summary>
        /// The chromaticity tag type provides basic chromaticity data and type of
        /// phosphors or colorants of a monitor to applications and utilities
        /// </summary>
        Chromaticity = 0x6368726D,

        /// <summary>
        /// This is an optional tag which specifies the laydown order in which colorants
        /// will be printed on an n-colorant device. The laydown order may be the same
        /// as the channel generation order listed in the colorantTableTag or the channel
        /// order of a colour encoding type such as CMYK, in which case this tag is not
        /// needed. When this is not the case (for example, ink-towers sometimes use
        /// the order KCMY), this tag may be used to specify the laydown order of the
        /// colorants
        /// </summary>
        ColorantOrder = 0x636c726f,

        /// <summary>
        /// The purpose of this tag is to identify the colorants used in the profile
        /// by a unique name and set of PCSXYZ or PCSLAB values to give the colorant
        /// an unambiguous value. The first colorant listed is the colorant of the
        /// first device channel of a LUT tag. The second colorant listed is the
        /// colorant of the second device channel of a LUT tag, and so on
        /// </summary>
        ColorantTable = 0x636c7274,

        /// <summary>
        /// The curveType embodies a one-dimensional function which maps an input
        /// value in the domain of the function to an output value in the range
        /// of the function
        /// </summary>
        Curve = 0x63757276,

        /// <summary>
        /// The dataType is a simple data structure that contains either 7-bit ASCII
        /// or binary data
        /// </summary>
        Data = 0x64617461,

        /// <summary>
        /// Date and time defined by 6 unsigned 16bit integers
        /// (year, month, day, hour, minute, second)
        /// </summary>
        DateTime = 0x6474696D,

        /// <summary>
        /// This structure represents a colour transform using tables with 16-bit
        /// precision. This type contains four processing elements: a 3 × 3 matrix
        /// (which shall be the identity matrix unless the input colour space is
        /// PCSXYZ), a set of one-dimensional input tables, a multi-dimensional
        /// lookup table, and a set of one-dimensional output tables
        /// </summary>
        Lut16 = 0x6D667432,

        /// <summary>
        /// This structure represents a colour transform using tables of 8-bit
        /// precision. This type contains four processing elements: a 3 × 3 matrix
        /// (which shall be the identity matrix unless the input colour space is
        /// PCSXYZ), a set of one-dimensional input tables, a multi-dimensional
        /// lookup table, and a set of one-dimensional output tables.
        /// </summary>
        Lut8 = 0x6D667431,

        /// <summary>
        /// This structure represents a colour transform. The type contains up
        /// to five processing elements which are stored in the AToBTag tag
        /// in the following order: a set of one-dimensional curves, a 3 × 3
        /// matrix with offset terms, a set of one-dimensional curves, a
        /// multi-dimensional lookup table, and a set of one-dimensional
        /// output curves
        /// </summary>
        LutAToB = 0x6D414220,

        /// <summary>
        /// This structure represents a colour transform. The type contains
        /// up to five processing elements which are stored in the BToATag
        /// in the following order: a set of one-dimensional curves, a 3 × 3
        /// matrix with offset terms, a set of one-dimensional curves, a
        /// multi-dimensional lookup table, and a set of one-dimensional curves.
        /// </summary>
        LutBToA = 0x6D424120,

        /// <summary>
        /// This information refers only to the internal
        /// profile data and is meant to provide profile makers an alternative
        /// to the default measurement specifications
        /// </summary>
        Measurement = 0x6D656173,

        /// <summary>
        /// This tag structure contains a set of records each referencing a
        /// multilingual Unicode string associated with a profile. Each string
        /// is referenced in a separate record with the information about what
        /// language and region the string is for.
        /// </summary>
        MultiLocalizedUnicode = 0x6D6C7563,

        /// <summary>
        /// This structure represents a colour transform, containing a sequence
        /// of processing elements. The processing elements contained in the
        /// structure are defined in the structure itself, allowing for a flexible
        /// structure. Currently supported processing elements are: a set of one
        /// dimensional curves, a matrix with offset terms, and a multidimensional
        /// lookup table (CLUT). Other processing element types may be added in
        /// the future. Each type of processing element may be contained any
        /// number of times in the structure.
        /// </summary>
        MultiProcessElements = 0x6D706574,

        /// <summary>
        /// This type is a count value and array of structures that provide colour
        /// coordinates for colour names. For each named colour, a PCS and optional
        /// device representation of the colour are given. Both representations are
        /// 16-bit values and PCS values shall be relative colorimetric. The device
        /// representation corresponds to the header's "data colour space" field.
        /// This representation should be consistent with the "number of device
        /// coordinates" field in the namedColor2Type. If this field is 0, device
        /// coordinates are not provided. The PCS representation corresponds to the
        /// header's PCS field. The PCS representation is always provided. Colour
        /// names are fixed-length, 32-byte fields including null termination. In
        /// order to maintain maximum portability, it is strongly recommended that
        /// special characters of the 7-bit ASCII set not be used.
        /// </summary>
        NamedColor2 = 0x6E636C32,

        /// <summary>
        /// This type describes a one-dimensional curve by specifying one of a
        /// predefined set of functions using the parameters.
        /// </summary>
        ParametricCurve = 0x70617261,

        /// <summary>
        /// This type is an array of structures, each of which contains information
        /// from the header fields and tags from the original profiles which were
        /// combined to create the final profile. The order of the structures is
        /// the order in which the profiles were combined and includes a structure
        /// for the final profile. This provides a description of the profile
        /// sequence from source to destination, typically used with the DeviceLink
        /// profile.
        /// </summary>
        ProfileSequenceDesc = 0x70736571,

        /// <summary>
        /// This type is an array of structures, each of which contains information
        /// for identification of a profile used in a sequence.
        /// </summary>
        ProfileSequenceIdentifier = 0x70736964,

        /// <summary>
        /// The purpose of this tag type is to provide a mechanism to relate physical
        /// colorant amounts with the normalized device codes produced by lut8Type,
        /// lut16Type, lutAToBType, lutBToAType or multiProcessElementsType tags
        /// so that corrections can be made for variation in the device without
        /// having to produce a new profile. The mechanism can be used by applications
        /// to allow users with relatively inexpensive and readily available
        /// instrumentation to apply corrections to individual output colour
        /// channels in order to achieve consistent results.
        /// </summary>
        ResponseCurveSet16 = 0x72637332,

        /// <summary>
        /// Array of signed floating point numbers with 1 sign bit, 15 value bits and 16 fractional bits
        /// </summary>
        S15Fixed16Array = 0x73663332,

        /// <summary>
        /// The signatureType contains a 4-byte sequence. Sequences of less than four
        /// characters are padded at the end with spaces. Typically this type is used
        /// for registered tags that can be displayed on many development systems as
        /// a sequence of four characters.
        /// </summary>
        Signature = 0x73696720,

        /// <summary>
        /// Simple ASCII text
        /// </summary>
        Text = 0x74657874,

        /// <summary>
        /// Array of unsigned floating point numbers with 16 value bits and 16 fractional bits
        /// </summary>
        U16Fixed16Array = 0x75663332,

        /// <summary>
        /// Array of unsigned 16bit integers (ushort)
        /// </summary>
        UInt16Array = 0x75693136,

        /// <summary>
        /// Array of unsigned 32bit integers (uint)
        /// </summary>
        UInt32Array = 0x75693332,

        /// <summary>
        /// Array of unsigned 64bit integers (ulong)
        /// </summary>
        UInt64Array = 0x75693634,

        /// <summary>
        /// Array of unsigned 8bit integers (byte)
        /// </summary>
        UInt8Array = 0x75693038,

        /// <summary>
        /// This type represents a set of viewing condition parameters.
        /// </summary>
        ViewingConditions = 0x76696577,

        /// <summary>
        /// 3 floating point values describing a XYZ color value
        /// </summary>
        Xyz = 0x58595A20,

        /// <summary>
        /// REMOVED IN V4 - The textDescriptionType is a complex structure that contains three
        /// types of text description structures: 7-bit ASCII, Unicode and ScriptCode. Since no
        /// single standard method for specifying localizable character sets exists across
        /// the major platform vendors, including all three provides access for the major
        /// operating systems. The 7-bit ASCII description is to be an invariant,
        /// nonlocalizable name for consistent reference. It is preferred that both the
        /// Unicode and ScriptCode structures be properly localized.
        /// </summary>
        TextDescription = 0x64657363,

        /// <summary>
        /// REMOVED IN V4 - This type contains the PostScript product name to which this
        /// profile corresponds and the names of the companion CRDs
        /// </summary>
        CrdInfo = 0x63726469,

        /// <summary>
        /// REMOVED IN V4 - The screeningType describes various screening parameters including
        /// screen frequency, screening angle, and spot shape
        /// </summary>
        Screening = 0x7363726E,

        /// <summary>
        /// REMOVED IN V4 - This type contains curves representing the under color removal and
        /// black generation and a text string which is a general description of the method
        /// used for the UCR and BG
        /// </summary>
        UcrBg = 0x62666420,

        /// <summary>
        /// REMOVED IN V4 - This type is an array of structures each of which contains
        /// platform-specific information about the settings of the device for which
        /// this profile is valid. This type is not supported.
        /// </summary>
        DeviceSettings = 0x64657673,        // not supported

        /// <summary>
        /// REMOVED IN V2 - use <see cref="NamedColor2"/> instead. This type is not supported.
        /// </summary>
        NamedColor = 0x6E636F6C,            // not supported
    }
}


text:
package org.apache.camel.component.jira.oauth;

import com.google.api.client.auth.oauth.OAuthGetAccessToken;

public class JiraOAuthGetAccessToken extends OAuthGetAccessToken {

    public JiraOAuthGetAccessToken(String authorizationServerUrl) {
        super(authorizationServerUrl);
        // use POST http method
        this.usePost = true;
    }

}


text:
package bin.fract;

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

import com.google.common.primitives.Chars;

public class Converter {

    private List<Double> powersOfTwo;

    public Converter(List<Double> powersOfTwo) {
        this.powersOfTwo = powersOfTwo;
    }

    public Double convertToDecimal(String binaryFraction) {
        List<Integer> splitBinaryFraction = splitBinaryFraction(binaryFraction);
        Double result = 0d;

        for (int i = 0; i < splitBinaryFraction.size(); i++) {
            result += splitBinaryFraction.get(i) * powersOfTwo.get(i);
        }

        return result;
    }

    public String convertToBinary(double decimalFraction) {
        StringBuilder result = new StringBuilder();
        int integerPart = (int) Math.floor(decimalFraction);
        result = getNextIntegerBit(result, integerPart);
        result = result.append(".");
        result = getNextFractionalBit(result, decimalFraction - integerPart);

        // I'm too lazy to convert result for better representation of repeating decimals. So sorry :).
        return result.toString();
    }

    private List<Integer> splitBinaryFraction(String binaryFraction) {
        int i = binaryFraction.indexOf(".");
        String numbersAfterPoint = binaryFraction.substring(i + 1);
        List<Integer> splitBinaryFraction = new ArrayList<>();

        Chars.asList(numbersAfterPoint.toCharArray()).forEach(c -> splitBinaryFraction.add(new Integer(c.toString())));
        return splitBinaryFraction;
    }

    private StringBuilder getNextFractionalBit(StringBuilder result, double fractionalPart) {
        if (fractionalPart == 0) {
            return result.append(String.valueOf((int)fractionalPart));
        }

        double multiplicationResult = fractionalPart * 2;
        double floor = Math.floor(multiplicationResult);
        double rest = multiplicationResult - floor;
        result = result.append(String.valueOf((int) floor));
        if (multiplicationResult != 1) {
            return getNextFractionalBit(result, rest);
        }

        return result;
    }

    private StringBuilder getNextIntegerBit(StringBuilder result, int integerPart) {
        int modulo = integerPart % 2;
        int division = integerPart / 2;
        result = result.append(String.valueOf(modulo));
        if (division != 0) {
            return getNextIntegerBit(result, division);
        }

        return result.reverse();
    }
}


text:
package com.gs.fw.common.mithra.finder.floatop;

import com.gs.fw.common.mithra.attribute.FloatAttribute;
import com.gs.fw.common.mithra.extractor.Extractor;
import com.gs.fw.common.mithra.extractor.FloatExtractor;
import com.gs.fw.common.mithra.finder.AtomicNotEqualityOperation;
import com.gs.fw.common.mithra.finder.SqlParameterSetter;
import com.gs.fw.common.mithra.finder.SqlQuery;
import com.gs.fw.common.mithra.finder.paramop.OpWithFloatParam;
import com.gs.fw.common.mithra.finder.paramop.OpWithFloatParamExtractor;
import com.gs.fw.common.mithra.util.HashUtil;

import java.sql.PreparedStatement;
import java.sql.SQLException;

public class FloatNotEqOperation  extends AtomicNotEqualityOperation implements SqlParameterSetter, OpWithFloatParam
{
    private float parameter;

    public FloatNotEqOperation(FloatAttribute attribute, float parameter)
    {
        super(attribute);
        this.parameter = parameter;
    }

    @Override
    protected Extractor getStaticExtractor()
    {
        return OpWithFloatParamExtractor.INSTANCE;
    }

    protected boolean matchesWithoutDeleteCheck(Object o, Extractor extractor)
    {
        FloatExtractor floatAttribute = (FloatExtractor) extractor;
        if (floatAttribute.isAttributeNull(o)) return false;
        return floatAttribute.floatValueOf(o) != parameter;
    }

    public int setSqlParameters(PreparedStatement pstmt, int startIndex, SqlQuery query) throws SQLException
    {
        pstmt.setFloat(startIndex, parameter);
        return 1;
    }

    public int hashCode()
    {
        return ~(this.getAttribute().hashCode() ^ HashUtil.hash(this.parameter));
    }

    public boolean equals(Object obj)
    {
        if (obj == this) return true;
        if (obj instanceof FloatNotEqOperation)
        {
            FloatNotEqOperation other = (FloatNotEqOperation) obj;
            return this.parameter == other.parameter && this.getAttribute().equals(other.getAttribute());
        }
        return false;
    }

    public Object getParameterAsObject()
    {
        return new Float(this.parameter);
    }

    public float getParameter()
    {
        return parameter;
    }
}


text:
import extractUrlsWithIndices from './extractUrlsWithIndices';

export default function(text, options) {
  const urlsOnly = [];
  const urlsWithIndices = extractUrlsWithIndices(text, options);

  for (let i = 0; i < urlsWithIndices.length; i++) {
    urlsOnly.push(urlsWithIndices[i].url);
  }

  return urlsOnly;
}


text:
package de.ailis.maven.plugin.javascript;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.codehaus.plexus.util.StringUtils;

import com.google.javascript.jscomp.SourceFile;

/**
 * Parses dependencies from a source file.
 *
 * @author Klaus Reimer (k@ailis.de)
 */
public class DependencyManager {
    /** Regular expression to match @require annotation */
    private static final Pattern REQUIRE_REGEX = Pattern
        .compile("(?m)^\\s*\\*\\s*[%@]require\\s+([a-zA-Z0-9\\/\\-\\.]+)\\s*$");

    /** Regular expression to match @use annotation */
    private static final Pattern USE_REGEX = Pattern.compile("(?m)^\\s*\\*\\s*[%@]use\\s+([a-zA-Z0-9\\/\\-\\.]+)\\s*$");

    /** Regular expression to match @nobundle annotation */
    private static final Pattern NOBUNDLE_REGEX = Pattern.compile("(?m)^\\s*\\*\\s*[%@]nobundle\\s*$");

    /** List of dependencies per script filename. */
    private final Map<String, List<Dependency>> scriptDependencies = new HashMap<>();

    /** List of script files which must not be bundled. */
    private final Set<String> noBundles = new HashSet<>();

    /** List of provided files. */
    private final Set<String> provided = new HashSet<>();

    /** The absolute source directory as string with trailing slash. */
    private final String sourceDirectory;

    /** The order of the resolved dependencies. */
    private final List<String> order = new ArrayList<>();

    /** The included dependencies. */
    private final Set<String> included = new HashSet<>();

    /** The resolve stack. */
    private final Stack<String> stack = new Stack<>();

    /** The used dependencies. */
    private final Set<String> used = new HashSet<>();

    /**
     * Constructor.
     *
     * @param sourceDirectory
     *            The source directory.
     */
    public DependencyManager(final File sourceDirectory) {
        this.sourceDirectory = sourceDirectory.getAbsolutePath() + File.separatorChar;
    }

    /**
     * Adds the specified JavaScript source file
     *
     * @param file
     *            The JavaScript source file to add. Must not be null.
     * @throws IOException
     *             If JavaScript source file was not found.
     */
    public void addScript(final SourceFile file) throws IOException {
        final List<Dependency> dependencies = new ArrayList<>();
        final String code = file.getCode();
        final String filename = getFilename(file);

        Matcher matcher = NOBUNDLE_REGEX.matcher(code);
        if (matcher.find()) {
            this.noBundles.add(filename);
        } else {
            this.provided.add(filename);
        }

        matcher = REQUIRE_REGEX.matcher(code);
        while (matcher.find()) {
            dependencies.add(new Dependency(matcher.group(1), true));
        }

        matcher = USE_REGEX.matcher(code);
        while (matcher.find()) {
            dependencies.add(new Dependency(matcher.group(1), false));
        }

        this.scriptDependencies.put(filename, dependencies);
    }

    /**
     * Returns the filename of the specified file.
     *
     * @param file
     *            The JavaScript source file.
     * @return The filename.
     */
    private String getFilename(final SourceFile file) {
        return file.getName().replace(this.sourceDirectory, "").replace("\\", "/");
    }

    /**
     * Adds the specified JavaScript source files.
     *
     * @param files
     *            The JavaScript source files to add. Must not be null.
     * @throws IOException
     *             If JavaScript source file was not found.
     */
    public void addScripts(final List<SourceFile> files) throws IOException {
        for (final SourceFile file : files) {
            addScript(file);
        }
    }

    /**
     * Returns the dependencies of the specified file.
     *
     * @param file
     *            The JavaScript source file.
     * @return The dependencies. Never null. May be empty.
     * @throws IllegalArgumentException
     *             When specified file was not added to the dependency manager first.
     */
    public List<Dependency> getDependencies(final SourceFile file) {
        final List<Dependency> dependencies = this.scriptDependencies.get(getFilename(file));
        if (dependencies == null) {
            throw new IllegalArgumentException("File " + file + " is unknown to script dependency manager");
        }
        return dependencies;
    }

    /**
     * Returns the external dependencies.
     *
     * @return The external dependencies. Never null. May be empty.
     */
    public Set<Dependency> getExternalDependencies() {
        final Set<Dependency> externalDependencies = new HashSet<>();
        for (final Map.Entry<String, List<Dependency>> entry : this.scriptDependencies.entrySet()) {
            // Do not process files which are not included in the bundle
            if (isNoBundle(entry.getKey())) {
                continue;
            }

            final List<Dependency> dependencies = entry.getValue();
            for (final Dependency dependency : dependencies) {
                final String filename = dependency.getFilename();
                if (!this.provided.contains(filename)) {
                    externalDependencies.add(dependency);
                }
            }
        }
        return externalDependencies;
    }

    /**
     * Returns the provided dependencies.
     *
     * @return The provided dependencies. Never null. May be empty.
     */
    public Set<String> getProvidedDependencies() {
        return Collections.unmodifiableSet(this.provided);
    }

    /**
     * Resolves the dependencies and returns a list with the correctly ordered files.
     *
     * @return The list with ordered files.
     * @throws CircularDependencyException
     *             When a circular dependency was found.
     */
    public List<String> resolve() {
        this.order.clear();
        this.stack.clear();
        this.used.clear();
        this.included.clear();
        for (final String name : this.scriptDependencies.keySet()) {
            includeScript(name);
        }
        return this.order;
    }

    /**
     * Dependency resolving: Includes the specified script.
     *
     * @param filename
     *            The script to include
     */
    private void includeScript(final String filename) {
        // Ignore script if already included
        if (this.included.contains(filename)) {
            return;
        }

        // Check for circular dependencies
        if (this.stack.contains(filename)) {
            throw new CircularDependencyException("Circular dependency detected: "
                + StringUtils.join(this.stack.iterator(), " > ") + " > " + filename, this.sourceDirectory + filename);
        }
        this.stack.push(filename);

        // Process the script
        processScript(filename);
        this.order.add((this.sourceDirectory + filename).replace("\\", "/"));

        // Mark script as included
        this.included.add(filename);
        this.stack.pop();

        if (this.stack.isEmpty()) {
            finish();
        }
    }

    /**
     * Dependency resolving: Uses the specified script.
     *
     * @param filename
     *            The script to use
     */
    private void useScript(final String filename) {
        if (this.included.contains(filename)) {
            return;
        }
        if (this.used.contains(filename)) {
            return;
        }
        this.used.add(filename);
    }

    /**
     * Dependency resolving: Finishes the resolving.
     */
    private void finish() {
        if (this.used.isEmpty()) {
            return;
        }
        final Set<String> used = new HashSet<>(this.used);
        this.used.clear();
        for (final String use : used) {
            includeScript(use);
        }
        finish();
    }

    /**
     * Dependency resolving: processes a script and its dependencies.
     *
     * @param filename
     *            The script to process
     */
    private void processScript(final String filename) {
        final List<Dependency> dependencies = this.scriptDependencies.get(filename);

        if (dependencies != null) {
            for (final Dependency dependency : dependencies) {
                if (dependency.isRequired()) {
                    includeScript(dependency.getFilename());
                }
            }
            for (final Dependency dependency : dependencies) {
                if (!dependency.isRequired()) {
                    useScript(dependency.getFilename());
                }
            }
        }
    }

    /**
     * Checks if the specified source file must not be bundled.
     *
     * @param sourceFile
     *            The source file to check.
     * @return True if file must not be bundled, false if it can be bundled.
     */
    public boolean isNoBundle(final SourceFile sourceFile) {
        return isNoBundle(getFilename(sourceFile));
    }

    /**
     * Checks if the specified source file must not be bundled.
     *
     * @param filename
     *            The filename (relative to source directrory) of the source file to check.
     * @return True if file must not be bundled, false if it can be bundled.
     */
    public boolean isNoBundle(final String filename) {
        return this.noBundles.contains(filename);
    }
}


text:
package api

func (c *Sys) Renew(id string, increment int) (*Secret, error) {
	r := c.c.NewRequest("PUT", "/v1/sys/renew/"+id)

	body := map[string]interface{}{"increment": increment}
	if err := r.SetJSONBody(body); err != nil {
		return nil, err
	}

	resp, err := c.c.RawRequest(r)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	return ParseSecret(resp.Body)
}

func (c *Sys) Revoke(id string) error {
	r := c.c.NewRequest("PUT", "/v1/sys/revoke/"+id)
	resp, err := c.c.RawRequest(r)
	if err == nil {
		defer resp.Body.Close()
	}
	return err
}

func (c *Sys) RevokePrefix(id string) error {
	r := c.c.NewRequest("PUT", "/v1/sys/revoke-prefix/"+id)
	resp, err := c.c.RawRequest(r)
	if err == nil {
		defer resp.Body.Close()
	}
	return err
}


text:
require "rails_helper"

RSpec.describe SendEmailToSupplierJob, type: :job do
  include ActiveJob::TestHelper

  let(:product) { create(:product) }

  it "checking job class name" do
    expect { SendEmailToSupplierJob.perform_later }
      .to have_enqueued_job(SendEmailToSupplierJob)
  end

  it "checking job enqueued time" do
    expect { SendEmailToSupplierJob.perform_later }
      .to have_enqueued_job.on_queue("emails")
  end

  it "checking passed arguments to job" do
    expect { SendEmailToSupplierJob.perform_later(product) }
      .to have_enqueued_job.with(product)
  end

  it "executes perform" do
    SupplierMailer.registered_product(product).deliver_now
    perform_enqueued_jobs { SendEmailToSupplierJob.perform_later(product) }
  end

  it "handles no results error" do
    allow(SupplierMailer).to receive(:registered_product).and_raise(Timeout::Error)

    perform_enqueued_jobs do
      expect_any_instance_of(SendEmailToSupplierJob)
        .to receive(:retry_job).with(wait: 1.minutes, queue: :high_priority)

      SendEmailToSupplierJob.perform_later(product)
    end
  end
end


text:
<?php

namespace yii\console;

use Yii;
use yii\base\ErrorException;
use yii\base\UserException;
use yii\helpers\Console;

/**
 * ErrorHandler handles uncaught PHP errors and exceptions.
 *
 * ErrorHandler is configured as an application component in [[\yii\base\Application]] by default.
 * You can access that instance via `Yii::$app->errorHandler`.
 *
 * @author Carsten Brandt <mail@cebe.cc>
 * @since  2.0
 */
class ErrorHandler extends \yii\base\ErrorHandler
{
    /**
     * Renders an exception using ansi format for console output.
     * @param \Exception $exception the exception to be rendered.
     */
    protected function renderException($exception)
    {
        if ($exception instanceof Exception && ($exception instanceof UserException || !YII_DEBUG)) {
            $message = $this->formatMessage($exception->getName() . ': ') . $exception->getMessage();
        } elseif (YII_DEBUG) {
            if ($exception instanceof Exception) {
                $message = $this->formatMessage("Exception ({$exception->getName()})");
            } elseif ($exception instanceof ErrorException) {
                $message = $this->formatMessage($exception->getName());
            } else {
                $message = $this->formatMessage('Exception');
            }
            $message .= $this->formatMessage(" '" . get_class($exception) . "'", [Console::BOLD, Console::FG_BLUE])
                . " with message " . $this->formatMessage("'{$exception->getMessage()}'", [Console::BOLD]) //. "\n"
                . "\n\nin " . dirname($exception->getFile()) . DIRECTORY_SEPARATOR . $this->formatMessage(basename($exception->getFile()), [Console::BOLD])
                . ':' . $this->formatMessage($exception->getLine(), [Console::BOLD, Console::FG_YELLOW]) . "\n";
            if ($exception instanceof \yii\db\Exception && !empty($exception->errorInfo)) {
                $message .= "\n" . $this->formatMessage("Error Info:\n", [Console::BOLD]) . print_r($exception->errorInfo, true);
            }
            $message .= "\n" . $this->formatMessage("Stack trace:\n", [Console::BOLD]) . $exception->getTraceAsString();
        } else {
            $message = $this->formatMessage('Error: ') . $exception->getMessage();
        }

        if (PHP_SAPI === 'cli') {
            Console::stderr($message . "\n");
        } else {
            echo $message . "\n";
        }
    }

    /**
     * Colorizes a message for console output.
     * @param string $message the message to colorize.
     * @param array  $format  the message format.
     * @return string the colorized message.
     * @see Console::ansiFormat() for details on how to specify the message format.
     */
    protected function formatMessage($message, $format = [Console::FG_RED, Console::BOLD])
    {
        $stream = (PHP_SAPI === 'cli') ? \STDERR : \STDOUT;
        // try controller first to allow check for --color switch
        if (Yii::$app->controller instanceof \yii\console\Controller && Yii::$app->controller->isColorEnabled($stream)
            || Yii::$app instanceof \yii\console\Application && Console::streamSupportsAnsiColors($stream)
        ) {
            $message = Console::ansiFormat($message, $format);
        }

        return $message;
    }
}


text:
package org.kie.workbench.common.stunner.core.graph.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Utility class that allows working with functional programming and streams easier when having exceptions.
 */
public class Exceptions {

    /**
     * The same as {@link java.util.function.Supplier} but supports throwing Exceptions.
     * @param <T>
     */
    @FunctionalInterface
    public interface Supplier<T> {
        T get() throws Exception;
    }

    private static final Logger LOGGER = LoggerFactory.getLogger(Exceptions.class);

    public static <T> T swallow(final Supplier<T> supplier, final T defaultReturn) {
        try {
            return supplier.get();
        } catch (Exception e) {
            LOGGER.info("Exception swallowed", e);
            return defaultReturn;
        }
    }
}


text:
define(function () {
	"use strict";

	var AboutController = function($scope, $translate) {
		$scope.about = $translate("about.sampletext");
	};

	AboutController.$inject = ["$scope", "$translate"];

	return AboutController;
});


text:
module Bosh::Director
  module DeploymentPlan
    module Steps
      class AttachDiskStep
        def initialize(disk, tags)
          @disk = disk
          @logger = Config.logger
          @tags = tags
        end

        def perform(_report)
          return if @disk.nil?

          instance_active_vm = @disk.instance.active_vm
          return if instance_active_vm.nil?

          cloud_factory = CloudFactory.create
          attach_disk_cloud = cloud_factory.get(@disk.cpi, instance_active_vm.stemcell_api_version)
          @logger.info("Attaching disk #{@disk.disk_cid}")
          attach_disk_cloud.attach_disk(@disk.instance.vm_cid, @disk.disk_cid)

          metadata_updater_cloud = cloud_factory.get(@disk.cpi)
          MetadataUpdater.build.update_disk_metadata(metadata_updater_cloud, @disk, @tags)
        end
      end
    end
  end
end


text:
package io.digdag.server.auth;

import com.google.inject.Inject;
import io.digdag.client.config.Config;
import io.digdag.client.config.ConfigFactory;
import io.digdag.spi.Authenticator;
import io.digdag.spi.AuthenticatorFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BasicAuthenticatorFactory
        implements AuthenticatorFactory
{
    private static final Logger logger = LoggerFactory.getLogger(BasicAuthenticatorFactory.class);

    private final Config systemConfig;
    private final ConfigFactory cf;

    @Inject
    public BasicAuthenticatorFactory(Config systemConfig, ConfigFactory cf)
    {
        this.systemConfig = systemConfig;
        this.cf = cf;
    }

    @Override
    public String getType()
    {
        return "basic";
    }

    @Override
    public Authenticator newAuthenticator()
    {
        if (systemConfig.has("basicauth.username")) {
            logger.warn("Setting basicauth.username or basicauth.password works but is deprecated. It is going to be removed in a near future version. Use server.authenticator.basic.username and server.authenticator.basic.password instead.");
            return new BasicAuthenticator(cf,
                    systemConfig.get("basicauth.username", String.class),
                    systemConfig.get("basicauth.password", String.class),
                    systemConfig.get("basicauth.admin", boolean.class, false));
        }
        else if (systemConfig.has("server.authenticator.basic.username")) {
            return new BasicAuthenticator(cf,
                    systemConfig.get("server.authenticator.basic.username", String.class),
                    systemConfig.get("server.authenticator.basic.password", String.class),
                    systemConfig.get("server.authenticator.basic.admin", boolean.class, false));
        }
        else {
            return new NoAuthenticator(cf);
        }
    }
}


text:
package kubelet

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/http/httputil"
	"reflect"
	"strings"
	"testing"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	"github.com/google/cadvisor/info"
)

type fakeKubelet struct {
	infoFunc          func(name string) (api.PodInfo, error)
	containerInfoFunc func(podFullName, containerName string, req *info.ContainerInfoRequest) (*info.ContainerInfo, error)
	rootInfoFunc      func(query *info.ContainerInfoRequest) (*info.ContainerInfo, error)
	machineInfoFunc   func() (*info.MachineInfo, error)
	logFunc           func(w http.ResponseWriter, req *http.Request)
	runFunc           func(podFullName, uuid, containerName string, cmd []string) ([]byte, error)
	containerLogsFunc func(podFullName, containerName, tail string, follow bool, stdout, stderr io.Writer) error
}

func (fk *fakeKubelet) GetPodInfo(name, uuid string) (api.PodInfo, error) {
	return fk.infoFunc(name)
}

func (fk *fakeKubelet) GetContainerInfo(podFullName, uuid, containerName string, req *info.ContainerInfoRequest) (*info.ContainerInfo, error) {
	return fk.containerInfoFunc(podFullName, containerName, req)
}

func (fk *fakeKubelet) GetRootInfo(req *info.ContainerInfoRequest) (*info.ContainerInfo, error) {
	return fk.rootInfoFunc(req)
}

func (fk *fakeKubelet) GetMachineInfo() (*info.MachineInfo, error) {
	return fk.machineInfoFunc()
}

func (fk *fakeKubelet) ServeLogs(w http.ResponseWriter, req *http.Request) {
	fk.logFunc(w, req)
}

func (fk *fakeKubelet) GetKubeletContainerLogs(podFullName, containerName, tail string, follow bool, stdout, stderr io.Writer) error {
	return fk.containerLogsFunc(podFullName, containerName, tail, follow, stdout, stderr)
}

func (fk *fakeKubelet) RunInContainer(podFullName, uuid, containerName string, cmd []string) ([]byte, error) {
	return fk.runFunc(podFullName, uuid, containerName, cmd)
}

type serverTestFramework struct {
	updateChan      chan interface{}
	updateReader    *channelReader
	serverUnderTest *Server
	fakeKubelet     *fakeKubelet
	testHTTPServer  *httptest.Server
}

func newServerTest() *serverTestFramework {
	fw := &serverTestFramework{
		updateChan: make(chan interface{}),
	}
	fw.updateReader = startReading(fw.updateChan)
	fw.fakeKubelet = &fakeKubelet{}
	server := NewServer(fw.fakeKubelet, fw.updateChan, true)
	fw.serverUnderTest = &server
	fw.testHTTPServer = httptest.NewServer(fw.serverUnderTest)
	return fw
}

func readResp(resp *http.Response) (string, error) {
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	return string(body), err
}

func TestContainer(t *testing.T) {
	fw := newServerTest()
	expected := []api.ContainerManifest{
		{
			ID:   "test_manifest",
			UUID: "value",
			Containers: []api.Container{
				{
					Name: "container",
				},
			},
			Volumes: []api.Volume{
				{
					Name: "test",
				},
			},
			RestartPolicy: api.RestartPolicy{
				Never: &api.RestartPolicyNever{},
			},
		},
	}
	body := bytes.NewBuffer([]byte(util.EncodeJSON(expected[0]))) // Only send a single ContainerManifest
	resp, err := http.Post(fw.testHTTPServer.URL+"/container", "application/json", body)
	if err != nil {
		t.Errorf("Post returned: %v", err)
	}
	resp.Body.Close()
	close(fw.updateChan)
	received := fw.updateReader.GetList()
	if len(received) != 1 {
		t.Errorf("Expected 1 manifest, but got %v", len(received))
	}
	expectedPods := []api.BoundPod{
		{
			TypeMeta: api.TypeMeta{
				ID:  "test_manifest",
				UID: "value",
			},
			Spec: api.PodSpec{
				Containers: []api.Container{
					{
						Name: "container",
					},
				},
				Volumes: []api.Volume{
					{
						Name: "test",
					},
				},
				RestartPolicy: api.RestartPolicy{
					Never: &api.RestartPolicyNever{},
				},
			},
		},
	}
	if !reflect.DeepEqual(expectedPods, received[0]) {
		t.Errorf("Expected %#v, but got %#v", expectedPods, received[0])
	}
}

func TestContainers(t *testing.T) {
	fw := newServerTest()
	expected := []api.ContainerManifest{
		{
			ID: "test_manifest_1",
			Containers: []api.Container{
				{
					Name: "container",
				},
			},
			Volumes: []api.Volume{
				{
					Name: "test",
				},
			},
			RestartPolicy: api.RestartPolicy{
				Never: &api.RestartPolicyNever{},
			},
		},
		{
			ID: "test_manifest_2",
			Containers: []api.Container{
				{
					Name: "container2",
				},
			},
			Volumes: []api.Volume{
				{
					Name: "test2",
				},
			},
			RestartPolicy: api.RestartPolicy{
				Never: &api.RestartPolicyNever{},
			},
		},
	}
	body := bytes.NewBuffer([]byte(util.EncodeJSON(expected)))
	resp, err := http.Post(fw.testHTTPServer.URL+"/containers", "application/json", body)
	if err != nil {
		t.Errorf("Post returned: %v", err)
	}
	resp.Body.Close()
	close(fw.updateChan)
	received := fw.updateReader.GetList()
	if len(received) != 1 {
		t.Errorf("Expected 1 update, but got %v", len(received))
	}
	expectedPods := []api.BoundPod{
		{
			TypeMeta: api.TypeMeta{
				ID: "1",
			},
			Spec: api.PodSpec{
				Containers: []api.Container{
					{
						Name: "container",
					},
				},
				Volumes: []api.Volume{
					{
						Name: "test",
					},
				},
				RestartPolicy: api.RestartPolicy{
					Never: &api.RestartPolicyNever{},
				},
			},
		},
		{
			TypeMeta: api.TypeMeta{
				ID: "2",
			},
			Spec: api.PodSpec{
				Containers: []api.Container{
					{
						Name: "container2",
					},
				},
				Volumes: []api.Volume{
					{
						Name: "test2",
					},
				},
				RestartPolicy: api.RestartPolicy{
					Never: &api.RestartPolicyNever{},
				},
			},
		},
	}
	if !reflect.DeepEqual(expectedPods, received[0]) {
		t.Errorf("Expected %#v, but got %#v", expectedPods, received[0])
	}
}

func TestPodInfo(t *testing.T) {
	fw := newServerTest()
	expected := api.PodInfo{
		"goodpod": api.ContainerStatus{},
	}
	fw.fakeKubelet.infoFunc = func(name string) (api.PodInfo, error) {
		if name == "goodpod.default.etcd" {
			return expected, nil
		}
		return nil, fmt.Errorf("bad pod %s", name)
	}
	resp, err := http.Get(fw.testHTTPServer.URL + "/podInfo?podID=goodpod&podNamespace=default")
	if err != nil {
		t.Errorf("Got error GETing: %v", err)
	}
	got, err := readResp(resp)
	if err != nil {
		t.Errorf("Error reading body: %v", err)
	}
	expectedBytes, err := json.Marshal(expected)
	if err != nil {
		t.Fatalf("Unexpected marshal error %v", err)
	}
	if got != string(expectedBytes) {
		t.Errorf("Expected: '%v', got: '%v'", expected, got)
	}
}

func TestContainerInfo(t *testing.T) {
	fw := newServerTest()
	expectedInfo := &info.ContainerInfo{}
	podID := "somepod"
	expectedPodID := "somepod" + ".default.etcd"
	expectedContainerName := "goodcontainer"
	fw.fakeKubelet.containerInfoFunc = func(podID, containerName string, req *info.ContainerInfoRequest) (*info.ContainerInfo, error) {
		if podID != expectedPodID || containerName != expectedContainerName {
			return nil, fmt.Errorf("bad podID or containerName: podID=%v; containerName=%v", podID, containerName)
		}
		return expectedInfo, nil
	}

	resp, err := http.Get(fw.testHTTPServer.URL + fmt.Sprintf("/stats/%v/%v", podID, expectedContainerName))
	if err != nil {
		t.Fatalf("Got error GETing: %v", err)
	}
	defer resp.Body.Close()
	var receivedInfo info.ContainerInfo
	err = json.NewDecoder(resp.Body).Decode(&receivedInfo)
	if err != nil {
		t.Fatalf("received invalid json data: %v", err)
	}
	if !reflect.DeepEqual(&receivedInfo, expectedInfo) {
		t.Errorf("received wrong data: %#v", receivedInfo)
	}
}

func TestRootInfo(t *testing.T) {
	fw := newServerTest()
	expectedInfo := &info.ContainerInfo{}
	fw.fakeKubelet.rootInfoFunc = func(req *info.ContainerInfoRequest) (*info.ContainerInfo, error) {
		return expectedInfo, nil
	}

	resp, err := http.Get(fw.testHTTPServer.URL + "/stats")
	if err != nil {
		t.Fatalf("Got error GETing: %v", err)
	}
	defer resp.Body.Close()
	var receivedInfo info.ContainerInfo
	err = json.NewDecoder(resp.Body).Decode(&receivedInfo)
	if err != nil {
		t.Fatalf("received invalid json data: %v", err)
	}
	if !reflect.DeepEqual(&receivedInfo, expectedInfo) {
		t.Errorf("received wrong data: %#v", receivedInfo)
	}
}

func TestMachineInfo(t *testing.T) {
	fw := newServerTest()
	expectedInfo := &info.MachineInfo{
		NumCores:       4,
		MemoryCapacity: 1024,
	}
	fw.fakeKubelet.machineInfoFunc = func() (*info.MachineInfo, error) {
		return expectedInfo, nil
	}

	resp, err := http.Get(fw.testHTTPServer.URL + "/spec")
	if err != nil {
		t.Fatalf("Got error GETing: %v", err)
	}
	defer resp.Body.Close()
	var receivedInfo info.MachineInfo
	err = json.NewDecoder(resp.Body).Decode(&receivedInfo)
	if err != nil {
		t.Fatalf("received invalid json data: %v", err)
	}
	if !reflect.DeepEqual(&receivedInfo, expectedInfo) {
		t.Errorf("received wrong data: %#v", receivedInfo)
	}
}

func TestServeLogs(t *testing.T) {
	fw := newServerTest()

	content := string(`<pre><a href="kubelet.log">kubelet.log</a><a href="google.log">google.log</a></pre>`)

	fw.fakeKubelet.logFunc = func(w http.ResponseWriter, req *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Header().Add("Content-Type", "text/html")
		w.Write([]byte(content))
	}

	resp, err := http.Get(fw.testHTTPServer.URL + "/logs/")
	if err != nil {
		t.Fatalf("Got error GETing: %v", err)
	}
	defer resp.Body.Close()

	body, err := httputil.DumpResponse(resp, true)
	if err != nil {
		// copying the response body did not work
		t.Errorf("Cannot copy resp: %#v", err)
	}
	result := string(body)
	if !strings.Contains(result, "kubelet.log") || !strings.Contains(result, "google.log") {
		t.Errorf("Received wrong data: %s", result)
	}
}

func TestServeRunInContainer(t *testing.T) {
	fw := newServerTest()
	output := "foo bar"
	podNamespace := "other"
	podName := "foo"
	expectedPodName := podName + "." + podNamespace + ".etcd"
	expectedContainerName := "baz"
	expectedCommand := "ls -a"
	fw.fakeKubelet.runFunc = func(podFullName, uuid, containerName string, cmd []string) ([]byte, error) {
		if podFullName != expectedPodName {
			t.Errorf("expected %s, got %s", expectedPodName, podFullName)
		}
		if containerName != expectedContainerName {
			t.Errorf("expected %s, got %s", expectedContainerName, containerName)
		}
		if strings.Join(cmd, " ") != expectedCommand {
			t.Errorf("expected: %s, got %v", expectedCommand, cmd)
		}

		return []byte(output), nil
	}

	resp, err := http.Get(fw.testHTTPServer.URL + "/run/" + podNamespace + "/" + podName + "/" + expectedContainerName + "?cmd=ls%20-a")

	if err != nil {
		t.Fatalf("Got error GETing: %v", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// copying the response body did not work
		t.Errorf("Cannot copy resp: %#v", err)
	}
	result := string(body)
	if result != output {
		t.Errorf("expected %s, got %s", output, result)
	}
}

func TestServeRunInContainerWithUUID(t *testing.T) {
	fw := newServerTest()
	output := "foo bar"
	podNamespace := "other"
	podName := "foo"
	expectedPodName := podName + "." + podNamespace + ".etcd"
	expectedUuid := "7e00838d_-_3523_-_11e4_-_8421_-_42010af0a720"
	expectedContainerName := "baz"
	expectedCommand := "ls -a"
	fw.fakeKubelet.runFunc = func(podFullName, uuid, containerName string, cmd []string) ([]byte, error) {
		if podFullName != expectedPodName {
			t.Errorf("expected %s, got %s", expectedPodName, podFullName)
		}
		if uuid != expectedUuid {
			t.Errorf("expected %s, got %s", expectedUuid, uuid)
		}
		if containerName != expectedContainerName {
			t.Errorf("expected %s, got %s", expectedContainerName, containerName)
		}
		if strings.Join(cmd, " ") != expectedCommand {
			t.Errorf("expected: %s, got %v", expectedCommand, cmd)
		}

		return []byte(output), nil
	}

	resp, err := http.Get(fw.testHTTPServer.URL + "/run/" + podNamespace + "/" + podName + "/" + expectedUuid + "/" + expectedContainerName + "?cmd=ls%20-a")

	if err != nil {
		t.Fatalf("Got error GETing: %v", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// copying the response body did not work
		t.Errorf("Cannot copy resp: %#v", err)
	}
	result := string(body)
	if result != output {
		t.Errorf("expected %s, got %s", output, result)
	}
}

func TestContainerLogs(t *testing.T) {
	fw := newServerTest()
	output := "foo bar"
	podNamespace := "other"
	podName := "foo"
	expectedPodName := podName + ".other.etcd"
	expectedContainerName := "baz"
	expectedTail := ""
	expectedFollow := false
	fw.fakeKubelet.containerLogsFunc = func(podFullName, containerName, tail string, follow bool, stdout, stderr io.Writer) error {
		if podFullName != expectedPodName {
			t.Errorf("expected %s, got %s", expectedPodName, podFullName)
		}
		if containerName != expectedContainerName {
			t.Errorf("expected %s, got %s", expectedContainerName, containerName)
		}
		if tail != expectedTail {
			t.Errorf("expected %s, got %s", expectedTail, tail)
		}
		if follow != expectedFollow {
			t.Errorf("expected %t, got %t", expectedFollow, follow)
		}
		return nil
	}
	resp, err := http.Get(fw.testHTTPServer.URL + "/containerLogs/" + podNamespace + "/" + podName + "/" + expectedContainerName)
	if err != nil {
		t.Errorf("Got error GETing: %v", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Errorf("Error reading container logs: %v", err)
	}
	result := string(body)
	if result != string(body) {
		t.Errorf("Expected: '%v', got: '%v'", output, result)
	}
}

func TestContainerLogsWithTail(t *testing.T) {
	fw := newServerTest()
	output := "foo bar"
	podNamespace := "other"
	podName := "foo"
	expectedPodName := podName + ".other.etcd"
	expectedContainerName := "baz"
	expectedTail := "5"
	expectedFollow := false
	fw.fakeKubelet.containerLogsFunc = func(podFullName, containerName, tail string, follow bool, stdout, stderr io.Writer) error {
		if podFullName != expectedPodName {
			t.Errorf("expected %s, got %s", expectedPodName, podFullName)
		}
		if containerName != expectedContainerName {
			t.Errorf("expected %s, got %s", expectedContainerName, containerName)
		}
		if tail != expectedTail {
			t.Errorf("expected %s, got %s", expectedTail, tail)
		}
		if follow != expectedFollow {
			t.Errorf("expected %t, got %t", expectedFollow, follow)
		}
		return nil
	}
	resp, err := http.Get(fw.testHTTPServer.URL + "/containerLogs/" + podNamespace + "/" + podName + "/" + expectedContainerName + "?tail=5")
	if err != nil {
		t.Errorf("Got error GETing: %v", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Errorf("Error reading container logs: %v", err)
	}
	result := string(body)
	if result != string(body) {
		t.Errorf("Expected: '%v', got: '%v'", output, result)
	}
}

func TestContainerLogsWithFollow(t *testing.T) {
	fw := newServerTest()
	output := "foo bar"
	podNamespace := "other"
	podName := "foo"
	expectedPodName := podName + ".other.etcd"
	expectedContainerName := "baz"
	expectedTail := ""
	expectedFollow := true
	fw.fakeKubelet.containerLogsFunc = func(podFullName, containerName, tail string, follow bool, stdout, stderr io.Writer) error {
		if podFullName != expectedPodName {
			t.Errorf("expected %s, got %s", expectedPodName, podFullName)
		}
		if containerName != expectedContainerName {
			t.Errorf("expected %s, got %s", expectedContainerName, containerName)
		}
		if tail != expectedTail {
			t.Errorf("expected %s, got %s", expectedTail, tail)
		}
		if follow != expectedFollow {
			t.Errorf("expected %t, got %t", expectedFollow, follow)
		}
		return nil
	}
	resp, err := http.Get(fw.testHTTPServer.URL + "/containerLogs/" + podNamespace + "/" + podName + "/" + expectedContainerName + "?follow=1")
	if err != nil {
		t.Errorf("Got error GETing: %v", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Errorf("Error reading container logs: %v", err)
	}
	result := string(body)
	if result != string(body) {
		t.Errorf("Expected: '%v', got: '%v'", output, result)
	}
}


text:
package org.sagebionetworks.repo.model.dbo.persistence;

import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_SESSION_TOKEN_PRINCIPAL_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_SESSION_TOKEN_SESSION_TOKEN;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_SESSION_TOKEN_VALIDATED_ON;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_USER_GROUP_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.TABLE_SESSION_TOKEN;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.TABLE_USER_GROUP;

import java.util.Date;
import java.util.List;

import org.sagebionetworks.repo.model.dbo.AutoTableMapping;
import org.sagebionetworks.repo.model.dbo.Field;
import org.sagebionetworks.repo.model.dbo.ForeignKey;
import org.sagebionetworks.repo.model.dbo.MigratableDatabaseObject;
import org.sagebionetworks.repo.model.dbo.Table;
import org.sagebionetworks.repo.model.dbo.TableMapping;
import org.sagebionetworks.repo.model.dbo.migration.BasicMigratableTableTranslation;
import org.sagebionetworks.repo.model.dbo.migration.MigratableTableTranslation;
import org.sagebionetworks.repo.model.migration.MigrationType;

@Table(name = TABLE_SESSION_TOKEN)
public class DBOSessionToken implements MigratableDatabaseObject<DBOSessionToken, DBOSessionToken> {

	private static TableMapping<DBOSessionToken> tableMapping = AutoTableMapping.create(DBOSessionToken.class);

	@Field(name = COL_SESSION_TOKEN_PRINCIPAL_ID, primary = true, backupId = true)
	@ForeignKey(table = TABLE_USER_GROUP, field = COL_USER_GROUP_ID, cascadeDelete = true)
	private Long principalId;

	@Field(name = COL_SESSION_TOKEN_VALIDATED_ON)
	private Date validatedOn;

	@Field(name = COL_SESSION_TOKEN_SESSION_TOKEN, varchar = 100)
	private String sessionToken;

	@Override
	public TableMapping<DBOSessionToken> getTableMapping() {
		return tableMapping;
	}

	public Long getPrincipalId() {
		return principalId;
	}
	public void setPrincipalId(Long principalId) {
		this.principalId = principalId;
	}
	public Date getValidatedOn() {
		return validatedOn;
	}
	public void setValidatedOn(Date validatedOn) {
		this.validatedOn = validatedOn;
	}
	public String getSessionToken() {
		return sessionToken;
	}
	public void setSessionToken(String sessionToken) {
		this.sessionToken = sessionToken;
	}

	@Override
	public MigrationType getMigratableTableType() {
		return MigrationType.SESSION_TOKEN;
	}

	@Override
	public MigratableTableTranslation<DBOSessionToken, DBOSessionToken> getTranslator() {
		return new BasicMigratableTableTranslation<DBOSessionToken>();
	}

	@Override
	public Class<? extends DBOSessionToken> getBackupClass() {
		return DBOSessionToken.class;
	}

	@Override
	public Class<? extends DBOSessionToken> getDatabaseObjectClass() {
		return DBOSessionToken.class;
	}

	@Override
	public List<MigratableDatabaseObject<?,?>> getSecondaryTypes() {
		return null;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((principalId == null) ? 0 : principalId.hashCode());
		result = prime * result + ((sessionToken == null) ? 0 : sessionToken.hashCode());
		result = prime * result + ((validatedOn == null) ? 0 : validatedOn.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		DBOSessionToken other = (DBOSessionToken) obj;
		if (principalId == null) {
			if (other.principalId != null)
				return false;
		} else if (!principalId.equals(other.principalId))
			return false;
		if (sessionToken == null) {
			if (other.sessionToken != null)
				return false;
		} else if (!sessionToken.equals(other.sessionToken))
			return false;
		if (validatedOn == null) {
			if (other.validatedOn != null)
				return false;
		} else if (!validatedOn.equals(other.validatedOn))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "DBOSessionToken [principalId=" + principalId + ", validatedOn=" + validatedOn + ", sessionToken="
				+ sessionToken + "]";
	}

}


text:
using System.Collections.Generic;

namespace Umbraco.Cms.Infrastructure.Migrations.Upgrade.V_8_0_0.DataTypes
{
    /// <summary>
    /// Defines a service migrating preValues.
    /// </summary>
    public interface IPreValueMigrator
    {
        /// <summary>
        /// Determines whether this migrator can migrate a data type.
        /// </summary>
        /// <param name="editorAlias">The data type editor alias.</param>
        bool CanMigrate(string editorAlias);

        /// <summary>
        /// Gets the v8 codebase data type editor alias.
        /// </summary>
        /// <param name="editorAlias">The original v7 codebase editor alias.</param>
        /// <remarks>
        /// <para>This is used to validate that the migrated configuration can be parsed
        /// by the new property editor. Return <c>null</c> to bypass this validation,
        /// when for instance we know it will fail, and another, later migration will
        /// deal with it.</para>
        /// </remarks>
        string? GetNewAlias(string editorAlias);

        /// <summary>
        /// Gets the configuration object corresponding to preValue.
        /// </summary>
        /// <param name="dataTypeId">The data type identifier.</param>
        /// <param name="editorAlias">The data type editor alias.</param>
        /// <param name="preValues">PreValues.</param>
        object GetConfiguration(int dataTypeId, string editorAlias, Dictionary<string, PreValueDto> preValues);
    }
}


text:
#include "webrtc/test/fake_audio_device.h"

#include <algorithm>

#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/modules/media_file/source/media_file_utility.h"
#include "webrtc/system_wrappers/interface/clock.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/event_wrapper.h"
#include "webrtc/system_wrappers/interface/file_wrapper.h"
#include "webrtc/system_wrappers/interface/thread_wrapper.h"

namespace webrtc {
namespace test {

FakeAudioDevice::FakeAudioDevice(Clock* clock, const std::string& filename)
    : audio_callback_(NULL),
      capturing_(false),
      captured_audio_(),
      playout_buffer_(),
      last_playout_ms_(-1),
      clock_(clock),
      tick_(EventWrapper::Create()),
      lock_(CriticalSectionWrapper::CreateCriticalSection()),
      file_utility_(new ModuleFileUtility(0)),
      input_stream_(FileWrapper::Create()) {
  memset(captured_audio_, 0, sizeof(captured_audio_));
  memset(playout_buffer_, 0, sizeof(playout_buffer_));
  // Open audio input file as read-only and looping.
  EXPECT_EQ(0, input_stream_->OpenFile(filename.c_str(), true, true))
      << filename;
}

FakeAudioDevice::~FakeAudioDevice() {
  Stop();

  if (thread_.get() != NULL)
    thread_->Stop();
}

int32_t FakeAudioDevice::Init() {
  CriticalSectionScoped cs(lock_.get());
  if (file_utility_->InitPCMReading(*input_stream_.get()) != 0)
    return -1;

  if (!tick_->StartTimer(true, 10))
    return -1;
  thread_.reset(ThreadWrapper::CreateThread(
      FakeAudioDevice::Run, this, webrtc::kHighPriority, "FakeAudioDevice"));
  if (thread_.get() == NULL)
    return -1;
  unsigned int thread_id;
  if (!thread_->Start(thread_id)) {
    thread_.reset();
    return -1;
  }
  return 0;
}

int32_t FakeAudioDevice::RegisterAudioCallback(AudioTransport* callback) {
  CriticalSectionScoped cs(lock_.get());
  audio_callback_ = callback;
  return 0;
}

bool FakeAudioDevice::Playing() const {
  CriticalSectionScoped cs(lock_.get());
  return capturing_;
}

int32_t FakeAudioDevice::PlayoutDelay(uint16_t* delay_ms) const {
  *delay_ms = 0;
  return 0;
}

bool FakeAudioDevice::Recording() const {
  CriticalSectionScoped cs(lock_.get());
  return capturing_;
}

bool FakeAudioDevice::Run(void* obj) {
  static_cast<FakeAudioDevice*>(obj)->CaptureAudio();
  return true;
}

void FakeAudioDevice::CaptureAudio() {
  {
    CriticalSectionScoped cs(lock_.get());
    if (capturing_) {
      int bytes_read = file_utility_->ReadPCMData(
          *input_stream_.get(), captured_audio_, kBufferSizeBytes);
      if (bytes_read <= 0)
        return;
      int num_samples = bytes_read / 2;  // 2 bytes per sample.
      uint32_t new_mic_level;
      EXPECT_EQ(0,
                audio_callback_->RecordedDataIsAvailable(captured_audio_,
                                                         num_samples,
                                                         2,
                                                         1,
                                                         kFrequencyHz,
                                                         0,
                                                         0,
                                                         0,
                                                         false,
                                                         new_mic_level));
      uint32_t samples_needed = kFrequencyHz / 100;
      int64_t now_ms = clock_->TimeInMilliseconds();
      uint32_t time_since_last_playout_ms = now_ms - last_playout_ms_;
      if (last_playout_ms_ > 0 && time_since_last_playout_ms > 0)
        samples_needed = std::min(kFrequencyHz / time_since_last_playout_ms,
                                  kBufferSizeBytes / 2);
      uint32_t samples_out = 0;
      EXPECT_EQ(0,
                audio_callback_->NeedMorePlayData(samples_needed,
                                                  2,
                                                  1,
                                                  kFrequencyHz,
                                                  playout_buffer_,
                                                  samples_out));
    }
  }
  tick_->Wait(WEBRTC_EVENT_INFINITE);
}

void FakeAudioDevice::Start() {
  CriticalSectionScoped cs(lock_.get());
  capturing_ = true;
}

void FakeAudioDevice::Stop() {
  CriticalSectionScoped cs(lock_.get());
  capturing_ = false;
}
}  // namespace test
}  // namespace webrtc


text:
TEST_CASE( "Result checks") {

    std::random_device rd;
    std::default_random_engine generator(rd());

    constexpr char CHECK_MIRROR [] = "Checking if calculations aren't mirrored";
    SECTION(CHECK_MIRROR){
        //The interpreter
        const char* src =
        "qreg a[5]; creg b[5];"
        "x a[0];"
        "measure a[0] -> b[0];"
        "measure a[1] -> b[1];"
        "measure a[2] -> b[2];"
        "measure a[3] -> b[3];"
        "measure a[4] -> b[4];";

        MiniQbt::QasmAsyncInterpreter interpreter;
        interpreter.interpret(std::string(src));
        auto res = interpreter.readClassicResult("b");
        REQUIRE(!interpreter.hasErrors());

        constexpr size_t REGISTER_SIZE = 5;
        MiniQbt::QuantumEmulator<REGISTER_SIZE,true> emulator;
        auto ent = emulator.generateRegister();
        emulator.pauliX(0, ent);
        std::bitset<REGISTER_SIZE> bitset = emulator.measure(ent, generator);

        std::stringstream ss;
        ss << CHECK_MIRROR << " answer from the interpreter was : " ;
        //for(const bool d : res){
        for(int i = 0; i < res.registerSize(); i++ ) {
             ss << res.getData(i);
        }

        //}
        ss << " while the answer from the emulator was ";
        for(size_t i = 0; i < REGISTER_SIZE; i++){
            ss << bitset[i];
        }

        INFO(ss.str());
        for(size_t i = 0; i < REGISTER_SIZE; i++){
            REQUIRE(res.getData(i) == bitset[i]);
        }
    }

    constexpr char MEASURE_CHECK[] = "Checking measure";
    SECTION(MEASURE_CHECK){
        //The interpreter
        const char* src =
        "qreg a[5]; creg b[5];"
        "x a[0]; x a[2]; x a[4];"
        "measure a[0] -> b[0];"
        "measure a[1] -> b[1];"
        "measure a[2] -> b[2];"
        "measure a[3] -> b[3];"
        "measure a[4] -> b[4];";

        MiniQbt::QasmAsyncInterpreter interpreter;
        interpreter.interpret(std::string(src));
        auto res = interpreter.readClassicResult("b");
        REQUIRE(!interpreter.hasErrors());

        constexpr size_t REGISTER_SIZE = 5;
        MiniQbt::QuantumEmulator<REGISTER_SIZE,true> emulator;
        auto ent = emulator.generateRegister();
        emulator.pauliX(0, ent);
        emulator.pauliX(2, ent);
        emulator.pauliX(4, ent);
        std::bitset<REGISTER_SIZE> bitset = emulator.measure(ent, generator);

        for(size_t i = 0; i < REGISTER_SIZE; i++){
            REQUIRE(res.getData(i) == bitset[i]);
        }
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Boost.Geometry (aka GGL, Generic Geometry Library)</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Examples

Class List

Class Index

Class Hierarchy

Class Members

boost

geometry

traits

point_type< geometry::strategy::simplify::detail::douglas_peucker_point< P > >

Public Types

boost::geometry::traits::point_type< geometry::strategy::simplify::detail::douglas_peucker_point< P > > Struct Template Reference

List of all members.

Public Types

typedef P 	type

template<typename P>

 struct boost::geometry::traits::point_type< geometry::strategy::simplify::detail::douglas_peucker_point< P > >

Member Typedef Documentation

template<typename P >

          typedef P boost::geometry::traits::point_type< geometry::strategy::simplify::detail::douglas_peucker_point< P > >::type

April 2, 2011

Copyright © 2007-2011 Barend Gehrels, Amsterdam, the Netherlands

Copyright © 2008-2011 Bruno Lalande, Paris, France

Copyright © 2009-2010 Mateusz Loskot, London, UK

<address style="text-align: right;">
Documentation is generated by Doxygen
</address>