text:
* Breaking changes
  * OL3-Cesium is now compiled together with OL3. A custom closure compiler
    build is no more required.

* Changes
  * Automatically use device pixel ratio (the right way) to configure the
    Webgl 3D globe. See https://github.com/AnalyticalGraphicsInc/cesium/pull/3233.

## v1.9 - 2015-10-22

* Breaking changes
  * Port to OL 3.10.1, remove saturation, gamma and hue functions.
  * Change `olcs.AbstractSynchronizer.prototype.createSingleCounterpart` to
    return an array of counterparts instead of a unique object. This allows
    one OL3 layer to be transformed in several Cesium layers.
  * Rename `olcs.AbstractSynchronizer.prototype.createSingleCounterpart` to
    `olcs.AbstractSynchronizer.prototype.createSingleLayerCounterparts`.
  * Rename `olcs.RasterSynchronizer.prototype.convertLayerToCesiumImagery` to
    `olcs.RasterSynchronizer.prototype.convertLayerToCesiumImageries`.

* Changes
  * Add `olcs.OLCesium.setResolutionScale` to allow improving performance at
    the cost of quality.
  * Automatically use device pixel ratio to configure the Webgl 3D globe.
  * Add the experimental method `olcs.OLCesium.enableAutoRenderLoop` to stop
    rendering the globe when idle. This is based on work from Kevin Ring.
  * Port to Cesium 1.14.
  * The `olcs.AbstractSynchronizer` now tries to synchronize the layer groups.
    Only if null is returned will it synchronize each of its children. This
    allows more synchronization strategies in user applications.

## v1.8 - 2015-09-10

* Breaking changes
  * Rename `olcs.core.OlLayerPrimitive` to `olcs.core.VectorLayerCounterpart`
    and stop inheriting from `Cesium.PrimitiveCollection`. The underlying
    primitive collection may be retrieved with the `getRootPrimitive()` method.

* Changes
  * Port to Cesium 1.13 and OL 3.9.0.
  * Allow blocking Cesium rendering to save resources using
    `olcs.OLCesium#setBlockCesiumRendering(true)`.
  * The `build/generate-info.js` tool now follows symlinks to properly
    generate exports.
  * `olcs.RasterSynchronizer.prototype.convertLayerToCesiumImagery` may be
    overriden. As usual, subclassing requires that the subclass and the
    library code be compiled together by Closure. This change notably allows
    application code to handle projections not supported by Cesium.
  * Allow application developers to easily compile plugin code together with
    the library by putting their files in the src/plugins directory. See
    src/plugins/README.md for details and instructions.
  * Allow lazy loading of the Cesium script (experimental feature).

## v1.7 - 2015-08-07

  * Port to Cesium 1.12 and Ol 3.8.1

## v1.6 - 2015-06-30

  * Breaking changes
    * The layer is now passed to the conversion methods of `ol.FeatureConverter`.
    * The feature is now passed to the conversion methods of `ol.FeatureConverter`.
    * The `olcs.core.olVectorLayerToCesium()` function now takes a `scene`
      parameter. The `olcs.core.OlLayerPrimitive` constructor now takes a
      `scene` parameter.
    * Core static functions for converting from OL3 features to Cesium primitives
      have been moved into a class designed for inheritance.
      The `olcs.FeatureConverter` may be extended and passed as a parameter of
      the `olcs.VectorSynchronizer` constructor. See the synchronizer function
      parameter of the `olcs.OLCesium` constructor. Subclassing requires that
      the subclass and the library code be compiled together.
      One way of migrating existing code is to define a global variable:
      `app.converter = new olcs.FeatureConverter({scene: scene});` and call
      the methods through it: `app.converter.olLineStringGeometryToCesium()`.
  * Set reference to the OpenLayers feature and layer to all created Cesium
    primitives.
  * Compiled code may override the new `olcs.FeatureConverter.csAddBillboard`
    method in order to manipulate the option before the Cesium billboard is
    actually created.
  * The layer is now stored together with the feature in the Cesium counterpart.
    They may be retrieved using `pickedCesiumPrimitive.olLayer` and
    `pickedCesiumPrimitive.olFeature`.
  * Position point geometries on terrain.
    With 2D coordinates, use `pointFeature.getGeometry().set('altitudeMode', 'clampToGround')`.
    With 3D relative coordinates, use `pointFeature.getGeometry().set('altitudeMode', 'relativeToGround')`.
  * Port to Cesium 1.10.

## v1.5 - 2015-05-29

  * Port to Cesium 1.9 and Ol 3.5.0

## v1.4 - 2015-04-30

  * Port to Cesium 1.8 and Ol 3.4.0
  * Mark `olcs.RasterSynchronizer` @api

## v1.3 - 2015-03-23

* Breaking changes
  * The `enable` argument to `olcs.OLCesium#setEnabled()` is no longer optional.
* Port to Cesium 1.7.1 and Ol 3.3.0

## v1.2 - 2015-02-25

* Port to Cesium 1.6 and Ol 3.2

## v1.1 - 2015-01-20

* Breaking changes
  * The `olFeatureId` has been removed from the picked Cesium counterpart.
    Use directly `olFeature` as illustrated in the synthetic vector examples.
  * The `olcs.OLCesium` constructor signature has changed. Use
    `new olcs.OLCesium({map: map, target: target});` instead of `new olcs.OLCesium(map, target);`
* Custom synchronizer function may be passed to the OLCesium constructor
* Core functions for implementing custom 2D-3D transitions à la Google Map
* Store the `ol.Feature` in the Cesium counterpart instead of an id.
  Use `primitive.olFeature` to read it after picking. See the synthetic vector examples.
* Allow 3D warmup while displaying the 2D map

## v1.0.0 - 2014-11-17


text:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SadRogue.Primitives;

namespace SadConsole.Tests
{
    [TestClass]
    partial class ScreenSurface
    {
        [TestMethod]
        public void Create_SmallSize()
        {
            new SadConsole.Tests.BasicGameHost();
            var screenSurface = new SadConsole.ScreenSurface(20, 20);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package zap

// LogMarshaler allows user-defined types to efficiently add themselves to the
// logging context, and to selectively omit information which shouldn't be
// included in logs (e.g., passwords).
type LogMarshaler interface {
	MarshalLog(KeyValue) error
}

// LogMarshalerFunc is a type adapter that allows using a function as a
// LogMarshaler.
type LogMarshalerFunc func(KeyValue) error

// MarshalLog calls the underlying function.
func (f LogMarshalerFunc) MarshalLog(kv KeyValue) error {
	return f(kv)
}


text:
const mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.setPublicPath('public/');

mix.js('resources/assets/js/app.js', 'public/js')
    .sass('resources/assets/sass/app.scss', 'public/css');

mix.js('resources/assets/js/blueprintdocs.js', 'public/js')
    .sass('resources/assets/sass/blueprintdocs.scss', 'public/css');


text:
package org.apache.commons.javaflow.providers.asm3;

import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassAdapter;
import org.objectweb.asm.Opcodes;

class MaybeContinuableAnnotationVisitor extends ClassAdapter {
    private final ContinuableClassInfoResolver cciResolver;
    private boolean classContinuableAnnotationFound = false;
    private boolean isAnnotation = false;

    MaybeContinuableAnnotationVisitor(ContinuableClassInfoResolver cciResolver) {
        super(MaybeContinuableClassVisitor.NOP);
        this.cciResolver = cciResolver;
    }

    @Override
    public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
        isAnnotation = (access & Opcodes.ACC_ANNOTATION) > 0;
    }

    @Override
    public AnnotationVisitor visitAnnotation(String description, boolean visible) {
        if (isAnnotation && !classContinuableAnnotationFound) {
            classContinuableAnnotationFound = cciResolver.isContinuableAnnotation(description);
        }
        return null;
    }

    boolean isContinuable() {
        return classContinuableAnnotationFound && isAnnotation;
    }
}


text:
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using Pulse.Core;
using Pulse.FS;
using SharpDX;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using Resource = SharpDX.Direct3D11.Resource;

namespace Pulse.DirectX
{
    public static class DxTextureReader
    {
        private static readonly Dx11Device _device;
        private static readonly CreateTextureIssueWorkaround _textureCreatingWorkaround;

        private delegate void CreateTextureIssueWorkaround(DeviceContext contextRef, Resource srcTextureRef, ImageFileFormat destFormat);
        private delegate void D3DX11SaveTextureToMemory(DeviceContext contextRef, Resource srcTextureRef, ImageFileFormat destFormat, out Blob destBufOut, int flags);

        static DxTextureReader ()
        {
            Configuration.EnableObjectTracking = true;
            _device = Dx11Device.CreateDefaultAdapter();
            _textureCreatingWorkaround = InitializeWorkaround();
        }

        private static CreateTextureIssueWorkaround InitializeWorkaround()
        {
            try
            {
                D3DX11SaveTextureToMemory saveMethod = (D3DX11SaveTextureToMemory)Delegate.CreateDelegate(
                    typeof(D3DX11SaveTextureToMemory),
                    null,
                    typeof(Resource).Assembly.GetType("SharpDX.Direct3D11.D3DX11").GetMethod("SaveTextureToMemory", BindingFlags.Static | BindingFlags.NonPublic));

                return (c, t, f) =>
                {
                    Blob buff;
                    saveMethod(c, t, f, out buff, 0);
                    buff.Dispose();
                };
            }
            catch
            {
                return (c, t, f) =>
                {
                    using (MemoryStream ms = new MemoryStream(32 * 1024))
                        Resource.ToStream(c, t, f, ms);
                };
            }
        }

        public static DxTexture ReadFromWpd(WpdArchiveListing listing, WpdEntry entry)
        {
            using (Stream headers = listing.Accessor.ExtractHeaders())
            using (Stream content = listing.Accessor.ExtractContent())
            {
                headers.SetPosition(entry.Offset);

                GtexData gtex;
                SectionHeader sectionHeader = headers.ReadContent<SectionHeader>();
                switch (sectionHeader.Type)
                {
                    case SectionType.Txb:
                        gtex = ReadGtexFromTxb(headers);
                        break;
                    case SectionType.Vtex:
                        gtex = ReadGtexFromVtex(headers);
                        break;
                    default:
                        throw new NotImplementedException();
                }

                return LoadFromStream(gtex, content);
            }
        }

        public static DxTexture LoadFromStream(GtexData gtex, Stream input)
        {
            if (gtex.Header.LayerCount == 0)
                return null;

            return gtex.Header.IsCubeMap
                ? ReadTextureCubeFromStream(gtex, input)
                : Read2DTextureFromStream(gtex, input);
        }

        private static DxTexture ReadTextureCubeFromStream(GtexData gtex, Stream input)
        {
            Texture2DDescription descriptor = GetTextureCubeDescription(gtex);

            using (SafeUnmanagedArray array = new SafeUnmanagedArray(gtex.MipMapData.Sum(d => d.Length)))
            {
                DataRectangle[] rects = new DataRectangle[gtex.MipMapData.Length];
                using (UnmanagedMemoryStream io = array.OpenStream(FileAccess.Write))
                {
                    byte[] buff = new byte[32 * 1024];
                    for (int index = 0; index < gtex.MipMapData.Length; index++)
                    {
                        GtexMipMapLocation mimMap = gtex.MipMapData[index];
                        Int32 pitch = GetPitch(descriptor, index);
                        rects[index] = CreateDataRectangle(array, io, pitch);
                        input.SetPosition(mimMap.Offset);
                        input.CopyToStream(io, mimMap.Length, buff);
                    }
                }

                Texture2D texture = new Texture2D(_device.Device, descriptor, rects);

                // Workaround
                _textureCreatingWorkaround(_device.Device.ImmediateContext, texture, ImageFileFormat.Dds);

                return new DxTexture(texture, descriptor);
            }
        }

        private static DxTexture Read2DTextureFromStream(GtexData gtex, Stream input)
        {
            Texture2DDescription descriptor = Get2DTextureDescription(gtex);

            using (SafeUnmanagedArray array = new SafeUnmanagedArray(gtex.MipMapData.Sum(d => d.Length)))
            {
                DataRectangle[] rects = new DataRectangle[gtex.MipMapData.Length];
                using (UnmanagedMemoryStream io = array.OpenStream(FileAccess.Write))
                {
                    byte[] buff = new byte[32 * 1024];
                    for (int index = 0; index < gtex.MipMapData.Length; index++)
                    {
                        GtexMipMapLocation mimMap = gtex.MipMapData[index];
                        Int32 pitch = GetPitch(descriptor, index);
                        rects[index] = CreateDataRectangle(array, io, pitch);
                        input.SetPosition(mimMap.Offset);
                        input.CopyToStream(io, mimMap.Length, buff);
                    }
                }

                Texture2D texture = new Texture2D(_device.Device, descriptor, rects);

                // Workaround
                _textureCreatingWorkaround(_device.Device.ImmediateContext, texture, ImageFileFormat.Dds);

                return new DxTexture(texture, descriptor);
            }
        }

        private static Int32 GetPitch(Texture2DDescription descriptor, Int32 mipLevel)
        {
            return GetRowPitch(descriptor.Format, descriptor.Width, mipLevel);
        }

        private static void GetPitch(Texture3DDescription descriptor, int mipLevel, out int rowPitch, out int depthPitch)
        {
            rowPitch = GetRowPitch(descriptor.Format, descriptor.Width, mipLevel);
            depthPitch = rowPitch * 6;
        }

        private static Int32 GetRowPitch(Format format, Int32 width, Int32 mipLevel)
        {
            for (int i = 0; i < mipLevel; i++)
                width >>= 1;

            if (width == 0)
                width = 1;

            switch (format)
            {
                case Format.BC1_UNorm:
                    return Math.Max(1, ((width + 3) / 4)) * 8;
                case Format.BC2_UNorm_SRgb:
                case Format.BC3_UNorm_SRgb:
                    return Math.Max(1, ((width + 3) / 4)) * 16;
            }

            return width * FormatHelper.SizeOfInBytes(format);
        }

        private static DataRectangle CreateDataRectangle(SafeUnmanagedArray array, UnmanagedMemoryStream input, Int32 pitch)
        {
            return new DataRectangle(new IntPtr(array.DangerousGetHandle().ToInt64() + input.Position), pitch);
        }

        private static DataBox CreateDataBox(SafeUnmanagedArray array, UnmanagedMemoryStream input, Int32 rowPitch, Int32 depthPitch)
        {
            return new DataBox(new IntPtr(array.DangerousGetHandle().ToInt64() + input.Position), rowPitch, depthPitch);
        }

        private static Texture2DDescription GetTextureCubeDescription(GtexData gtex)
        {
            if (!gtex.Header.IsCubeMap)
                throw new Exception("IsCubeMap: false");

            return new Texture2DDescription
            {
                ArraySize = 6,
                Width = gtex.Header.Width,
                Height = gtex.Header.Height,
                Format = GetDxFormat(gtex.Header.Format),

                MipLevels = gtex.Header.MipMapCount,

                BindFlags = BindFlags.ShaderResource,
                OptionFlags = ResourceOptionFlags.Shared | ResourceOptionFlags.TextureCube,

                Usage = ResourceUsage.Default,
                CpuAccessFlags = CpuAccessFlags.None,
                SampleDescription = new SampleDescription(1, 0)
            };
        }

        private static Texture2DDescription Get2DTextureDescription(GtexData gtex)
        {
            if (gtex.Header.IsCubeMap)
                throw new Exception("IsCubeMap: true");

            return new Texture2DDescription
            {
                ArraySize = 1,
                Width = gtex.Header.Width,
                Height = gtex.Header.Height,
                Format = GetDxFormat(gtex.Header.Format),

                MipLevels = gtex.Header.MipMapCount,

                BindFlags = BindFlags.ShaderResource,
                OptionFlags = ResourceOptionFlags.Shared,

                Usage = ResourceUsage.Default,
                CpuAccessFlags = CpuAccessFlags.None,
                SampleDescription = new SampleDescription(1, 0)
            };
        }

        private static Format GetDxFormat(GtexPixelFromat format)
        {
            switch (format)
            {
                case GtexPixelFromat.Dxt1:
                    return Format.BC1_UNorm;
                case GtexPixelFromat.Dxt3:
                    return Format.BC2_UNorm_SRgb;
                case GtexPixelFromat.Dxt5:
                    return Format.BC3_UNorm_SRgb;
                case GtexPixelFromat.A8R8G8B8:
                    return Format.B8G8R8A8_UNorm;
                case GtexPixelFromat.X8R8G8B8:
                    return Format.B8G8R8X8_UNorm;
            }

            throw new NotImplementedException(format.ToString());
        }

        private static GtexData ReadGtexFromTxb(Stream headers)
        {
            TextureHeader textureHeader = headers.ReadContent<TextureHeader>();
            return headers.ReadContent<GtexData>();
        }

        private static GtexData ReadGtexFromVtex(Stream headers)
        {
            VtexHeader textureHeader = headers.ReadContent<VtexHeader>();
            headers.Seek(textureHeader.GtexOffset - VtexHeader.Size, SeekOrigin.Current);
            return headers.ReadContent<GtexData>();
        }
    }
}


text:
alter table SEC_USER_SETTING add VALUE_ text^
alter table SYS_CONFIG add VALUE_ text^
alter table SEC_PERMISSION add VALUE_ integer^

update SEC_USER_SETTING set VALUE_ = VALUE^
update SYS_CONFIG set VALUE_ = VALUE^
update SEC_PERMISSION set VALUE_ = VALUE^


text:
// a simple atomic stat counter/rate
package stats

import (
	"expvar"
	"strconv"
)

// An AtomicInt is an int64 to be accessed atomically.
type AtomicInt struct {
	Val *expvar.Int
}

func NewAtomic(name string) *AtomicInt {
	var att *AtomicInt
	gots := expvar.Get(name)
	if gots == nil {
		att = &AtomicInt{
			Val: expvar.NewInt(name),
		}
		att.Set(0)
	} else {
		att = &AtomicInt{
			Val: gots.(*expvar.Int),
		}
	}
	return att
}

// Add atomically adds n to i.
func (i *AtomicInt) Add(n int64) int64 {
	i.Val.Add(n)
	return i.Get()
}

// Get atomically gets the value of i.
func (i *AtomicInt) Get() int64 {
	ret, _ := strconv.Atoi(i.Val.String())
	return int64(ret)
}

// Set the int to an arb number to a number
func (i *AtomicInt) Set(n int64) {
	i.Val.Set(n)
}

func (i *AtomicInt) Equal(n int64) bool {
	return i.Get() == n
}

func (i *AtomicInt) String() string {
	return i.Val.String()
}


text:
#pragma once
#include <aws/iam/IAM_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace IAM
{
namespace Model
{

  /**
   *
Contains information about the reason that the operation failed.

This
   * data type is used as a response element in the
   * GetOrganizationsAccessReport, GetServiceLastAccessedDetails, and
   * GetServiceLastAccessedDetailsWithEntities operations.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_IAM_API ErrorDetails
  {
  public:
    ErrorDetails();
    ErrorDetails(const Aws::Utils::Xml::XmlNode& xmlNode);
    ErrorDetails& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
    void OutputToStream(Aws::OStream& oStream, const char* location) const;

    /**
     *
Detailed information about the reason that the operation failed.

     */
    inline const Aws::String& GetMessage() const{ return m_message; }

    /**
     *
Detailed information about the reason that the operation failed.

     */
    inline bool MessageHasBeenSet() const { return m_messageHasBeenSet; }

    /**
     *
Detailed information about the reason that the operation failed.

     */
    inline void SetMessage(const Aws::String& value) { m_messageHasBeenSet = true; m_message = value; }

    /**
     *
Detailed information about the reason that the operation failed.

     */
    inline void SetMessage(Aws::String&& value) { m_messageHasBeenSet = true; m_message = std::move(value); }

    /**
     *
Detailed information about the reason that the operation failed.

     */
    inline void SetMessage(const char* value) { m_messageHasBeenSet = true; m_message.assign(value); }

    /**
     *
Detailed information about the reason that the operation failed.

     */
    inline ErrorDetails& WithMessage(const Aws::String& value) { SetMessage(value); return *this;}

    /**
     *
Detailed information about the reason that the operation failed.

     */
    inline ErrorDetails& WithMessage(Aws::String&& value) { SetMessage(std::move(value)); return *this;}

    /**
     *
Detailed information about the reason that the operation failed.

     */
    inline ErrorDetails& WithMessage(const char* value) { SetMessage(value); return *this;}

    /**
     *
The error code associated with the operation failure.

     */
    inline const Aws::String& GetCode() const{ return m_code; }

    /**
     *
The error code associated with the operation failure.

     */
    inline bool CodeHasBeenSet() const { return m_codeHasBeenSet; }

    /**
     *
The error code associated with the operation failure.

     */
    inline void SetCode(const Aws::String& value) { m_codeHasBeenSet = true; m_code = value; }

    /**
     *
The error code associated with the operation failure.

     */
    inline void SetCode(Aws::String&& value) { m_codeHasBeenSet = true; m_code = std::move(value); }

    /**
     *
The error code associated with the operation failure.

     */
    inline void SetCode(const char* value) { m_codeHasBeenSet = true; m_code.assign(value); }

    /**
     *
The error code associated with the operation failure.

     */
    inline ErrorDetails& WithCode(const Aws::String& value) { SetCode(value); return *this;}

    /**
     *
The error code associated with the operation failure.

     */
    inline ErrorDetails& WithCode(Aws::String&& value) { SetCode(std::move(value)); return *this;}

    /**
     *
The error code associated with the operation failure.

     */
    inline ErrorDetails& WithCode(const char* value) { SetCode(value); return *this;}

  private:

    Aws::String m_message;
    bool m_messageHasBeenSet = false;

    Aws::String m_code;
    bool m_codeHasBeenSet = false;
  };

} // namespace Model
} // namespace IAM
} // namespace Aws


text:
package exec

import (
	"archive/tar"
	"bytes"
	"os"
	"time"

	"code.cloudfoundry.org/lager"
	"github.com/concourse/atc"
	"github.com/concourse/atc/db"
	"github.com/concourse/atc/resource"
	"github.com/concourse/atc/worker"
)

// PutStep produces a resource version using preconfigured params and any data
// available in the SourceRepository.
type PutStep struct {
	logger         lager.Logger
	resourceConfig atc.ResourceConfig
	params         atc.Params
	stepMetadata   StepMetadata
	session        resource.Session
	tags           atc.Tags
	teamID         int
	delegate       PutDelegate
	tracker        resource.Tracker
	resourceTypes  atc.ResourceTypes

	repository *SourceRepository

	resource resource.Resource

	versionedSource resource.VersionedSource

	succeeded bool

	containerSuccessTTL time.Duration
	containerFailureTTL time.Duration
}

func newPutStep(
	logger lager.Logger,
	resourceConfig atc.ResourceConfig,
	params atc.Params,
	stepMetadata StepMetadata,
	session resource.Session,
	tags atc.Tags,
	teamID int,
	delegate PutDelegate,
	tracker resource.Tracker,
	resourceTypes atc.ResourceTypes,
	containerSuccessTTL time.Duration,
	containerFailureTTL time.Duration,
) PutStep {
	return PutStep{
		logger:              logger,
		resourceConfig:      resourceConfig,
		params:              params,
		stepMetadata:        stepMetadata,
		session:             session,
		tags:                tags,
		teamID:              teamID,
		delegate:            delegate,
		tracker:             tracker,
		resourceTypes:       resourceTypes,
		containerSuccessTTL: containerSuccessTTL,
		containerFailureTTL: containerFailureTTL,
	}
}

// Using finishes construction of the PutStep and returns a *PutStep. If the
// *PutStep errors, its error is reported to the delegate.
func (step PutStep) Using(prev Step, repo *SourceRepository) Step {
	step.repository = repo

	return errorReporter{
		Step:          &step,
		ReportFailure: step.delegate.Failed,
	}
}

// Run chooses a worker that supports the step's resource type and creates a
// container.
//
// All ArtifactSources present in the SourceRepository are then brought into
// the container, using volumes if possible, and streaming content over if not.
//
// The resource's put script is then invoked. The PutStep is ready as soon as
// the resource's script starts, and signals will be forwarded to the script.
func (step *PutStep) Run(signals <-chan os.Signal, ready chan<- struct{}) error {
	step.delegate.Initializing()

	sources := step.repository.AsMap()

	resourceSources := make(map[string]resource.ArtifactSource)
	for name, source := range sources {
		resourceSources[string(name)] = resourceSource{source}
	}

	runSession := step.session
	runSession.ID.Stage = db.ContainerStageRun

	trackedResource, missingNames, err := step.tracker.InitWithSources(
		step.logger,
		step.stepMetadata,
		runSession,
		resource.ResourceType(step.resourceConfig.Type),
		step.tags,
		step.teamID,
		resourceSources,
		step.resourceTypes,
		step.delegate,
	)

	if err != nil {
		return err
	}

	missingSourceNames := make([]SourceName, len(missingNames))
	for i, n := range missingNames {
		missingSourceNames[i] = SourceName(n)
	}

	step.resource = trackedResource

	scopedRepo, err := step.repository.ScopedTo(missingSourceNames...)
	if err != nil {
		return err
	}

	var artifactSource resource.ArtifactSource
	if len(sources) == 0 {
		artifactSource = emptySource{}
	} else {
		artifactSource = resourceSource{scopedRepo}
	}

	step.versionedSource, err = step.resource.Put(
		resource.IOConfig{
			Stdout: step.delegate.Stdout(),
			Stderr: step.delegate.Stderr(),
		},
		step.resourceConfig.Source,
		step.params,
		artifactSource,
		signals,
		ready,
	)

	if err, ok := err.(resource.ErrResourceScriptFailed); ok {
		step.delegate.Completed(ExitStatus(err.ExitStatus), nil)
		return nil
	}

	if err == resource.ErrAborted {
		return ErrInterrupted
	}

	if err != nil {
		return err
	}

	step.succeeded = true
	step.delegate.Completed(ExitStatus(0), &VersionInfo{
		Version:  step.versionedSource.Version(),
		Metadata: step.versionedSource.Metadata(),
	})

	return nil
}

func (step *PutStep) Release() {
	if step.resource == nil {
		return
	}

	if step.succeeded {
		step.resource.Release(worker.FinalTTL(step.containerSuccessTTL))
	} else {
		step.resource.Release(worker.FinalTTL(step.containerFailureTTL))
	}
}

// Result indicates Success as true if the script completed with exit status 0.
//
// It also indicates VersionInfo returned by the script.
//
// Any other type is ignored.
func (step *PutStep) Result(x interface{}) bool {
	switch v := x.(type) {
	case *Success:
		*v = Success(step.succeeded)
		return true
	case *VersionInfo:
		*v = VersionInfo{
			Version:  step.versionedSource.Version(),
			Metadata: step.versionedSource.Metadata(),
		}
		return true

	default:
		return false
	}
}

type resourceSource struct {
	ArtifactSource
}

func (source resourceSource) StreamTo(dest resource.ArtifactDestination) error {
	return source.ArtifactSource.StreamTo(resource.ArtifactDestination(dest))
}

type emptySource struct {
	ArtifactSource
}

func (source emptySource) StreamTo(dest resource.ArtifactDestination) error {
	emptyTar := new(bytes.Buffer)

	err := tar.NewWriter(emptyTar).Close()
	if err != nil {
		return err
	}

	err = dest.StreamIn(".", emptyTar)
	if err != nil {
		return err
	}

	return nil
}


text:
from django.shortcuts import get_object_or_404

from rest_framework import viewsets
from rest_framework.response import Response

from paranuara_api.models import Company, Person
from paranuara_api.serializers import (
        CompanySerializer, CompanyListSerializer, PersonListSerializer,
        PersonSerializer, FriendshipSerializer
)

class MultiSerializerMixin(object):

    def get_serializer_class(self):
        return self.serializers[self.action]

class CompanyViewSet(MultiSerializerMixin, viewsets.ReadOnlyModelViewSet):
    queryset = Company.objects.all()
    lookup_field = 'index'

    serializers = {
        'list': CompanyListSerializer,
        'retrieve': CompanySerializer,
    }

class PersonViewSet(MultiSerializerMixin, viewsets.ReadOnlyModelViewSet):
    queryset = Person.objects.all()
    lookup_field = 'index'

    serializers = {
        'list': PersonListSerializer,
        'retrieve': PersonSerializer,
    }

class Friendship(object):

    def __init__(self, person, friend, friends):
        self.person = person
        self.friend = friend
        self.friends = friends

class FriendsViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Person.objects.all()
    lookup_field = 'index'

    serializers = {
        'list': CompanyListSerializer,
        'retrieve': CompanySerializer,
    }

    def list(self, request, person_index=None):
        person = get_object_or_404(Person, index=person_index)
        serializer = PersonListSerializer(person.friends.is_alive(),
                                          many=True,
                                          context={'request': request})
        return Response(serializer.data)

    def retrieve(self, request, index=None, person_index=None):
        person = get_object_or_404(Person, index=person_index)
        friend = get_object_or_404(Person, index=index)

        friends = Person.objects.mutual_friends_alive_with_brown_eyes(
                        person, friend)
        friendship = Friendship(person, friend, friends)
        serializer = FriendshipSerializer(friendship)
        return Response(serializer.data)


text:
Plugin.define "Microsoft-HTTPAPI" do
author "Brendan Coles <bcoles@gmail.com>" # 2011-03-13
version "0.2"
description "The HTTP Server API enables applications to communicate over HTTP without using Microsoft Internet Information Server (IIS). Applications can register to receive HTTP requests for particular URLs, receive HTTP requests, and send HTTP responses. The HTTP Server API includes SSL support so that applications can exchange data over secure HTTP connections without IIS. It is also designed to work with I/O completion ports."
website "http://msdn.microsoft.com/en-us/library/aa364510%28v=vs.85%29.aspx"

# ShodanHQ results as at 2011-03-13 #
# 148,635 for Microsoft-HTTPAPI

matches [

	# HTTP Server Header
	{ :regexp=>/Microsoft-HTTPAPI/, :search=>"headers[server]" },
	# Version Detection # HTTP Server Header
	{ :version=>/Microsoft-HTTPAPI\/(.+)$/, :search=>"headers[server]" },

]

end


text:
package org.citydb.gui.operation.exporter.view;

import org.citydb.config.Config;
import org.citydb.config.i18n.Language;
import org.citydb.gui.plugin.util.DefaultView;
import org.citydb.gui.plugin.view.ViewController;

import javax.swing.*;

public class CityGMLExportView extends DefaultView {

	public CityGMLExportView(ViewController viewController, Config config) {
		super(new ExportPanel(viewController, config));
	}

	@Override
	public String getLocalizedTitle() {
		return Language.I18N.getString("main.tabbedPane.export");
	}

	@Override
	public String getToolTip() {
		return null;
	}

	@Override
	public Icon getIcon() {
		return null;
	}
}


text:
default['abiquo']['profile'] = 'monolithic'

# Wether or not to install external dependant services
# like MariaDB, Redis, RabbitMQ
# Set to false if you wish to use existing servers.
default['abiquo']['install_ext_services'] = true

# Common properties
default['abiquo']['license'] = nil

# NFS repository configuration
default['abiquo']['nfs']['mountpoint'] = '/opt/vm_repository'
default['abiquo']['nfs']['location'] = nil # Change to something like: "127.0.0.1:/opt/vm_repository"

# Yum repository configuration
default['abiquo']['yum']['install-repo'] = true
default['abiquo']['yum']['base-repo'] = 'http://mirror.abiquo.com/el$releasever/4.7/os/x86_64'
default['abiquo']['yum']['updates-repo'] = 'http://mirror.abiquo.com/el$releasever/4.7/updates/x86_64'
default['abiquo']['yum']['gpg-check'] = true
default['abiquo']['yum']['proxy'] = nil

# Database configuration
default['abiquo']['db']['host'] = 'localhost'
default['abiquo']['db']['port'] = 3306
default['abiquo']['db']['user'] = 'root'
default['abiquo']['db']['from'] = 'localhost'
default['abiquo']['db']['password'] = nil
default['abiquo']['db']['upgrade'] = true
default['abiquo']['db']['enable-master'] = false

# Redis configuration
default['redisio']['servers'] = [{
  'name' => 'master',
  'port' => 6379,
  'address' => '0.0.0.0',
}]
default['redisio']['package_install'] = true
default['redisio']['version'] = nil
default['redisio']['package_name'] = 'redis'
default['redisio']['bin_path'] = '/usr/bin'

# RabbitMQ configuration
default['rabbitmq']['config'] = '/etc/rabbitmq/rabbitmq.config'
default['rabbitmq']['use_distro_version'] = true
default['rabbitmq']['ssl'] = false
default['rabbitmq']['port'] = 5672
default['rabbitmq']['ssl_port'] = 5671
default['rabbitmq']['nodename'] = "rabbit@#{node['hostname']}"
default['rabbitmq']['config-env_template_cookbook'] = 'abiquo'
default['abiquo']['rabbitmq']['username'] = 'abiquo'
default['abiquo']['rabbitmq']['password'] = 'abiquo'
default['abiquo']['rabbitmq']['addresses'] = "localhost:#{node['rabbitmq'][node['rabbitmq']['ssl'] ? 'ssl_port' : 'port']}"
default['abiquo']['rabbitmq']['tags'] = 'administrator'
default['abiquo']['rabbitmq']['vhost'] = '/'
default['abiquo']['rabbitmq']['tls'] = node['rabbitmq']['ssl']
default['abiquo']['rabbitmq']['tlstrustall'] = false
default['abiquo']['rabbitmq']['generate_cert'] = false

# Tomcat configuration
default['abiquo']['tomcat']['http-port'] = 8009
default['abiquo']['tomcat']['ajp-port'] = 8010
default['abiquo']['tomcat']['wait-for-webapps'] = false
default['abiquo']['tomcat']['alias'] = node['fqdn']

# Override the Apache proxy configuration
default['apache']['proxy']['order'] = 'allow,deny'
default['apache']['proxy']['deny_from']  = 'none'
default['apache']['proxy']['allow_from'] = 'all'
default['apache']['listen_ports'] = [80, 443]

# Determine if the server should include the frontend components
default['abiquo']['server']['install_frontend'] = true

# UI Apache configuration
default['abiquo']['ui_apache_opts'] = {}

# UI app configuration attributes. These attributes will be rendered
# in /var/www/html/ui/config/client-config-custom.json
default['abiquo']['ui_config'] = { 'config.endpoint' => "https://#{node['fqdn']}/api" }
default['abiquo']['ui_proxies'] = {}

# Wheter or not to generate a self signed certificate
# for this host. If not, provide path to certificate,
# private key and optionally a CA cert. The cookbook
# does not manage the certificate files path provided
# for non generated certificates.
default['abiquo']['certificate']['common_name'] = node['fqdn']
default['abiquo']['certificate']['organization'] = 'Abiquo'
default['abiquo']['certificate']['department'] = 'Engineering'
default['abiquo']['certificate']['country'] = 'ES'
default['abiquo']['certificate']['source'] = 'self-signed'
default['abiquo']['certificate']['file'] = "/etc/pki/abiquo/#{node['abiquo']['certificate']['common_name']}.crt"
default['abiquo']['certificate']['key_file'] = "/etc/pki/abiquo/#{node['abiquo']['certificate']['common_name']}.key"
default['abiquo']['certificate']['ca_file'] = nil

# Additional certs to add to Java truststore
# Provide a hash of {alias => url} or {alias => host}
# { 'api' => 'https://somehost/' }
# or just
# { 'someservice' => 'someservice.local' }
default['abiquo']['certificate']['additional_certs'] = {}

# Configure abiquo KVM
default['abiquo']['aim']['port'] = 8889
default['abiquo']['aim']['include_neutron'] = false
default['abiquo']['aim']['neutron']['vlan_ranges'] = 'abq-vlans:2:4094'
default['abiquo']['aim']['neutron']['interface_mappings'] = 'external:ens3,abq-vlans:ens4'
default['abiquo']['aim']['neutron']['rabbit_userid'] = 'abiquo'
default['abiquo']['aim']['neutron']['rabbit_password'] = 'xabiquo'
default['abiquo']['aim']['neutron']['rabbit_host'] = 'localhost'
default['abiquo']['aim']['neutron']['rabbit_port'] = 5672
default['abiquo']['aim']['neutron']['identity_uri'] = 'http://localhost:35357/v3'
default['abiquo']['aim']['neutron']['domain'] = 'default'
default['abiquo']['aim']['neutron']['project'] = 'service'
default['abiquo']['aim']['neutron']['admin_user'] = 'admin'
default['abiquo']['aim']['neutron']['admin_password'] = 'xabiquo'

# Configure monitoring node
default['abiquo']['monitoring']['cassandra']['cluster_name'] = 'abiquo'
default['abiquo']['monitoring']['kairosdb']['host'] = 'localhost'
default['abiquo']['monitoring']['kairosdb']['port'] = 8080
default['abiquo']['monitoring']['db']['host'] = 'localhost'
default['abiquo']['monitoring']['db']['port'] = 3306
default['abiquo']['monitoring']['db']['user'] = 'root'
default['abiquo']['monitoring']['db']['password'] = nil
default['abiquo']['monitoring']['db']['from'] = 'localhost'
default['abiquo']['monitoring']['db']['install'] = true
default['abiquo']['monitoring']['emmett']['port'] = 36638
default['abiquo']['monitoring']['emmett']['ssl'] = false

# Override the default java configuration
default['java']['oracle']['accept_oracle_download_terms'] = true
default['java']['install_flavor'] = 'oracle_rpm'
default['java']['oracle_rpm']['type'] = 'jdk'
default['java']['java_home'] = '/usr/java/default'
default['java']['jdk_version'] = 8

# Override Cassandra default configuration to make sure it is always running properly
default['cassandra']['notify_restart'] = true
default['cassandra']['use_systemd'] = true if node['platform_version'].to_i >= 7

# Default properties
default['abiquo']['properties']['abiquo.datacenter.id'] = node['hostname']
default['abiquo']['properties']['abiquo.rabbitmq.username'] = node['abiquo']['rabbitmq']['username']
default['abiquo']['properties']['abiquo.rabbitmq.password'] = node['abiquo']['rabbitmq']['password']
default['abiquo']['properties']['abiquo.rabbitmq.addresses'] = node['abiquo']['rabbitmq']['addresses']
default['abiquo']['properties']['abiquo.rabbitmq.tls'] = node['abiquo']['rabbitmq']['tls']
default['abiquo']['properties']['abiquo.rabbitmq.tls.trustallcertificates'] = node['abiquo']['rabbitmq']['tlstrustall']
default['abiquo']['properties']['abiquo.vncport.min'] = 5900
default['abiquo']['properties']['abiquo.vncport.max'] = 5999

case node['abiquo']['profile']
when 'monolithic', 'server'
  default['abiquo']['properties']['abiquo.m.instanceid'] = node['hostname']
  default['abiquo']['properties']['abiquo.m.identity'] = 'default_outbound_api_user'
  default['abiquo']['properties']['abiquo.server.sessionTimeout'] = 30
  default['abiquo']['properties']['abiquo.server.mail.server'] = '127.0.0.1'
  default['abiquo']['properties']['abiquo.server.mail.user'] = 'none@none.es'
  default['abiquo']['properties']['abiquo.server.mail.password'] = 'none'
  default['abiquo']['properties']['abiquo.redis.host'] = '127.0.0.1'
  default['abiquo']['properties']['abiquo.redis.port'] = 6379
  default['abiquo']['properties']['abiquo.monitoring.enabled'] = false
  default['abiquo']['properties']['abiquo.server.api.location'] = "https://#{node['fqdn']}/api"
when 'remoteservices'
  default['abiquo']['properties']['abiquo.appliancemanager.localRepositoryPath'] = node['abiquo']['nfs']['mountpoint']
  default['abiquo']['properties']['abiquo.appliancemanager.checkMountedRepository'] = !node['abiquo']['nfs']['location'].nil?
  default['abiquo']['properties']['abiquo.monitoring.enabled'] = false
end

# KairosDB config
default['abiquo']['kairosdb_config']['kairosdb.telnetserver.port'] = 4242
default['abiquo']['kairosdb_config']['kairosdb.service.telnet'] = 'org.kairosdb.core.telnet.TelnetServerModule'
default['abiquo']['kairosdb_config']['kairosdb.service.http'] = 'org.kairosdb.core.http.WebServletModule'
default['abiquo']['kairosdb_config']['kairosdb.service.reporter'] = 'org.kairosdb.core.reporting.MetricReportingModule'
default['abiquo']['kairosdb_config']['kairosdb.datapoints.factory.long'] = 'org.kairosdb.core.datapoints.LongDataPointFactoryImpl'
default['abiquo']['kairosdb_config']['kairosdb.datapoints.factory.double'] = 'org.kairosdb.core.datapoints.DoubleDataPointFactoryImpl'
default['abiquo']['kairosdb_config']['kairosdb.datapoints.factory.string'] = 'org.kairosdb.core.datapoints.StringDataPointFactory'
default['abiquo']['kairosdb_config']['kairosdb.reporter.schedule'] = '0 */1 * * * ?'
default['abiquo']['kairosdb_config']['kairosdb.jetty.port'] = node['abiquo']['monitoring']['kairosdb']['port']
default['abiquo']['kairosdb_config']['kairosdb.jetty.static_web_root'] = 'webroot'
default['abiquo']['kairosdb_config']['kairosdb.datastore.concurrentQueryThreads'] = 5
default['abiquo']['kairosdb_config']['kairosdb.service.datastore'] = 'org.kairosdb.datastore.cassandra.CassandraModule'
default['abiquo']['kairosdb_config']['kairosdb.datastore.h2.database_path'] = 'build/h2db'
default['abiquo']['kairosdb_config']['kairosdb.datastore.cassandra.host_list'] = "localhost:#{node['cassandra']['config']['rpc_port']}"
default['abiquo']['kairosdb_config']['kairosdb.datastore.cassandra.keyspace'] = 'kairosdb'
default['abiquo']['kairosdb_config']['kairosdb.datastore.cassandra.replication_factor'] = 1
default['abiquo']['kairosdb_config']['kairosdb.datastore.cassandra.write_delay'] = 1000
default['abiquo']['kairosdb_config']['kairosdb.datastore.cassandra.write_buffer_max_size'] = 500000
default['abiquo']['kairosdb_config']['kairosdb.datastore.cassandra.single_row_read_size'] = 10240
default['abiquo']['kairosdb_config']['kairosdb.datastore.cassandra.multi_row_size'] = 1000
default['abiquo']['kairosdb_config']['kairosdb.datastore.cassandra.multi_row_read_size'] = 1024
default['abiquo']['kairosdb_config']['kairosdb.datastore.cassandra.row_key_cache_size'] = 10240
default['abiquo']['kairosdb_config']['kairosdb.datastore.cassandra.string_cache_size'] = 5000
default['abiquo']['kairosdb_config']['kairosdb.datastore.cassandra.increase_buffer_size_schedule'] = '0 */5 * * * ?'
default['abiquo']['kairosdb_config']['kairosdb.datastore.cassandra.read_consistency_level'] = 'ONE'
default['abiquo']['kairosdb_config']['kairosdb.datastore.cassandra.write_consistency_level'] = 'QUORUM'
default['abiquo']['kairosdb_config']['kairosdb.datastore.cassandra.datapoint_ttl'] = 31536000
default['abiquo']['kairosdb_config']['kairosdb.datastore.hbase.timeseries_table'] = 'tsdb'
default['abiquo']['kairosdb_config']['kairosdb.datastore.hbase.uinqueids_table'] = 'tsdb-uid'
default['abiquo']['kairosdb_config']['kairosdb.datastore.hbase.zoo_keeper_quorum'] = 'localhost'
default['abiquo']['kairosdb_config']['kairosdb.datastore.hbase.zoo_keeper_base_dir'] = ''
default['abiquo']['kairosdb_config']['kairosdb.datastore.hbase.auto_create_metrics'] = true
default['abiquo']['kairosdb_config']['kairosdb.datastore.remote.data_dir'] = '.'
default['abiquo']['kairosdb_config']['kairosdb.datastore.remote.remote_url'] = ''
default['abiquo']['kairosdb_config']['kairosdb.datastore.remote.schedule'] = '0 */30 * * * ?'
default['abiquo']['kairosdb_config']['kairosdb.datastore.remote.random_delay'] = 0
default['abiquo']['kairosdb_config']['kairosdb.query_cache.cache_file_cleaner_schedule'] = '0 0 12 ? * SUN *'

# Java
default['java']['oracle']['jce']['8']['checksum'] = '9c64997edfce44e29296bfbd0cf90abf8b6b9ef2ea64733adae3bdac9ae2c5a6'


text:
package commands

import (
	log "github.com/cihub/seelog"
	"github.com/imosquera/uploadthis/conf"
	"github.com/imosquera/uploadthis/util"
	"os"
	"path"
)

type Commander interface {
	SetMonitor(conf.MonitorDir)
	SetName(string)
	SetUploadFiles([]string)
	Prepare()
	Run() ([]string, error)
}

type Command struct {
	monitorDir     conf.MonitorDir
	UploadFiles    []string
	statePersistor StatePersistor
	Name           string
}

func NewFileStateCommand() *Command {
	return &Command{
		statePersistor: &FileStatePersistor{},
	}
}

func (self *Command) SetMonitor(monitor conf.MonitorDir) {
	self.monitorDir = monitor
}

func (self *Command) SetName(name string) {
	self.Name = name
}

func (self *Command) SetUploadFiles(uploadFiles []string) {
	self.UploadFiles = uploadFiles
}

func (self *Command) Prepare() {
	workDir := path.Join(self.monitorDir.Path, ".uploadthis", self.Name)
	self.statePersistor.SetWorkDir(workDir)
	self.statePersistor.SetActive(self.UploadFiles)
	self.UploadFiles = self.statePersistor.GetActive()
}

type StatePersistor interface {
	SetWorkDir(string)
	SetActive([]string) []string
	GetActive() []string
}

type FileStatePersistor struct {
	WorkDir string
}

func (self *FileStatePersistor) SetWorkDir(workDir string) {
	log.Infof("Setting workdir to: %s", workDir)
	util.MakeDir(workDir)
	self.WorkDir = workDir
}

func (self *FileStatePersistor) GetActive() []string {
	return util.GetFilesFromDir(self.WorkDir)
}

//set the active files by moving them into their own directory
func (self *FileStatePersistor) SetActive(filePaths []string) []string {
	newUploadFiles := make([]string, 0, len(filePaths))
	log.Infof("Setting %d files to active", len(filePaths))
	for _, uploadFileInfo := range filePaths {
		filename := path.Base(uploadFileInfo)
		workFile := path.Join(self.WorkDir, filename)
		log.Infof("Setting %s to %s to be active", uploadFileInfo, workFile)
		err := os.Rename(uploadFileInfo, workFile)
		util.LogPanic(err)
	}
	return newUploadFiles
}


text:
#ifndef GCC_INT_VECTOR_BUILDER_H
#define GCC_INT_VECTOR_BUILDER_H 1

#include "vector-builder.h"

/* This class is used to build vectors of integer type T using the same
   encoding as tree and rtx constants.  See vector_builder for more
   details.  */
template<typename T>
class int_vector_builder : public vector_builder<T, int_vector_builder<T> >
{
  typedef vector_builder<T, int_vector_builder> parent;
  friend class vector_builder<T, int_vector_builder>;

public:
  int_vector_builder () {}
  int_vector_builder (poly_uint64, unsigned int, unsigned int);

  using parent::new_vector;

private:
  bool equal_p (T, T) const;
  bool allow_steps_p () const { return true; }
  bool integral_p (T) const { return true; }
  T step (T, T) const;
  T apply_step (T, unsigned int, T) const;
  bool can_elide_p (T) const { return true; }
  void note_representative (T *, T) {}
};

/* Create a new builder for a vector with FULL_NELTS elements.
   Initially encode the value as NPATTERNS interleaved patterns with
   NELTS_PER_PATTERN elements each.  */

template<typename T>
inline
int_vector_builder<T>::int_vector_builder (poly_uint64 full_nelts,
					   unsigned int npatterns,
					   unsigned int nelts_per_pattern)
{
  new_vector (full_nelts, npatterns, nelts_per_pattern);
}

/* Return true if elements ELT1 and ELT2 are equal.  */

template<typename T>
inline bool
int_vector_builder<T>::equal_p (T elt1, T elt2) const
{
  return known_eq (elt1, elt2);
}

/* Return the value of element ELT2 minus the value of element ELT1.  */

template<typename T>
inline T
int_vector_builder<T>::step (T elt1, T elt2) const
{
  return elt2 - elt1;
}

/* Return a vector element with the value BASE + FACTOR * STEP.  */

template<typename T>
inline T
int_vector_builder<T>::apply_step (T base, unsigned int factor, T step) const
{
  return base + factor * step;
}

#endif


text:
namespace Tempest {
namespace Detail {

class VFence;
class VTexture;
class VMeshletHelper;

inline void vkAssert(VkResult code){
  if(T_LIKELY(code==VkResult::VK_SUCCESS))
    return;

  switch( code ) {
    case VK_ERROR_OUT_OF_DEVICE_MEMORY:
      throw std::system_error(Tempest::GraphicsErrc::OutOfVideoMemory);
    case VK_ERROR_OUT_OF_HOST_MEMORY:
      //throw std::system_error(Tempest::GraphicsErrc::OutOfHostMemory);
      throw std::bad_alloc();
    case VK_ERROR_DEVICE_LOST:
      throw DeviceLostException();

    default:
      throw std::runtime_error("engine internal error"); //TODO
    }
  }

inline VkFormat nativeFormat(TextureFormat f) {
  switch(f) {
    case TextureFormat::Last:
    case TextureFormat::Undefined:
      return VK_FORMAT_UNDEFINED;
    case TextureFormat::R8:
      return VK_FORMAT_R8_UNORM;
    case TextureFormat::RG8:
      return VK_FORMAT_R8G8_UNORM;
    case TextureFormat::RGB8:
      return VK_FORMAT_R8G8B8_UNORM;
    case TextureFormat::RGBA8:
      return VK_FORMAT_R8G8B8A8_UNORM;
    case TextureFormat::R16:
      return VK_FORMAT_R16_UNORM;
    case TextureFormat::RG16:
      return VK_FORMAT_R16G16_UNORM;
    case TextureFormat::RGB16:
      return VK_FORMAT_R16G16B16_UNORM;
    case TextureFormat::RGBA16:
      return VK_FORMAT_R16G16B16A16_UNORM;
    case TextureFormat::R32F:
      return VK_FORMAT_R32_SFLOAT;
    case TextureFormat::RG32F:
      return VK_FORMAT_R32G32_SFLOAT;
    case TextureFormat::RGB32F:
      return VK_FORMAT_R32G32B32_SFLOAT;
    case TextureFormat::RGBA32F:
      return VK_FORMAT_R32G32B32A32_SFLOAT;
    case TextureFormat::Depth16:
      return VK_FORMAT_D16_UNORM;
    case TextureFormat::Depth24x8:
      return VK_FORMAT_X8_D24_UNORM_PACK32;
    case TextureFormat::Depth24S8:
      return VK_FORMAT_D24_UNORM_S8_UINT;
    case TextureFormat::DXT1:
      return VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
    case TextureFormat::DXT3:
      return VK_FORMAT_BC2_UNORM_BLOCK;
    case TextureFormat::DXT5:
      return VK_FORMAT_BC3_UNORM_BLOCK;
    case TextureFormat::R11G11B10UF:
      return VK_FORMAT_B10G11R11_UFLOAT_PACK32;
    case TextureFormat::RGBA16F:
      return VK_FORMAT_R16G16B16A16_SFLOAT;
    }
  return VK_FORMAT_UNDEFINED;
  }

inline bool nativeIsDepthFormat(VkFormat f){
  return f==VK_FORMAT_D16_UNORM ||
         f==VK_FORMAT_X8_D24_UNORM_PACK32 ||
         f==VK_FORMAT_D32_SFLOAT ||
         f==VK_FORMAT_S8_UINT ||
         f==VK_FORMAT_D16_UNORM_S8_UINT ||
         f==VK_FORMAT_D24_UNORM_S8_UINT ||
         f==VK_FORMAT_D32_SFLOAT_S8_UINT;
  }

inline VkSamplerAddressMode nativeFormat(ClampMode f){
  static const VkSamplerAddressMode vfrm[]={
    VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,
    VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
    VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT,
    VK_SAMPLER_ADDRESS_MODE_REPEAT,
    VK_SAMPLER_ADDRESS_MODE_REPEAT,
    };
  return vfrm[int(f)];
  }

inline VkBlendFactor nativeFormat(RenderState::BlendMode b) {
  switch(b) {
    case RenderState::BlendMode::Zero:             return VK_BLEND_FACTOR_ZERO;
    case RenderState::BlendMode::One:              return VK_BLEND_FACTOR_ONE;
    case RenderState::BlendMode::SrcColor:         return VK_BLEND_FACTOR_SRC_COLOR;
    case RenderState::BlendMode::OneMinusSrcColor: return VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR;
    case RenderState::BlendMode::SrcAlpha:         return VK_BLEND_FACTOR_SRC_ALPHA;
    case RenderState::BlendMode::OneMinusSrcAlpha: return VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
    case RenderState::BlendMode::DstAlpha:         return VK_BLEND_FACTOR_DST_ALPHA;
    case RenderState::BlendMode::OneMinusDstAlpha: return VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA;
    case RenderState::BlendMode::DstColor:         return VK_BLEND_FACTOR_DST_COLOR;
    case RenderState::BlendMode::OneMinusDstColor: return VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR;
    case RenderState::BlendMode::SrcAlphaSaturate: return VK_BLEND_FACTOR_SRC_ALPHA_SATURATE;
    }
  return VK_BLEND_FACTOR_ZERO;
  }

inline VkBlendOp nativeFormat(RenderState::BlendOp op) {
  switch(op) {
    case RenderState::BlendOp::Add:             return VK_BLEND_OP_ADD;
    case RenderState::BlendOp::Subtract:        return VK_BLEND_OP_SUBTRACT;
    case RenderState::BlendOp::ReverseSubtract: return VK_BLEND_OP_REVERSE_SUBTRACT;
    case RenderState::BlendOp::Min:             return VK_BLEND_OP_MIN;
    case RenderState::BlendOp::Max:             return VK_BLEND_OP_MAX;
    }
  return VK_BLEND_OP_ADD;
  }

inline VkCullModeFlags nativeFormat(RenderState::CullMode c) {
  switch(c) {
    case RenderState::CullMode::Back:   return VK_CULL_MODE_BACK_BIT;
    case RenderState::CullMode::Front:  return VK_CULL_MODE_FRONT_BIT;
    case RenderState::CullMode::NoCull: return 0;
    }
  return 0;
  }

inline VkCompareOp nativeFormat(RenderState::ZTestMode zm) {
  switch(zm) {
    case RenderState::ZTestMode::Always:  return VK_COMPARE_OP_ALWAYS;
    case RenderState::ZTestMode::Never:   return VK_COMPARE_OP_NEVER;
    case RenderState::ZTestMode::Greater: return VK_COMPARE_OP_GREATER;
    case RenderState::ZTestMode::Less:    return VK_COMPARE_OP_LESS;
    case RenderState::ZTestMode::GEqual:  return VK_COMPARE_OP_GREATER_OR_EQUAL;
    case RenderState::ZTestMode::LEqual:  return VK_COMPARE_OP_LESS_OR_EQUAL;
    case RenderState::ZTestMode::NOEqual: return VK_COMPARE_OP_NOT_EQUAL;
    case RenderState::ZTestMode::Equal:   return VK_COMPARE_OP_EQUAL;
    }
  return VK_COMPARE_OP_ALWAYS;
  }

inline VkFilter nativeFormat(Filter f){
  static const VkFilter vfrm[]={
    VK_FILTER_NEAREST,
    VK_FILTER_LINEAR,
    VK_FILTER_LINEAR
    };
  return vfrm[int(f)];
  }

inline VkFormat nativeFormat(Decl::ComponentType t) {
  switch(t) {
    case Decl::float0:
    case Decl::count:
      return VK_FORMAT_UNDEFINED;
    case Decl::float1:
      return VK_FORMAT_R32_SFLOAT;
    case Decl::float2:
      return VK_FORMAT_R32G32_SFLOAT;
    case Decl::float3:
      return VK_FORMAT_R32G32B32_SFLOAT;
    case Decl::float4:
      return VK_FORMAT_R32G32B32A32_SFLOAT;
    case Decl::int1:
      return VK_FORMAT_R32_SINT;
    case Decl::int2:
      return VK_FORMAT_R32G32_SINT;
    case Decl::int3:
      return VK_FORMAT_R32G32B32_SINT;
    case Decl::int4:
      return VK_FORMAT_R32G32B32A32_SINT;
    case Decl::uint1:
      return VK_FORMAT_R32_UINT;
    case Decl::uint2:
      return VK_FORMAT_R32G32_UINT;
    case Decl::uint3:
      return VK_FORMAT_R32G32B32_UINT;
    case Decl::uint4:
      return VK_FORMAT_R32G32B32A32_UINT;
    }
  return VK_FORMAT_UNDEFINED;
  }

inline VkIndexType nativeFormat(IndexClass icls) {
  switch(icls) {
    case Detail::IndexClass::i16:
      return VK_INDEX_TYPE_UINT16;
    case Detail::IndexClass::i32:
      return VK_INDEX_TYPE_UINT32;
    }
  return VK_INDEX_TYPE_UINT16;
  }

inline VkDescriptorType nativeFormat(ShaderReflection::Class cls) {
  switch(cls) {
    case ShaderReflection::Ubo:
      return VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
    case ShaderReflection::Texture:
      return VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
    case ShaderReflection::Image:
      return VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
    case ShaderReflection::Sampler:
      return VK_DESCRIPTOR_TYPE_SAMPLER;
    case ShaderReflection::SsboR:
      return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
    case ShaderReflection::SsboRW :
      return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
    case ShaderReflection::ImgR:
      return VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
    case ShaderReflection::ImgRW:
      return VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
    case ShaderReflection::Tlas:
      return VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR;
    case ShaderReflection::Push:
    case ShaderReflection::Count:
      return VK_DESCRIPTOR_TYPE_MAX_ENUM;
    }
  return VK_DESCRIPTOR_TYPE_MAX_ENUM;
  }

inline VkShaderStageFlagBits nativeFormat(ShaderReflection::Stage st) {
  uint32_t stageFlags = 0;
  if(st&ShaderReflection::Compute)
    stageFlags |= VK_SHADER_STAGE_COMPUTE_BIT;
  if(st&ShaderReflection::Vertex)
    stageFlags |= VK_SHADER_STAGE_VERTEX_BIT;
  if(st&ShaderReflection::Control)
    stageFlags |= VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
  if(st&ShaderReflection::Evaluate)
    stageFlags |= VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
  if(st&ShaderReflection::Geometry)
    stageFlags |= VK_SHADER_STAGE_GEOMETRY_BIT;
  if(st&ShaderReflection::Fragment)
    stageFlags |= VK_SHADER_STAGE_FRAGMENT_BIT;
  if(st&ShaderReflection::Task)
    stageFlags |= VK_SHADER_STAGE_TASK_BIT_NV;
  if(st&ShaderReflection::Mesh)
    stageFlags |= VK_SHADER_STAGE_MESH_BIT_NV;
  return VkShaderStageFlagBits(stageFlags);
  }

inline VkPrimitiveTopology nativeFormat(Topology tp) {
  switch(tp) {
    case Topology::Points:
      return VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
    case Topology::Lines:
      return VK_PRIMITIVE_TOPOLOGY_LINE_LIST;
    case Topology::Triangles:
      return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
    }
  return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
  }

class VDevice : public AbstractGraphicsApi::Device {
  private:
    class DataStream;

  public:
    using ResPtr = Detail::DSharedPtr<AbstractGraphicsApi::Shared*>;
    using BufPtr = Detail::DSharedPtr<VBuffer*>;
    using TexPtr = Detail::DSharedPtr<VTexture*>;

    using VkProps = Detail::VulkanInstance::VkProp;

    using SwapChainSupport = VSwapchain::SwapChainSupport;

    VDevice(VulkanInstance& api,const char* gpuName);
    ~VDevice() override;

    struct autoDevice {
      VkDevice impl = nullptr;
      ~autoDevice();
      };

    struct Queue final {
      std::mutex sync;
      VkQueue    impl=nullptr;
      uint32_t   family=0;

      void       submit(uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence);
      void       submit(uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits, VkFence fence, PFN_vkQueueSubmit2KHR fn);
      VkResult   present(VkPresentInfoKHR& presentInfo);
      void       waitIdle();
      };

    struct MemIndex final {
      uint32_t heapId      = 0;
      uint32_t typeId      = 0;
      bool     hostVisible = false;
      };

    VkInstance              instance           =nullptr;
    VkPhysicalDevice        physicalDevice     =nullptr;
    autoDevice              device;

    Queue                   queues[3];
    Queue*                  graphicsQueue=nullptr;
    Queue*                  presentQueue =nullptr;

    std::mutex              allocSync;
    VAllocator              allocator;

    VFramebufferMap         fboMap;

    std::mutex                      meshSync;
    std::unique_ptr<VMeshletHelper> meshHelper;

    VkProps                 props={};

    PFN_vkGetBufferMemoryRequirements2KHR vkGetBufferMemoryRequirements2 = nullptr;
    PFN_vkGetImageMemoryRequirements2KHR  vkGetImageMemoryRequirements2  = nullptr;

    PFN_vkCmdPipelineBarrier2KHR          vkCmdPipelineBarrier2          = nullptr;
    PFN_vkQueueSubmit2KHR                 vkQueueSubmit2                 = nullptr;

    PFN_vkCmdBeginRenderingKHR            vkCmdBeginRenderingKHR         = nullptr;
    PFN_vkCmdEndRenderingKHR              vkCmdEndRenderingKHR           = nullptr;

    PFN_vkGetBufferDeviceAddressKHR                vkGetBufferDeviceAddress                = nullptr;
    PFN_vkGetAccelerationStructureDeviceAddressKHR vkGetAccelerationStructureDeviceAddress = nullptr;

    PFN_vkCreateAccelerationStructureKHR        vkCreateAccelerationStructure        = nullptr;
    PFN_vkDestroyAccelerationStructureKHR       vkDestroyAccelerationStructure       = nullptr;
    PFN_vkGetAccelerationStructureBuildSizesKHR vkGetAccelerationStructureBuildSizes = nullptr;
    PFN_vkCmdBuildAccelerationStructuresKHR     vkCmdBuildAccelerationStructures     = nullptr;

    PFN_vkCmdDrawMeshTasksNV                    vkCmdDrawMeshTasks = nullptr;
    PFN_vkCmdDispatchBase                       vkCmdDispatchBase = nullptr;

    void                    waitIdle() override;
    void                    submit(VCommandBuffer& cmd, VFence* sync);

    VkSurfaceKHR            createSurface(void* hwnd);
    SwapChainSupport        querySwapChainSupport(VkSurfaceKHR surface) { return querySwapChainSupport(physicalDevice,surface); }
    MemIndex                memoryTypeIndex(uint32_t typeBits, VkMemoryPropertyFlags props, VkImageTiling tiling) const;

    using DataMgr = UploadEngine<VDevice,VCommandBuffer,VFence,VBuffer>;
    DataMgr&                dataMgr() const { return *data; }

    void                    allocMeshletHelper();

  private:
    VkPhysicalDeviceMemoryProperties memoryProperties;
    std::unique_ptr<DataMgr>         data;

    void                    waitIdleSync(Queue* q, size_t n);

    void                    implInit(VulkanInstance& api, VkPhysicalDevice pdev);
    void                    pickPhysicalDevice();
    bool                    isDeviceSuitable(VkPhysicalDevice device, const char* gpuName);
    void                    deviceQueueProps(VulkanInstance::VkProp& prop, VkPhysicalDevice device);
    bool                    checkDeviceExtensionSupport(VkPhysicalDevice device);
    auto                    extensionsList(VkPhysicalDevice device) -> std::vector<VkExtensionProperties>;
    bool                    checkForExt(const std::vector<VkExtensionProperties>& list,const char* name);
    SwapChainSupport        querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);

    void                    createLogicalDevice(VulkanInstance& api, VkPhysicalDevice pdev);
  };

}}


text:
from __future__ import print_function

import pygion
from pygion import task

@task
def main():
    pygion.print_once("Hello, Legion!")

if __name__ == '__main__':
    main()


text:
/**
 * Created by dhnishi on 4/1/15.
 */

/// <reference path="scripts/TimerHelpers.ts" />
/// <reference path="scripts/PauseTimer.ts" />

var DEFAULT_WORK_MINUTES = 30;
var DEFAULT_BREAK_MINUTES = 5;
var DEFAULT_IDLE_DURATION = 60 * 5;

var WINDOW_WIDTH = 500;
var WINDOW_HEIGHT = 210;
var DISRUPTOR_WIDTH = 750;
var DISRUPTOR_HEIGHT = 250;

var SECONDS = 1000;
var MINUTES = SECONDS * 60;
var HOURS = MINUTES * 60;

declare var chrome: any;

// TODO: Remove lastDuration -- or refactor it into TimerHelpers.
var lastDuration = null;

function initializeStorageDefaults(callback) {
    chrome.storage.sync.get([
        "remindOnClose",
        "clearAlarmsOnClose",
        "times",
        "showDisruptor"
    ], (data) => {
        if (data.remindOnClose === undefined) {
            chrome.storage.sync.set({remindOnClose: true});
        }
        if (data.clearAlarmsOnCloses === undefined) {
        }
        if (data.times === undefined) {
            var times = {
                work: DEFAULT_WORK_MINUTES,
                break: DEFAULT_BREAK_MINUTES
            };
            chrome.storage.sync.set({times: times});
        }
        if (data.showDisruptor === undefined) {
            chrome.storage.sync.set({showDisruptor: true});
        }
        callback();
    });
}

var createWindow = () => {
    chrome.app.window.create("window.html", {
        "bounds": {
            "width": WINDOW_WIDTH,
            "height": WINDOW_HEIGHT
        },
        "resizable": false
    }, (appWindow) => {
        appWindow.onClosed.addListener(() => {
            chrome.storage.sync.get("remindOnClose", (data) => {
                var remindOnClose = data.remindOnClose;
                if (remindOnClose) {
                    remindRunningAlarmsNotification();
                }
            });
            chrome.storage.sync.get("clearAlarmsOnClose", (data) => {
                var clearAlarms = data.clearAlarmsOnClose;
                if (clearAlarms) {
                    chrome.alarms.clearAll();
                }
            });
        });
    });
};

var createDisruptor = () => {
    chrome.storage.sync.get("showDisruptor", (data) => {
       if (data.showDisruptor) {
           var disruptorWindow = chrome.app.window.get("disruptor");
           if (disruptorWindow === null) {
               chrome.app.window.create("disruptor.html", {
                   id: "disruptor",
                   "bounds": {
                       "width": DISRUPTOR_WIDTH,
                       "height": DISRUPTOR_HEIGHT
                   },
                   "resizable": false
               }, (appWindow) => {
                   appWindow.maximize();
               });
           } else {
               disruptorWindow.show();
           }
       }
    });
};

function remindRunningAlarmsNotification() {
    var options = {
        type: "basic",
        title: "pause is still running in the background.",
        message: "Your work/break reminders will continue to fire.",
        buttons: [{title: "Don't remind me again"}, {title: "Don't run alarms after closing pause."}],
        iconUrl: "pause-512.png"
    };

    chrome.notifications.clear("onClose", (wasCleared) => {
        chrome.notifications.create("onClose", options, (notificationId) => {
            console.log("Triggered close notification.", notificationId);
        });
    });
};

chrome.app.runtime.onLaunched.addListener(function() {
    initializeStorageDefaults(() => {
        chrome.storage.local.remove("pauseFromIdle");
        chrome.storage.local.get("storedAlarm", alarm => {
            if (alarm.storedAlarm === undefined) {
                chrome.alarms.getAll(alarms => {
                    if (alarms.length === 0) {
                        scheduleAlarm("work");
                    }
                });
            }
        });
        createWindow();
    });
});

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request === "scheduleWork") {
        scheduleAlarm("work");
    } else if (request === "scheduleBreak") {
        scheduleAlarm("break");
    } else if (request.message === "scheduleAlarm") {
        scheduleAlarm(request.type, request.duration);
    }
});

// TODO: Move this function into TimerHelpers.
function scheduleAlarm(alarmType, timeOverride?) {
    chrome.alarms.clearAll();

    // TODO: Refactor this into a callback when the message is received.
    if (alarmType === "break") {
        createDisruptor();
    } else {
        var disruptorWindow = chrome.app.window.get("disruptor");
        if (disruptorWindow != null) {
            disruptorWindow.close();
        }
    }

    if (timeOverride === undefined) {
        chrome.storage.sync.get("times", (data) => {
                var myData = data.times;
                var alarmTime = myData[alarmType];
                console.log(alarmTime);
                chrome.alarms.create(alarmType, { when: Date.now() + alarmTime * MINUTES});
                lastDuration = alarmTime * 60;
            }
        );
    } else {
        chrome.alarms.create(alarmType, { when: Date.now() + timeOverride * SECONDS});
        lastDuration = timeOverride;
    }
};

chrome.alarms.onAlarm.addListener(alarm => {
    console.log("We received an alarm!", alarm);
    if (alarm.name === "work") {
        var options = {
            type: "basic",
            title: "Time for a break!",
            message: "Your work time has ended.",
            buttons: [{ title: "Skip break" }, { title: "Postpone 10 minutes"}],
            iconUrl: "pause-512.png"
        };
        chrome.notifications.clear("breakTime", (wasCleared) => {
            chrome.notifications.create("breakTime", options, (notificationId) => {
                console.log("Triggered break notification.", notificationId);
            });
        });
        scheduleAlarm("break");
    } else if (alarm.name === "break") {
        scheduleAlarm("work");
        var workMessage = {
            type: "basic",
            title: "Time for work!",
            message: "Your break time has ended.",
            iconUrl: "pause-512.png"
        };
        chrome.notifications.clear("workTime", (wasCleared) => {
            chrome.notifications.create("workTime", workMessage, (notificationId) => {
                console.log("Triggered break notification.", notificationId);
            });
        });
        scheduleAlarm("work");
    } else if (alarm.name === "restoreAlarm") {
        restoreStoredAlarm();
    }
});

chrome.notifications.onButtonClicked.addListener((notificationId : string, buttonIndex : number) => {
    if (notificationId === "breakTime") {
        var SKIP_BREAK = 0;
        // var TAKE_10 = 1;

        if (buttonIndex === SKIP_BREAK) {
            scheduleAlarm("work");
        } else {
            scheduleAlarm("work", 10 * 60);
        }
    } else if (notificationId === "onClose") {
        var DONT_REMIND_ME_AGAIN = 0;
        var DONT_RUN_ALARMS = 1;

        if (buttonIndex === DONT_REMIND_ME_AGAIN) {
            chrome.storage.sync.set({remindOnClose: false});
        } else { // Don"t run alarms.
            chrome.storage.sync.set({clearAlarmsOnClose: true});
            chrome.alarms.clearAll();
        }
    }
});

chrome.notifications.onClicked.addListener(notificationId => {
    var appWindows = chrome.app.window.getAll();
    if (appWindows.length) {
        appWindows[0].show();
    } else {
        createWindow();
    }
});

chrome.idle.setDetectionInterval(DEFAULT_IDLE_DURATION);
chrome.idle.onStateChanged.addListener((state) => {
    console.log("Idle changed: ", state);
    if (state === "idle") {
        chrome.alarms.get("work", alarm => {
            if (alarm === undefined) {
                return;
            }

            pauseAlarm();
            // TODO: Set an alarm to invalidate the stored alarm after a full break of time.
            chrome.storage.local.set({ pauseFromIdle: true});
        });
    } else if (state === "active") {
        chrome.storage.local.get(["pauseFromIdle"], data => {
            if (data.pauseFromIdle) {
                chrome.storage.local.set({ pauseFromIdle: false});
                restoreStoredAlarm();
            }
        });
    }
    // TODO: Check if alarm is expired. Due to a chrome.alarms bug, we need to work around this.
});


text:
<!DOCTYPE html>

Please input a number between 1 and 10:

<input id="numb" type="number">

<button type="button" onclick="myFunction()">Submit</button>


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_81a.cpp
Label Definition File: CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close.label.xml
Template File: source-sinks-81a.tmpl.cpp
*/
/*
 * @description
 * CWE: 775 Missing Release of File Descriptor or Handle After Effective Lifetime
 * BadSource:  Open a file using CreateFile()
 * Sinks:
 *    GoodSink: Close the file using CloseHandle()
 *    BadSink : Do not close file
 * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
 *
 * */

#include "std_testcase.h"
#include "CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_81.h"

namespace CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_81
{

#ifndef OMITBAD

void bad()
{
    HANDLE data;
    /* Initialize data */
    data = INVALID_HANDLE_VALUE;
    /* POTENTIAL FLAW: Open a file without closing it */
    data = CreateFile("BadSource_w32CreateFile.txt",
                      (GENERIC_WRITE|GENERIC_READ),
                      0,
                      NULL,
                      OPEN_ALWAYS,
                      FILE_ATTRIBUTE_NORMAL,
                      NULL);
    const CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_81_base& baseObject = CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_81_bad();
    baseObject.action(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G uses the BadSource with the GoodSink */
static void goodB2G()
{
    HANDLE data;
    /* Initialize data */
    data = INVALID_HANDLE_VALUE;
    /* POTENTIAL FLAW: Open a file without closing it */
    data = CreateFile("BadSource_w32CreateFile.txt",
                      (GENERIC_WRITE|GENERIC_READ),
                      0,
                      NULL,
                      OPEN_ALWAYS,
                      FILE_ATTRIBUTE_NORMAL,
                      NULL);
    const CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_81_base& baseObject = CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_81_goodB2G();
    baseObject.action(data);
}

void good()
{
    goodB2G();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

using namespace CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_81; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
<?php

namespace Faker\Provider\ja_JP;

class Company extends \Faker\Provider\Company
{
    protected static $formats = array(
        '{{companyPrefix}} {{lastName}}'
    );

    protected static $companyPrefix = array('株式会社', '有限会社');

    public static function companyPrefix()
    {
        return static::randomElement(static::$companyPrefix);
    }
}


text:
/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#include <fcntl.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>

#include <cerrno>
#include <cstring>
#include <stdexcept>

#include "vast/config.hpp"
#include "vast/detail/assert.hpp"
#include "vast/detail/posix.hpp"
#include "vast/detail/raise_error.hpp"

namespace vast {
namespace detail {

int uds_listen(const std::string& path) {
  int fd;
  if ((fd = ::socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
    return fd;
  ::sockaddr_un un;
  std::memset(&un, 0, sizeof(un));
  un.sun_family = AF_UNIX;
  std::strncpy(un.sun_path, path.data(), sizeof(un.sun_path));
  ::unlink(path.c_str()); // Always remove previous socket file.
  auto sa = reinterpret_cast<sockaddr*>(&un);
  if (::bind(fd, sa, sizeof(un)) < 0 || ::listen(fd, 10) < 0) {
    ::close(fd);
    return -1;
  }
  return fd;
}

int uds_accept(int socket) {
  if (socket < 0)
    return -1;
  int fd;
  ::sockaddr_un un;
  socklen_t size = sizeof(un);
  if ((fd = ::accept(socket, reinterpret_cast<::sockaddr*>(&un), &size)) < 0)
    return -1;
  return fd;
}

int uds_connect(const std::string& path) {
  int fd;
  if ((fd = ::socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
    return fd;
  ::sockaddr_un un;
  std::memset(&un, 0, sizeof(un));
  un.sun_family = AF_UNIX;
  std::strncpy(un.sun_path, path.data(), sizeof(un.sun_path));
  if (::connect(fd, reinterpret_cast<sockaddr*>(&un), sizeof(un)) < 0)
    return -1;
  return fd;
}

// On Mac OS, CMSG_SPACE is for some reason not a constant expression.
VAST_DIAGNOSTIC_PUSH
VAST_DIAGNOSTIC_IGNORE_VLA_EXTENSION

bool uds_send_fd(int socket, int fd) {
  if (socket < 0)
    return -1;
  char dummy = '*';
  ::iovec iov[1];
  iov[0].iov_base = &dummy;
  iov[0].iov_len = sizeof(dummy);
  char ctrl_buf[CMSG_SPACE(sizeof(int))];
  std::memset(ctrl_buf, 0, CMSG_SPACE(sizeof(int)));
  // Setup message header.
  ::msghdr m;
  std::memset(&m, 0, sizeof(struct msghdr));
  m.msg_name = nullptr;
  m.msg_namelen = 0;
  m.msg_iov = iov;
  m.msg_iovlen = 1;
  m.msg_controllen = CMSG_SPACE(sizeof(int));
  m.msg_control = ctrl_buf;
  // Setup control message header.
  auto c = CMSG_FIRSTHDR(&m);
  c->cmsg_level = SOL_SOCKET;
  c->cmsg_type = SCM_RIGHTS;
  c->cmsg_len = CMSG_LEN(sizeof(int));
  *reinterpret_cast<int*>(CMSG_DATA(c)) = fd;
  // Send a message.
  return ::sendmsg(socket, &m, 0) > 0;
}

int uds_recv_fd(int socket) {
  if (socket < 0)
    return -1;
  char ctrl_buf[CMSG_SPACE(sizeof(int))];
  std::memset(ctrl_buf, 0, CMSG_SPACE(sizeof(int)));
  char dummy;
  ::iovec iov[1];
  iov[0].iov_base = &dummy;
  iov[0].iov_len = sizeof(dummy);
  // Setup message header.
  ::msghdr m;
  std::memset(&m, 0, sizeof(struct msghdr));
  m.msg_name = nullptr;
  m.msg_namelen = 0;
  m.msg_control = ctrl_buf;
  m.msg_controllen = CMSG_SPACE(sizeof(int));
  m.msg_iov = iov;
  m.msg_iovlen = 1;
  // Receive a message.
  if (::recvmsg(socket, &m, 0) <= 0)
    return -1;
  // Iterate over control message headers until we find the descriptor.
  for (auto c = CMSG_FIRSTHDR(&m); c != nullptr; c = CMSG_NXTHDR(&m, c))
    if (c->cmsg_level == SOL_SOCKET && c->cmsg_type == SCM_RIGHTS)
      return *reinterpret_cast<int*>(CMSG_DATA(c));
  return -1;
}

VAST_DIAGNOSTIC_POP
int unix_domain_socket::listen(const std::string& path) {
  return detail::uds_listen(path);
}

unix_domain_socket unix_domain_socket::accept(const std::string& path) {
  auto server = detail::uds_listen(path);
  if (server != -1)
    return unix_domain_socket{detail::uds_accept(server)};
  return unix_domain_socket{};
}

unix_domain_socket unix_domain_socket::connect(const std::string& path) {
  return unix_domain_socket{detail::uds_connect(path)};
}

unix_domain_socket::unix_domain_socket(int fd) : fd_{fd} {
}

unix_domain_socket::operator bool() const {
  return fd_ != -1;
}

bool unix_domain_socket::send_fd(int fd) {
  VAST_ASSERT(*this);
  return detail::uds_send_fd(fd_, fd);
}

int unix_domain_socket::recv_fd() {
  VAST_ASSERT(*this);
  return detail::uds_recv_fd(fd_);
}

int unix_domain_socket::fd() const {
  return fd_;
}

namespace {

bool make_nonblocking(int fd, bool flag) {
  auto flags = ::fcntl(fd, F_GETFL, 0);
  if (flags == -1)
    return false;
  flags = flag ? flags | O_NONBLOCK : flags & ~O_NONBLOCK;
  return ::fcntl(fd, F_SETFL, flags) != -1;
}

} // namespace <anonymous>

bool make_nonblocking(int fd) {
  return make_nonblocking(fd, true);
}

bool make_blocking(int fd) {
  return make_nonblocking(fd, false);
}

bool poll(int fd, int usec) {
  fd_set rdset;
  FD_ZERO(&rdset);
  FD_SET(fd, &rdset);
  timeval timeout{0, usec};
  auto rc = ::select(fd + 1, &rdset, nullptr, nullptr, &timeout);
  if (rc < 0) {
    switch (rc) {
      default:
        VAST_RAISE_ERROR(std::logic_error, "unhandled select() error");
      case EINTR:
      case ENOMEM:
        return false;
    }
  }
  return FD_ISSET(fd, &rdset);
}

bool close(int fd) {
  int result;
  do {
    result = ::close(fd);
  } while (result < 0 && errno == EINTR);
  return result == 0;
}

bool read(int fd, void* buffer, size_t bytes, size_t* got) {
  ssize_t taken;
  do {
    taken = ::read(fd, buffer, bytes);
  } while (taken < 0 && errno == EINTR);
  if (taken <= 0) // EOF == 0, error == -1
    return false;
  if (got)
    *got = static_cast<size_t>(taken);
  return true;
}

bool write(int fd, const void* buffer, size_t bytes, size_t* put) {
  auto total = size_t{0};
  auto buf = reinterpret_cast<const uint8_t*>(buffer);
  while (total < bytes) {
    ssize_t written;
    do {
      written = ::write(fd, buf + total, bytes - total);
    } while (written < 0 && errno == EINTR);
    if (written <= 0)
      return false;
    total += static_cast<size_t>(written);
  }
  if (put)
    *put = total;
  return true;
}

bool seek(int fd, size_t bytes) {
  return ::lseek(fd, bytes, SEEK_CUR) != -1;
}

} // namespace detail
} // namespace vast


text:
function download_html(filename, html) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/html;charset=utf-8,' + encodeURIComponent(html));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}


text:
<!DOCTYPE html>
<html lang="de">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Labeling Example</title>

    <!-- Core CSS -->
    <link href="../build/css/bootstrap.css" rel="stylesheet">
    <link href="../build/css/ol.css" rel="stylesheet">
    <link href="../build/css/anol.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
   <script type="text/javascript" src="../build/anol.js"></script>

  </head>

  <body ng-app="example" ng-controller="ExampleController">
    <!-- map -->
    <div anol-map style="width:600px; height: 400px; border: 1px solid black;">
      <div anol-zoom></div>
    </div>
  </body>
</html>


text:
..  index:: WOPI requests; GetShareUrl (containers), GetShareUrl (containers)

..  |operation| replace:: GetShareUrl

..  _GetShareUrl (containers):

GetShareUrl (containers)
==============================

:Required for: |ios|

..  seealso::

    :ref:`GetShareUrl (files)`

..  default-domain:: http

..  post:: /wopi/containers/(container_id)

    The |operation| operation returns a :term:`Share URL` that is suitable for viewing a shared container when launched
    in a web browser. A host can support multiple Share URL types, as described by the :term:`SupportedShareUrlTypes`
    property. The **X-WOPI-UrlType** request header contains the Share URL type that should be returned.

    If the **X-WOPI-UrlType** header is not present or contains a value that is invalid or not supported by the host,
    the host should respond with a :http:statuscode:`501`.

    ..  include:: /_fragments/common_containers_params.rst

    :reqheader X-WOPI-Override:
        The **string** ``GET_SHARE_URL``. Required.

    :reqheader X-WOPI-UrlType:
        A **string** indicating what Share URL type to return. Required.

    :code 200: Success
    :code 401: Invalid :term:`access token`
    :code 404: Resource not found/user unauthorized
    :code 500: Server error
    :code 501: Operation not supported

    ..  include:: /_fragments/common_headers.rst

Response
--------

..  include:: /_fragments/json_response_required.rst

ShareUrl
    A URI that points to a webpage that allows the user to access the container. Required.

    ..  seealso::

        :term:`Share Url`


text:
<?php

// Note that this DB singleton is not a db connection, just a db wrapper
class DB extends Pattern_Singleton {
	// adapters, etc would be great, just need this done for PL2015.
	// Maybe later, hence so many TODOs

	public $connection;

	public function connect($isRequired = false) {

		if ($this->connection && !$isRequired) {
			return;
		}
		unset($this->connection);

		// A db connection class normally requires a resource target
		// but this example only has one possible target
		$tries = 0;
		do {
			$tries++;
			try {
				$this->connection = new CustomDB();
			} catch (Exception $e) {
				if (!$this->isReconnectError($e)) {
					throw $e;
				}
				$config = Configuration::getInstance();
				if ($tries > $config->DB_MAX_TRIES) {
					// TODO proper exceptions
					throw new Exception('Failed to create connection.', $e->getCode(), $e);
				}
				usleep(rand($config->DB_USLEEP_MIN, $config->DB_USLEEP_MAX));
			}
		} while (!$this->connection);

	}

	public function find($className, $args) {
		$config = Configuration::getInstance();

		$whereClause = $this->whereClause($className, $args);
		$params = $this->params($className, $args);
		$sql = 'SELECT * FROM ' . $className::getTableName() . $whereClause;

		$forceReconnect = false;
		$tries = 0;
		while (true) {
			$tries++;
			$this->connect($forceReconnect);
			try {
				$result = $this->connection->execute($sql, $params, $className);
				break;
			} catch (Exception $e) {
				if ($tries > $config->DB_MAX_TRIES) {
					// TODO proper exceptions
					throw new Exception('Failed to find.', $e->getCode(), $e);
				}
				if (!$this->isRetryableError($e)) {
					throw $e;
				}
				if ($this->isReconnectError($e)) {
					$forceReconnect = true;
				}
				usleep(rand($config->DB_USLEEP_MIN, $config->DB_USLEEP_MAX));
				continue;
			}
		}
		return $result;
	}

	public function isReconnectError(Exception $e) {
		// TODO Full set of reconnect error codes
		if (in_array($e->getCode(), array(1040,2013))) {
			return true;
		}
		return false;
	}

	public function isRetryableError(Exception $e) {
		// TODO Full set of retry error codes
		if (in_array($e->getCode(), array(1205,1213))) {
			return true;
		}
		return false;
	}

	private function params($className, $args) {
		$metadata = $className::getMetadata();
		foreach ($args as $columnName => $columnValue) {
			if (!$metadata[$columnName]) {
				// TODO proper exceptions
				throw Exception('Field does not exist');
			}
			// @TODO implement non-equality, nulls, input normalization, etc
			$params[$columnName] = $columnValue;
		}
		return $params;
	}

	private function whereClause($className, $args) {
		$metadata = $className::getMetadata();
		foreach ($args as $columnName => $columnValue) {
			if (!$metadata[$columnName]) {
				// TODO proper exceptions
				throw Exception('Field does not exist');
			}
			// @TODO implement non-equalities, nulls, etc etc
			if (isset($sql)) {
				$sql .= " AND $columnName = :$columnName";
			} else {
				$sql = " WHERE $columnName = :$columnName";
			}
		}
		return $sql;
	}
}


text:
namespace device {

class BluetoothDeviceCast;

// This class allows callers to discover, connect to, and interact with remote
// BLE peripherals. Upon creation, it scans for devices and observes the Cast
// bluetooth stack for events in remote BLE peripherals. This class does not
// support functionality needed only for Bluetooth Classic. It also does not
// act as a GATT server.
//
// THREADING
// This class is created and called on a single thread. It makes aysnchronous
// calls to the Cast bluetooth stack, which may live on another thread. Unless
// noted otherwise, callbacks will always be posted on the calling thread.
class DEVICE_BLUETOOTH_EXPORT BluetoothAdapterCast
    : public BluetoothAdapter,
      chromecast::bluetooth::GattClientManager::Observer,
      chromecast::bluetooth::LeScanManager::Observer {
 public:
  // Do not call this constructor directly; use CreateAdapter() instead. Neither
  // |gatt_client_manager| nor |le_scan_manager| are owned by this class. Both
  // must outlive |this|.
  BluetoothAdapterCast(
      chromecast::bluetooth::GattClientManager* gatt_client_manager,
      chromecast::bluetooth::LeScanManager* le_scan_manager);

  // BluetoothAdapter implementation
  // |callback| will be executed asynchronously on the calling sequence.
  void Initialize(base::OnceClosure callback) override;
  std::string GetAddress() const override;
  std::string GetName() const override;
  void SetName(const std::string& name,
               const base::Closure& callback,
               const ErrorCallback& error_callback) override;
  bool IsInitialized() const override;
  bool IsPresent() const override;
  bool IsPowered() const override;
  void SetPowered(bool powered,
                  const base::Closure& callback,
                  const ErrorCallback& error_callback) override;
  bool IsDiscoverable() const override;
  void SetDiscoverable(bool discoverable,
                       const base::Closure& callback,
                       const ErrorCallback& error_callback) override;
  bool IsDiscovering() const override;
  UUIDList GetUUIDs() const override;
  void CreateRfcommService(
      const BluetoothUUID& uuid,
      const ServiceOptions& options,
      const CreateServiceCallback& callback,
      const CreateServiceErrorCallback& error_callback) override;
  void CreateL2capService(
      const BluetoothUUID& uuid,
      const ServiceOptions& options,
      const CreateServiceCallback& callback,
      const CreateServiceErrorCallback& error_callback) override;
  void RegisterAdvertisement(
      std::unique_ptr<BluetoothAdvertisement::Data> advertisement_data,
      const CreateAdvertisementCallback& callback,
      const AdvertisementErrorCallback& error_callback) override;
  void SetAdvertisingInterval(
      const base::TimeDelta& min,
      const base::TimeDelta& max,
      const base::Closure& callback,
      const AdvertisementErrorCallback& error_callback) override;
  void ResetAdvertising(
      const base::Closure& callback,
      const AdvertisementErrorCallback& error_callback) override;
  BluetoothLocalGattService* GetGattService(
      const std::string& identifier) const override;
  base::WeakPtr<BluetoothAdapter> GetWeakPtr() override;
  bool SetPoweredImpl(bool powered) override;
  void StartScanWithFilter(
      std::unique_ptr<device::BluetoothDiscoveryFilter> discovery_filter,
      DiscoverySessionResultCallback callback) override;
  void UpdateFilter(
      std::unique_ptr<device::BluetoothDiscoveryFilter> discovery_filter,
      DiscoverySessionResultCallback callback) override;
  void StopScan(DiscoverySessionResultCallback callback) override;
  void RemovePairingDelegateInternal(
      BluetoothDevice::PairingDelegate* pairing_delegate) override;

  base::WeakPtr<BluetoothAdapterCast> GetCastWeakPtr();

  // |factory_cb| is used to inject a factory method from ChromecastService into
  // this class. It will be invoked when Create() is called.
  // TODO(slan): Remove this once this class talks to a dedicated Bluetooth
  // service (b/76155468)
  using FactoryCb =
      base::RepeatingCallback<scoped_refptr<BluetoothAdapterCast>()>;
  static void SetFactory(FactoryCb factory_cb);

  // Resets the factory callback for test scenarios.
  static void ResetFactoryForTest();

  // Creates a BluetoothAdapterCast using the |factory_cb| set in SetFactory().
  // This method is intended to be called only by the WebBluetooth code in
  // //device/bluetooth/.
  static scoped_refptr<BluetoothAdapter> Create();

 private:
  ~BluetoothAdapterCast() override;

  // chromecast::bluetooth::GattClientManager::Observer implementation:
  void OnConnectChanged(
      scoped_refptr<chromecast::bluetooth::RemoteDevice> device,
      bool connected) override;
  void OnMtuChanged(scoped_refptr<chromecast::bluetooth::RemoteDevice> device,
                    int mtu) override;
  void OnCharacteristicNotification(
      scoped_refptr<chromecast::bluetooth::RemoteDevice> device,
      scoped_refptr<chromecast::bluetooth::RemoteCharacteristic> characteristic,
      std::vector<uint8_t> value) override;

  // chromecast::bluetooth::LeScanManager::Observer implementation:
  void OnNewScanResult(chromecast::bluetooth::LeScanResult) override;
  void OnScanEnableChanged(bool enabled) override;

  // Helper method to access |devices_| as BluetoothDeviceCast*.
  BluetoothDeviceCast* GetCastDevice(const std::string& address);

  // Creates a BluetoothDeviceCast for |remote_device|, adds it to |devices_|,
  // and updates observers.
  void AddDevice(
      scoped_refptr<chromecast::bluetooth::RemoteDevice> remote_device);

  // Called when the scanner has enabled scanning.
  void OnScanEnabled(
      std::unique_ptr<chromecast::bluetooth::LeScanManager::ScanHandle>
          scan_handle);
  void OnGetDevice(scoped_refptr<chromecast::bluetooth::RemoteDevice> device);
  void OnGetScanResults(
      std::vector<chromecast::bluetooth::LeScanResult> results);

  struct DiscoveryParams {
    DiscoveryParams(std::unique_ptr<device::BluetoothDiscoveryFilter> filter,
                    base::Closure success_callback,
                    DiscoverySessionErrorCallback error_callback);
    DiscoveryParams(DiscoveryParams&& params) noexcept;
    DiscoveryParams& operator=(DiscoveryParams&& params);
    ~DiscoveryParams();
    std::unique_ptr<device::BluetoothDiscoveryFilter> filter;
    base::Closure success_callback;
    DiscoverySessionErrorCallback error_callback;
  };

  std::queue<DiscoveryParams> pending_discovery_requests_;

  int num_discovery_sessions_ = 0;

  // Maps address to ScanResults received from |le_scan_manager_|.
  std::map<std::string, std::list<chromecast::bluetooth::LeScanResult>>
      pending_scan_results_;

  chromecast::bluetooth::GattClientManager* const gatt_client_manager_;
  chromecast::bluetooth::LeScanManager* const le_scan_manager_;

  std::unique_ptr<chromecast::bluetooth::LeScanManager::ScanHandle>
      scan_handle_;

  bool powered_ = true;
  bool initialized_ = false;

  std::string name_;

  SEQUENCE_CHECKER(sequence_checker_);
  base::WeakPtrFactory<BluetoothAdapterCast> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(BluetoothAdapterCast);
};

}  // namespace device

#endif  // DEVICE_BLUETOOTH_CAST_BLUETOOTH_ADAPTER_CAST_H_


text:
/**
 * @fileoverview Tests for phonenumber.js.
 */

goog.provide('firebaseui.auth.PhoneNumberTest');

goog.require('firebaseui.auth.PhoneNumber');
goog.require('goog.testing.jsunit');

goog.setTestOnly('firebaseui.auth.PhoneNumberTest');

function testPhoneNumber() {
  var countryId = '45-DK-0';
  var nationalNumber = '6505550101';
  var phoneNumber = new firebaseui.auth.PhoneNumber(countryId, nationalNumber);
  assertEquals(countryId, phoneNumber.countryId);
  assertEquals(nationalNumber, phoneNumber.nationalNumber);
  assertEquals('+45' + nationalNumber, phoneNumber.getPhoneNumber());
}

function testPhoneNumber_badCountryId() {
  var countryId = 'iAmInvalid';
  var nationalNumber = '6505550101';
  var phoneNumber = new firebaseui.auth.PhoneNumber(countryId, nationalNumber);
  assertThrows(function() {
    phoneNumber.getPhoneNumber();
  });
}

function testPhoneNumber_fromString() {
  // Empty string.
  assertNull(firebaseui.auth.PhoneNumber.fromString(''));

  // Missing plus sign.
  assertNull(firebaseui.auth.PhoneNumber.fromString('11234567890'));

  // Invalid.
  assertNull(firebaseui.auth.PhoneNumber.fromString('bla1234567890'));

  // Valid number with +1 code should always map to US.
  assertObjectEquals(
      new firebaseui.auth.PhoneNumber('1-US-0', '1234567890'),
      firebaseui.auth.PhoneNumber.fromString('+11234567890'));

  // Phone number with no national number should still be accepted.
  assertObjectEquals(
      new firebaseui.auth.PhoneNumber('1-US-0', ''),
      firebaseui.auth.PhoneNumber.fromString('+1'));

  // Other codes that are shared will just pick the first match instead of the
  // more likely 44-GB-0 country code.
  assertObjectEquals(
      new firebaseui.auth.PhoneNumber('44-GG-0', '1234567890'),
      firebaseui.auth.PhoneNumber.fromString('+441234567890'));

  // Parsing should not reformat the number.
  assertObjectEquals(
      new firebaseui.auth.PhoneNumber('1-US-0', '(123) 456-7890'),
      firebaseui.auth.PhoneNumber.fromString(' +1 (123) 456-7890 '));
  assertObjectEquals(
      new firebaseui.auth.PhoneNumber('1-US-0', '(123)456-7890'),
      firebaseui.auth.PhoneNumber.fromString('+1(123)456-7890'));

  // Parsing a country code that is only used by one country.
  assertObjectEquals(
      new firebaseui.auth.PhoneNumber('52-MX-0', '1234567890'),
      firebaseui.auth.PhoneNumber.fromString('+521234567890'));
}

function testPhoneNumber_getCountry() {
  var phoneNumber = new firebaseui.auth.PhoneNumber('52-MX-0', '1234567890');
  assertEquals('MX', phoneNumber.getCountry().iso2_cc);

  phoneNumber = new firebaseui.auth.PhoneNumber('1-US-0', '1234567890');
  assertEquals('US', phoneNumber.getCountry().iso2_cc);

  phoneNumber = new firebaseui.auth.PhoneNumber('invalid', '1234567890');
  assertNull(phoneNumber.getCountry());
}