text:
package com.rgi.geopackage.extensions;

/**
 * GeoPackage Extension
 *
 *

 * The gpkg_extensions table or updateable view in a GeoPackage is used to
 * indicate that a particular extension applies to a GeoPackage, a table in a
 * GeoPackage or a column of a table in a GeoPackage. An application that
 * access a GeoPackage can query the gpkg_extensions table instead of the
 * contents of all the user data tables to determine if it has the required
 * capabilities to read or write to tables with extensions, and to "fail fast"
 * and return an error message if it does not.
 *

 *
 * @see
 *                 OGC® GeoPackage Encoding Standard - 2.5.2.1.1. Table
 *                 Definition
 * @see OGC®
 *                 GeoPackage Encoding Standard - Table 17. GeoPackage
 *                 Extensions Table or View Definition (Table or View Name:
 *                 gpkg_extensions)
 *
 * @author Luke Lambert
 *
 */
public class Extension
{
    /**
     * An object representation of an entry in the GeoPackage extensions table
     *
     * @param tableName
     *             Name of the table that requires the extension. When NULL,
     *             the extension is required for the entire GeoPackage. SHALL
     *             NOT be NULL when the column_name is not NULL
     * @param columnName
     *             Name of the column that requires the extension. When NULL,
     *             the extension is required for the entire table
     * @param extensionName
     *             The case sensitive name of the extension that is required,
     *             in the form <author>_<extension_name> where <author>
     *             indicates the person or organization that developed and
     *             maintains the extension. The valid character set for
     *             <author> is [a-zA-Z0-9]. The valid character set for
     *             <extension_name> is [a-zA-Z0-9_]
     * @param definition
     *             Definition of the extension in the form specified by the
     *             template in
     *             GeoPackage Extension Template (Normative) or reference
     *             thereto.
     * @param scope
     *             Indicates scope of extension effects on readers / writers:
     *             "read-write" or "write-only" in lowercase.
     */
    protected Extension(final String tableName,
                        final String columnName,
                        final String extensionName,
                        final String definition,
                        final String scope)
    {
        if(columnName != null && tableName == null)
        {
            throw new IllegalArgumentException("Table name may not be null if column name is not null"); // Requirement 80
        }

        if(tableName != null && tableName.isEmpty())
        {
            throw new IllegalArgumentException("If table name is not null, it may not be empty");
        }

        if(columnName != null && columnName.isEmpty())
        {
            throw new IllegalArgumentException("If column name is not null, it may not be empty");
        }

        if(extensionName == null || extensionName.isEmpty())
        {
            throw new IllegalArgumentException("Extension name may not be null or empty");
        }

        if(!extensionName.matches(Extension.ExtensionNameRegularExpression))
        {
            throw new IllegalArgumentException("Extension name must be a value of the form <author>_<extension_name> where <author> indicates the person or organization that developed and maintains the extension. The valid character set for <author> SHALL be [a-zA-Z0-9]. The valid character set for <extension_name> SHALL be [a-zA-Z0-9_]");   // Requirement 82
        }

        if(definition == null || definition.isEmpty())
        {
            throw new IllegalArgumentException("Definition may not be null or empty");
        }

        if(Scope.fromText(scope) == null)
        {
            throw new IllegalArgumentException("Bad value for scope");
        }

        this.tableName     = tableName;
        this.columnName    = columnName;
        this.extensionName = extensionName;
        this.definition    = definition;
        this.scope         = scope;
    }

    /**
     * @param inTableName
     *             the tableName corresponding to other Extension
     * @param inColumnName
     *             the columnName corresponding to other Extension
     * @param inExtensionName
     *             the extension Name corresponding to other Extension
     * @param inDefinition
     *             the definition corresponding to other Extension
     * @param inScope
     *             the Scope corresponding to other Extension
     * @return true if this.Extension equals the parameters
     */
    public boolean equals(final String inTableName,
                          final String inColumnName,
                          final String inExtensionName,
                          final String inDefinition,
                          final Scope  inScope)
    {
        return Extension.equals(this.tableName,     inTableName)     &&
               Extension.equals(this.columnName,    inColumnName)    &&
               Extension.equals(this.extensionName, inExtensionName) &&
               Extension.equals(this.definition,    inDefinition)    &&
               Extension.equals(this.scope,         inScope.toString());
    }

    /**
     * @return the tableName
     */
    public String getTableName()
    {
        return this.tableName;
    }

    /**
     * @return the columnName
     */
    public String getColumnName()
    {
        return this.columnName;
    }

    /**
     * @return the extensionName
     */
    public String getExtensionName()
    {
        return this.extensionName;
    }

    /**
     * @return the definition
     */
    public String getDefinition()
    {
        return this.definition;
    }

    /**
     * @return the scope
     */
    public String getScope()
    {
        return this.scope;
    }

    private static <T> boolean equals(final T lhs, final T rhs)
    {
        return lhs == null ? rhs == null
                           : lhs.equals(rhs);
    }

    private final String tableName;
    private final String columnName;
    private final String extensionName;
    private final String definition;
    private final String scope;

    /**
     * The regular Expression of allowed extension names according to the OGC
     * specification (http://www.geopackage.org/spec/#_extension_mechanism)
     * under Requirement 82
     */
    public static final String ExtensionNameRegularExpression = "[a-zA-Z0-9]+_[a-zA-Z0-9_]+";
}


text:
title: Knee Injuries
authors:
    - Layla Abubshait, MD
    - Michael Gottlieb, MD, RDMS
    - Mary Haas, MD
created: 2016/11/21
updates: null
categories:
    - Orthopedics
---

# Knee Injuries

## [Knee Dislocation](/cards/knee-injuries-knee-dislocation)

## [Patella Fracture](/cards/knee-injuries-patella-fracture)

## [Patella Dislocation](/cards/knee-injuries-patella-dislocation)

* * *

## References

- [Schwartz A. Patella Fractures Treatment & Management, Emedicine.com (June 2016)](http://emedicine.medscape.com/article/1249384-treatment).

- [Hinton RY, Sharma KM. Acute and recurrent patellar instability in the young athlete. Orthop Clin North Am. 2003 Jul;34(3):385-96.](https://www.ncbi.nlm.nih.gov/pubmed/?term=12974488)

- [Ji G, et al . Surgical versus Nonsurgical Treatments of Acute Primary Patellar Dislocation with Special Emphasis on the MPFL Injury Patterns. J Knee Surg. 2016 Sep 14. Epub ahead of print.](https://www.ncbi.nlm.nih.gov/pubmed/?term=27626368.)

- [Petri M, et al. Current Concepts for Patellar Dislocation. Arch Trauma Res. 2015 Sep 1;4(3):e29301.](https://www.ncbi.nlm.nih.gov/pubmed/?term=26566512)

- [Medina O, et al. Vascular and nerve injury after knee dislocation: a systematic review. Clin Orthop Relat Res. 2014 Sep;472(9):2621-9.](https://www.ncbi.nlm.nih.gov/pubmed/?term=24554457)

redpajama_set_name: RedPajamaGithub


text:
<select [formControl]="control" name="cuisine" class="form-control font-italic" style="font-size: 0.875rem">
    <option [value]="null" disabled>Select cuisine</option>
    <option *ngFor="let cuisine of cuisines" [value]="cuisine.id">{{cuisine.name}}</option>
</select>


text:
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System.Globalization;
using Autofac.Builder;
using Autofac.Core;
using Autofac.Core.Resolving.Pipeline;
using Autofac.Features.Decorators;
using Autofac.Features.LightweightAdapters;
using Autofac.Features.OpenGenerics;

namespace Autofac;

/// <summary>
/// Adds registration syntax to the <see cref="ContainerBuilder"/> type.
/// </summary>
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
public static partial class RegistrationExtensions
{
    /// <summary>
    /// Decorate all components implementing open generic service <paramref name="decoratedServiceType"/>.
    /// The <paramref name="fromKey"/> and <paramref name="toKey"/> parameters must be different values.
    /// </summary>
    /// <param name="builder">Container builder.</param>
    /// <param name="decoratedServiceType">Service type being decorated. Must be an open generic type.</param>
    /// <param name="fromKey">Service key or name associated with the components being decorated.</param>
    /// <param name="toKey">Service key or name given to the decorated components.</param>
    /// <param name="decoratorType">The type of the decorator. Must be an open generic type, and accept a parameter
    /// of type <paramref name="decoratedServiceType"/>, which will be set to the instance being decorated.</param>
    public static IRegistrationBuilder<object, OpenGenericDecoratorActivatorData, DynamicRegistrationStyle>
        RegisterGenericDecorator(
            this ContainerBuilder builder,
            [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type decoratorType,
            Type decoratedServiceType,
            object fromKey,
            object? toKey = null)
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        if (decoratorType == null)
        {
            throw new ArgumentNullException(nameof(decoratorType));
        }

        if (decoratedServiceType == null)
        {
            throw new ArgumentNullException(nameof(decoratedServiceType));
        }

        return OpenGenericRegistrationExtensions.RegisterGenericDecorator(builder, decoratorType, decoratedServiceType, fromKey, toKey);
    }

    /// <summary>
    /// Decorate all components implementing service <typeparamref name="TService"/>
    /// using the provided <paramref name="decorator"/> function.
    /// The <paramref name="fromKey"/> and <paramref name="toKey"/> parameters must be different values.
    /// </summary>
    /// <typeparam name="TService">Service type being decorated.</typeparam>
    /// <param name="builder">Container builder.</param>
    /// <param name="decorator">Function decorating a component instance that provides
    /// <typeparamref name="TService"/>, given the context and parameters.</param>
    /// <param name="fromKey">Service key or name associated with the components being decorated.</param>
    /// <param name="toKey">Service key or name given to the decorated components.</param>
    public static IRegistrationBuilder<TService, LightweightAdapterActivatorData, DynamicRegistrationStyle>
        RegisterDecorator<TService>(
            this ContainerBuilder builder,
            Func<IComponentContext, IEnumerable<Parameter>, TService, TService> decorator,
            object fromKey,
            object? toKey = null)
        where TService : notnull
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        if (decorator == null)
        {
            throw new ArgumentNullException(nameof(decorator));
        }

        return LightweightAdapterRegistrationExtensions.RegisterDecorator(builder, decorator, fromKey, toKey);
    }

    /// <summary>
    /// Decorate all components implementing service <typeparamref name="TService"/>
    /// using the provided <paramref name="decorator"/> function.
    /// The <paramref name="fromKey"/> and <paramref name="toKey"/> parameters must be different values.
    /// </summary>
    /// <typeparam name="TService">Service type being decorated.</typeparam>
    /// <param name="builder">Container builder.</param>
    /// <param name="decorator">Function decorating a component instance that provides
    /// <typeparamref name="TService"/>, given the context.</param>
    /// <param name="fromKey">Service key or name associated with the components being decorated.</param>
    /// <param name="toKey">Service key or name given to the decorated components.</param>
    public static IRegistrationBuilder<TService, LightweightAdapterActivatorData, DynamicRegistrationStyle>
        RegisterDecorator<TService>(
            this ContainerBuilder builder,
            Func<IComponentContext, TService, TService> decorator,
            object fromKey,
            object? toKey = null)
        where TService : notnull
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        if (decorator == null)
        {
            throw new ArgumentNullException(nameof(decorator));
        }

        return LightweightAdapterRegistrationExtensions.RegisterDecorator<TService>(builder, (c, p, f) => decorator(c, f), fromKey, toKey);
    }

    /// <summary>
    /// Decorate all components implementing service <typeparamref name="TService"/>
    /// using the provided <paramref name="decorator"/> function.
    /// The <paramref name="fromKey"/> and <paramref name="toKey"/> parameters must be different values.
    /// </summary>
    /// <typeparam name="TService">Service type being decorated.</typeparam>
    /// <param name="builder">Container builder.</param>
    /// <param name="decorator">Function decorating a component instance that provides
    /// <typeparamref name="TService"/>.</param>
    /// <param name="fromKey">Service key or name associated with the components being decorated.</param>
    /// <param name="toKey">Service key or name given to the decorated components.</param>
    public static IRegistrationBuilder<TService, LightweightAdapterActivatorData, DynamicRegistrationStyle>
        RegisterDecorator<TService>(
            this ContainerBuilder builder,
            Func<TService, TService> decorator,
            object fromKey,
            object? toKey = null)
        where TService : notnull
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        if (decorator == null)
        {
            throw new ArgumentNullException(nameof(decorator));
        }

        return LightweightAdapterRegistrationExtensions.RegisterDecorator<TService>(builder, (c, p, f) => decorator(f), fromKey, toKey);
    }

    /// <summary>
    /// Decorate all components implementing service <typeparamref name="TService"/>
    /// with decorator service <typeparamref name="TDecorator"/>.
    /// </summary>
    /// <typeparam name="TDecorator">Service type of the decorator. Must accept a parameter
    /// of type <typeparamref name="TService"/>, which will be set to the instance being decorated.</typeparam>
    /// <typeparam name="TService">Service type being decorated.</typeparam>
    /// <param name="builder">Container builder.</param>
    /// <param name="condition">A function that when provided with an <see cref="IDecoratorContext"/>
    /// instance determines if the decorator should be applied.</param>
    public static void RegisterDecorator<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TDecorator, TService>(this ContainerBuilder builder, Func<IDecoratorContext, bool>? condition = null)
        where TDecorator : notnull, TService
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        var decoratorService = new DecoratorService(typeof(TService), condition);

        var rb = RegistrationBuilder.ForType<TDecorator>().As(decoratorService);

        var decoratorRegistration = rb.CreateRegistration();

        var middleware = new DecoratorMiddleware(decoratorService, decoratorRegistration);
        builder.RegisterServiceMiddleware<TService>(middleware, MiddlewareInsertionMode.StartOfPhase);

        // Add the decorator to the registry so the pipeline gets built.
        builder.RegisterCallback(crb => crb.Register(decoratorRegistration));
    }

    /// <summary>
    /// Decorate all components implementing service <paramref name="serviceType"/>
    /// with decorator service <paramref name="decoratorType"/>.
    /// </summary>
    /// <param name="builder">Container builder.</param>
    /// <param name="decoratorType">Service type of the decorator. Must accept a parameter
    /// of type <paramref name="serviceType"/>, which will be set to the instance being decorated.</param>
    /// <param name="serviceType">Service type being decorated.</param>
    /// <param name="condition">A function that when provided with an <see cref="IDecoratorContext"/>
    /// instance determines if the decorator should be applied.</param>
    public static void RegisterDecorator(
        this ContainerBuilder builder,
        [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type decoratorType,
        Type serviceType,
        Func<IDecoratorContext, bool>? condition = null)
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        if (decoratorType == null)
        {
            throw new ArgumentNullException(nameof(decoratorType));
        }

        if (serviceType == null)
        {
            throw new ArgumentNullException(nameof(serviceType));
        }

        var decoratorService = new DecoratorService(serviceType, condition);

        var rb = RegistrationBuilder.ForType(decoratorType).As(decoratorService);

        var decoratorRegistration = rb.CreateRegistration();

        var middleware = new DecoratorMiddleware(decoratorService, decoratorRegistration);

        builder.RegisterServiceMiddleware(serviceType, middleware, MiddlewareInsertionMode.StartOfPhase);

        // Add the decorator to the registry so the pipeline gets built.
        builder.RegisterCallback(crb => crb.Register(decoratorRegistration));
    }

    /// <summary>
    /// Decorate all components implementing service <typeparamref name="TService"/>
    /// using the provided <paramref name="decorator"/> function.
    /// </summary>
    /// <typeparam name="TService">Service type being decorated.</typeparam>
    /// <param name="builder">Container builder.</param>
    /// <param name="decorator">Function decorating a component instance that provides
    /// <typeparamref name="TService"/>, given the context, parameters and service to decorate.</param>
    /// <param name="condition">A function that when provided with an <see cref="IDecoratorContext"/>
    /// instance determines if the decorator should be applied.</param>
    public static void RegisterDecorator<TService>(
        this ContainerBuilder builder,
        Func<IComponentContext, IEnumerable<Parameter>, TService, TService> decorator,
        Func<IDecoratorContext, bool>? condition = null)
        where TService : class
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        if (decorator == null)
        {
            throw new ArgumentNullException(nameof(decorator));
        }

        var service = new DecoratorService(typeof(TService), condition);

        var rb = RegistrationBuilder.ForDelegate((c, p) =>
        {
            TService? instance = (TService?)p
                .OfType<TypedParameter>()
                .FirstOrDefault(tp => tp.Type == typeof(TService))
                ?.Value;

            if (instance == null)
            {
                throw new DependencyResolutionException(string.Format(CultureInfo.CurrentCulture, RegistrationExtensionsResources.DecoratorRequiresInstanceParameter, typeof(TService).Name));
            }

            return decorator(c, p, instance);
        }).As(service);

        var decoratorRegistration = rb.CreateRegistration();

        var middleware = new DecoratorMiddleware(service, decoratorRegistration);

        builder.RegisterServiceMiddleware<TService>(middleware, MiddlewareInsertionMode.StartOfPhase);

        // Add the decorator to the registry so the pipeline gets built.
        builder.RegisterCallback(crb => crb.Register(decoratorRegistration));
    }

    /// <summary>
    /// Decorate all components implementing open generic service <paramref name="serviceType"/>.
    /// </summary>
    /// <param name="builder">Container builder.</param>
    /// <param name="decoratorType">The type of the decorator. Must be an open generic type, and accept a parameter
    /// of type <paramref name="serviceType"/>, which will be set to the instance being decorated.</param>
    /// <param name="serviceType">Service type being decorated. Must be an open generic type.</param>
    /// <param name="condition">A function that when provided with an <see cref="IDecoratorContext"/>
    /// instance determines if the decorator should be applied.</param>
    public static void RegisterGenericDecorator(
        this ContainerBuilder builder,
        [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type decoratorType,
        Type serviceType,
        Func<IDecoratorContext, bool>? condition = null)
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        if (decoratorType == null)
        {
            throw new ArgumentNullException(nameof(decoratorType));
        }

        if (serviceType == null)
        {
            throw new ArgumentNullException(nameof(serviceType));
        }

        var decoratorService = new DecoratorService(serviceType, condition);

        var genericRegistration = OpenGenericRegistrationExtensions
            .CreateGenericBuilder(decoratorType)
            .As(decoratorService);

        builder.RegisterServiceMiddlewareSource(new OpenGenericDecoratorMiddlewareSource(decoratorService, genericRegistration.RegistrationData, genericRegistration.ActivatorData));
    }
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var LIMIT_NONE = null;
var LIMIT_ONCE = 1;
var LIMIT_TWICE = 2;

var PRIORITY_LOW = 1;
var PRIORITY_NORMAL = 5;
var PRIORITY_HIGH = 10;

/**
 * Event Listener
 *
 * Process event when it is emitted by the EventManager
 */

var Listener = function () {
  /**
   * Constructor
   * @param {!function} runner Callback function to process event, it would receive an event as input
   * @param {?number} [priority=5] Determine the order of listener in running queue
   * @param {?number} [limit=null] Define if this listen could only run at a specific times
   */
  function Listener(runner) {
    var priority = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : PRIORITY_NORMAL;
    var limit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : LIMIT_NONE;

    _classCallCheck(this, Listener);

    /**
     * @access protected
     * @type {function}
     */
    this.runner = runner;

    /**
     * @access protected
     * @type {number}
     */
    this.priority = priority;

    /**
     * @access protected
     * @type {number}
     */
    this.limit = limit;

    /**
     * @access private
     * @type {function}
     */
    this.cbDone = null;

    /**
     * @access private
     * @type {function}
     */
    this.cbError = null;
  }

  /**
   * Callback function to be called right after event is fired and stopped completely
   * @param {!function} callback
   * @returns {Listener} The current listener object
   */

  _createClass(Listener, [{
    key: "done",
    value: function done(callback) {
      this.cbDone = callback;
      return this;
    }

    /**
     * Callback function to be run if there is an error when processing event
     * @param {!function} callback
     * @returns {Listener} The current listener object
     */

  }, {
    key: "error",
    value: function error(callback) {
      this.cbError = callback;
      return this;
    }
  }]);

  return Listener;
}();

exports.default = Listener;

Listener.LIMIT_NONE = LIMIT_NONE;
Listener.LIMIT_ONCE = LIMIT_ONCE;
Listener.LIMIT_TWICE = LIMIT_TWICE;

Listener.PRIORITY_LOW = PRIORITY_LOW;
Listener.PRIORITY_NORMAL = PRIORITY_NORMAL;
Listener.PRIORITY_HIGH = PRIORITY_HIGH;


text:
 # build an executable named myprog from myprog.c
all: main.cpp
	g++ -o bluetooth main.cpp -lbluetooth

clean:
	rm -rf bluetooth


text:
import mock
from mock import call

from osc_lib import exceptions
from osc_lib import utils

from openstackclient.tests.unit.volume.v2 import fakes as volume_fakes
from openstackclient.volume.v2 import volume_backup

class TestBackup(volume_fakes.TestVolume):

    def setUp(self):
        super(TestBackup, self).setUp()

        self.backups_mock = self.app.client_manager.volume.backups
        self.backups_mock.reset_mock()
        self.volumes_mock = self.app.client_manager.volume.volumes
        self.volumes_mock.reset_mock()
        self.snapshots_mock = self.app.client_manager.volume.volume_snapshots
        self.snapshots_mock.reset_mock()
        self.restores_mock = self.app.client_manager.volume.restores
        self.restores_mock.reset_mock()

class TestBackupCreate(TestBackup):

    volume = volume_fakes.FakeVolume.create_one_volume()
    snapshot = volume_fakes.FakeSnapshot.create_one_snapshot()
    new_backup = volume_fakes.FakeBackup.create_one_backup(
        attrs={'volume_id': volume.id, 'snapshot_id': snapshot.id})

    columns = (
        'availability_zone',
        'container',
        'description',
        'id',
        'name',
        'object_count',
        'size',
        'snapshot_id',
        'status',
        'volume_id',
    )
    data = (
        new_backup.availability_zone,
        new_backup.container,
        new_backup.description,
        new_backup.id,
        new_backup.name,
        new_backup.object_count,
        new_backup.size,
        new_backup.snapshot_id,
        new_backup.status,
        new_backup.volume_id,
    )

    def setUp(self):
        super(TestBackupCreate, self).setUp()

        self.volumes_mock.get.return_value = self.volume
        self.snapshots_mock.get.return_value = self.snapshot
        self.backups_mock.create.return_value = self.new_backup

        # Get the command object to test
        self.cmd = volume_backup.CreateVolumeBackup(self.app, None)

    def test_backup_create(self):
        arglist = [
            "--name", self.new_backup.name,
            "--description", self.new_backup.description,
            "--container", self.new_backup.container,
            "--force",
            "--incremental",
            "--snapshot", self.new_backup.snapshot_id,
            self.new_backup.volume_id,
        ]
        verifylist = [
            ("name", self.new_backup.name),
            ("description", self.new_backup.description),
            ("container", self.new_backup.container),
            ("force", True),
            ("incremental", True),
            ("snapshot", self.new_backup.snapshot_id),
            ("volume", self.new_backup.volume_id),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        columns, data = self.cmd.take_action(parsed_args)

        self.backups_mock.create.assert_called_with(
            self.new_backup.volume_id,
            container=self.new_backup.container,
            name=self.new_backup.name,
            description=self.new_backup.description,
            force=True,
            incremental=True,
            snapshot_id=self.new_backup.snapshot_id,
        )
        self.assertEqual(self.columns, columns)
        self.assertEqual(self.data, data)

    def test_backup_create_without_name(self):
        arglist = [
            "--description", self.new_backup.description,
            "--container", self.new_backup.container,
            self.new_backup.volume_id,
        ]
        verifylist = [
            ("description", self.new_backup.description),
            ("container", self.new_backup.container),
            ("volume", self.new_backup.volume_id),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        columns, data = self.cmd.take_action(parsed_args)

        self.backups_mock.create.assert_called_with(
            self.new_backup.volume_id,
            container=self.new_backup.container,
            name=None,
            description=self.new_backup.description,
            force=False,
            incremental=False,
            snapshot_id=None,
        )
        self.assertEqual(self.columns, columns)
        self.assertEqual(self.data, data)

class TestBackupDelete(TestBackup):

    backups = volume_fakes.FakeBackup.create_backups(count=2)

    def setUp(self):
        super(TestBackupDelete, self).setUp()

        self.backups_mock.get = (
            volume_fakes.FakeBackup.get_backups(self.backups))
        self.backups_mock.delete.return_value = None

        # Get the command object to mock
        self.cmd = volume_backup.DeleteVolumeBackup(self.app, None)

    def test_backup_delete(self):
        arglist = [
            self.backups[0].id
        ]
        verifylist = [
            ("backups", [self.backups[0].id])
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        result = self.cmd.take_action(parsed_args)

        self.backups_mock.delete.assert_called_with(
            self.backups[0].id, False)
        self.assertIsNone(result)

    def test_backup_delete_with_force(self):
        arglist = [
            '--force',
            self.backups[0].id,
        ]
        verifylist = [
            ('force', True),
            ("backups", [self.backups[0].id])
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        result = self.cmd.take_action(parsed_args)

        self.backups_mock.delete.assert_called_with(self.backups[0].id, True)
        self.assertIsNone(result)

    def test_delete_multiple_backups(self):
        arglist = []
        for b in self.backups:
            arglist.append(b.id)
        verifylist = [
            ('backups', arglist),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        result = self.cmd.take_action(parsed_args)

        calls = []
        for b in self.backups:
            calls.append(call(b.id, False))
        self.backups_mock.delete.assert_has_calls(calls)
        self.assertIsNone(result)

    def test_delete_multiple_backups_with_exception(self):
        arglist = [
            self.backups[0].id,
            'unexist_backup',
        ]
        verifylist = [
            ('backups', arglist),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        find_mock_result = [self.backups[0], exceptions.CommandError]
        with mock.patch.object(utils, 'find_resource',
                               side_effect=find_mock_result) as find_mock:
            try:
                self.cmd.take_action(parsed_args)
                self.fail('CommandError should be raised.')
            except exceptions.CommandError as e:
                self.assertEqual('1 of 2 backups failed to delete.',
                                 str(e))

            find_mock.assert_any_call(self.backups_mock, self.backups[0].id)
            find_mock.assert_any_call(self.backups_mock, 'unexist_backup')

            self.assertEqual(2, find_mock.call_count)
            self.backups_mock.delete.assert_called_once_with(
                self.backups[0].id, False
            )

class TestBackupList(TestBackup):

    volume = volume_fakes.FakeVolume.create_one_volume()
    backups = volume_fakes.FakeBackup.create_backups(
        attrs={'volume_id': volume.name}, count=3)

    columns = [
        'ID',
        'Name',
        'Description',
        'Status',
        'Size',
    ]
    columns_long = columns + [
        'Availability Zone',
        'Volume',
        'Container',
    ]

    data = []
    for b in backups:
        data.append((
            b.id,
            b.name,
            b.description,
            b.status,
            b.size,
        ))
    data_long = []
    for b in backups:
        data_long.append((
            b.id,
            b.name,
            b.description,
            b.status,
            b.size,
            b.availability_zone,
            volume_backup.VolumeIdColumn(b.volume_id),
            b.container,
        ))

    def setUp(self):
        super(TestBackupList, self).setUp()

        self.volumes_mock.list.return_value = [self.volume]
        self.backups_mock.list.return_value = self.backups
        self.volumes_mock.get.return_value = self.volume
        self.backups_mock.get.return_value = self.backups[0]
        # Get the command to test
        self.cmd = volume_backup.ListVolumeBackup(self.app, None)

    def test_backup_list_without_options(self):
        arglist = []
        verifylist = [
            ("long", False),
            ("name", None),
            ("status", None),
            ("volume", None),
            ("marker", None),
            ("limit", None),
            ('all_projects', False),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        columns, data = self.cmd.take_action(parsed_args)

        search_opts = {
            "name": None,
            "status": None,
            "volume_id": None,
            'all_tenants': False,
        }
        self.volumes_mock.get.assert_not_called()
        self.backups_mock.get.assert_not_called()
        self.backups_mock.list.assert_called_with(
            search_opts=search_opts,
            marker=None,
            limit=None,
        )
        self.assertEqual(self.columns, columns)
        self.assertListItemEqual(self.data, list(data))

    def test_backup_list_with_options(self):
        arglist = [
            "--long",
            "--name", self.backups[0].name,
            "--status", "error",
            "--volume", self.volume.id,
            "--marker", self.backups[0].id,
            "--all-projects",
            "--limit", "3",
        ]
        verifylist = [
            ("long", True),
            ("name", self.backups[0].name),
            ("status", "error"),
            ("volume", self.volume.id),
            ("marker", self.backups[0].id),
            ('all_projects', True),
            ("limit", 3),
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        columns, data = self.cmd.take_action(parsed_args)

        search_opts = {
            "name": self.backups[0].name,
            "status": "error",
            "volume_id": self.volume.id,
            'all_tenants': True,
        }
        self.volumes_mock.get.assert_called_once_with(self.volume.id)
        self.backups_mock.get.assert_called_once_with(self.backups[0].id)
        self.backups_mock.list.assert_called_with(
            search_opts=search_opts,
            marker=self.backups[0].id,
            limit=3,
        )
        self.assertEqual(self.columns_long, columns)
        self.assertListItemEqual(self.data_long, list(data))

class TestBackupRestore(TestBackup):

    volume = volume_fakes.FakeVolume.create_one_volume()
    backup = volume_fakes.FakeBackup.create_one_backup(
        attrs={'volume_id': volume.id})

    def setUp(self):
        super(TestBackupRestore, self).setUp()

        self.backups_mock.get.return_value = self.backup
        self.volumes_mock.get.return_value = self.volume
        self.restores_mock.restore.return_value = (
            volume_fakes.FakeVolume.create_one_volume(
                {'id': self.volume['id']}))
        # Get the command object to mock
        self.cmd = volume_backup.RestoreVolumeBackup(self.app, None)

    def test_backup_restore(self):
        arglist = [
            self.backup.id,
            self.backup.volume_id
        ]
        verifylist = [
            ("backup", self.backup.id),
            ("volume", self.backup.volume_id)
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        result = self.cmd.take_action(parsed_args)
        self.restores_mock.restore.assert_called_with(self.backup.id,
                                                      self.backup.volume_id)
        self.assertIsNotNone(result)

class TestBackupSet(TestBackup):

    backup = volume_fakes.FakeBackup.create_one_backup()

    def setUp(self):
        super(TestBackupSet, self).setUp()

        self.backups_mock.get.return_value = self.backup

        # Get the command object to test
        self.cmd = volume_backup.SetVolumeBackup(self.app, None)

    def test_backup_set_name(self):
        arglist = [
            '--name', 'new_name',
            self.backup.id,
        ]
        verifylist = [
            ('name', 'new_name'),
            ('backup', self.backup.id),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        # In base command class ShowOne in cliff, abstract method take_action()
        # returns nothing
        result = self.cmd.take_action(parsed_args)
        self.backups_mock.update.assert_called_once_with(
            self.backup.id, **{'name': 'new_name'})
        self.assertIsNone(result)

    def test_backup_set_description(self):
        arglist = [
            '--description', 'new_description',
            self.backup.id,
        ]
        verifylist = [
            ('name', None),
            ('description', 'new_description'),
            ('backup', self.backup.id),
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        result = self.cmd.take_action(parsed_args)

        # Set expected values
        kwargs = {
            'description': 'new_description'
        }
        self.backups_mock.update.assert_called_once_with(
            self.backup.id,
            **kwargs
        )
        self.assertIsNone(result)

    def test_backup_set_state(self):
        arglist = [
            '--state', 'error',
            self.backup.id
        ]
        verifylist = [
            ('state', 'error'),
            ('backup', self.backup.id)
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        result = self.cmd.take_action(parsed_args)
        self.backups_mock.reset_state.assert_called_once_with(
            self.backup.id, 'error')
        self.assertIsNone(result)

    def test_backup_set_state_failed(self):
        self.backups_mock.reset_state.side_effect = exceptions.CommandError()
        arglist = [
            '--state', 'error',
            self.backup.id
        ]
        verifylist = [
            ('state', 'error'),
            ('backup', self.backup.id)
        ]

        parsed_args = self.check_parser(self.cmd, arglist, verifylist)
        try:
            self.cmd.take_action(parsed_args)
            self.fail('CommandError should be raised.')
        except exceptions.CommandError as e:
            self.assertEqual('One or more of the set operations failed',
                             str(e))
        self.backups_mock.reset_state.assert_called_with(
            self.backup.id, 'error')

class TestBackupShow(TestBackup):

    backup = volume_fakes.FakeBackup.create_one_backup()

    columns = (
        'availability_zone',
        'container',
        'description',
        'id',
        'name',
        'object_count',
        'size',
        'snapshot_id',
        'status',
        'volume_id',
    )
    data = (
        backup.availability_zone,
        backup.container,
        backup.description,
        backup.id,
        backup.name,
        backup.object_count,
        backup.size,
        backup.snapshot_id,
        backup.status,
        backup.volume_id,
    )

    def setUp(self):
        super(TestBackupShow, self).setUp()

        self.backups_mock.get.return_value = self.backup
        # Get the command object to test
        self.cmd = volume_backup.ShowVolumeBackup(self.app, None)

    def test_backup_show(self):
        arglist = [
            self.backup.id
        ]
        verifylist = [
            ("backup", self.backup.id)
        ]
        parsed_args = self.check_parser(self.cmd, arglist, verifylist)

        columns, data = self.cmd.take_action(parsed_args)
        self.backups_mock.get.assert_called_with(self.backup.id)

        self.assertEqual(self.columns, columns)
        self.assertEqual(self.data, data)


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.psalgs;

import java.util.HashSet;
import java.util.Set;

/**
 *
 * @author djoshi
 *
 * https://www.geeksforgeeks.org/find-the-smallest-positive-number-missing-from-an-unsorted-array/
 */
public class SmallestPositive {

    public int solution(int[] A) {
        // write your code in Java SE 8
        int N = A.length;
        Set<Integer> set = new HashSet<>();

        for (int a : A) {
            if (a > 0) {
                set.add(a);
            }
        }

        for (int i = 1; i <= N + 1; i++) {
            if (!set.contains(i)) {
                return i;
            }
        }

        return 1;
    }

    public static void main(String args[]) {
        int A[] = {1, 3, 6, 4, 1, 2};

        SmallestPositive sp = new SmallestPositive();
        System.out.println(sp.solution(A));
    }
}


text:
package Feb2021Leetcode;

public class _0092ReverseLinkedListII {

	static public class ListNode {
		int val;
		ListNode next;

		ListNode() {
		}

		ListNode(int val) {
			this.val = val;
		}

		ListNode(int val, ListNode next) {
			this.val = val;
			this.next = next;
		}
	}

	public static void main(String[] args) {
		ListNode ln = new ListNode(1);
		ln.next = new ListNode(2);
		ln.next.next = new ListNode(3);
		ln.next.next.next = new ListNode(4);
		ln.next.next.next.next = new ListNode(5);
		ln = reverseBetween(ln, 1, 4);
		printNodes(ln);
		System.out.println();

		ln = new ListNode(3);
		ln.next = new ListNode(5);
		ln = reverseBetween(ln, 1, 2);
		printNodes(ln);
	}

	public static void printNodes(ListNode head) {
		while (head != null) {
			System.out.print(head.val + "->");
			head = head.next;
		}
		System.out.println();
	}

	public static ListNode reverseBetween(ListNode head, int m, int n) {
		ListNode op = new ListNode();
		ListNode opPtr = op;
		int count = 0;
		op.next = head;
		ListNode leftPart = null;
		ListNode rightPart = null;

		ListNode prev = op;
		while (count <= n) {
			if (count == m - 1) {
				leftPart = prev;
			}

			if (count == n) {
				rightPart = prev;
			}
			prev = head;
			if (head != null)
				head = head.next;
			count++;
		}

		ListNode leftPtr = leftPart;
		ListNode nextToLeft = leftPart.next;
		leftPart.next = null;

		ListNode rightPtr = rightPart.next;
		rightPart.next = null;

		ListNode bwPart = reverseLL(nextToLeft);
		leftPtr.next = bwPart;
		nextToLeft.next = rightPtr;

		return opPtr.next;
	}

	public static ListNode reverseLL(ListNode head) {
		if (head == null || head.next == null)
			return head;

		ListNode nextNode = head.next;
		ListNode reverseNode = reverseLL(head.next);
		nextNode.next = head;
		head.next = null;
		return reverseNode;
	}
}


text:
class User < ActiveRecord::Base
  before_save { self.email = email.downcase }

  validates :name, presence: true, length: {maximum: 50}
  VALID_EMAIL_REGEX = /\A([\w+\-].?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
  validates :email, presence: true, length: {maximum: 255},
            format: {with: VALID_EMAIL_REGEX},
            uniqueness: {case_sensitive: false}
  validates :password, presence: true, length: {minimum: 6}

  has_secure_password
end


text:
/**
  ******************************************************************************
  * @attention
  *
  * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");
  * You may not use this file except in compliance with the License.
  * You may obtain a copy of the License at:
  *
  *        http://www.st.com/software_license_agreement_liberty_v2
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  *
  ******************************************************************************
  */

#ifndef LISTWHEEL_PRIVATE_H
#define LISTWHEEL_PRIVATE_H

#include "LISTWHEEL.h"
#include "WM.h"
#include "GUI_ARRAY.h"
#include "WIDGET.h"

#if GUI_WINSUPPORT

/*********************************************************************
*
*       Defines
*
**********************************************************************
*/
#define LISTWHEEL_STATE_PRESSED WIDGET_STATE_USER0

/*********************************************************************
*
*       Object definition
*
**********************************************************************
*/

typedef struct {
  void * pData;
  char   acText[1];
} LISTWHEEL_ITEM;

typedef struct {
  const GUI_FONT * pFont;
  GUI_COLOR        aBackColor[2];
  GUI_COLOR        aTextColor[2];
  I16              Align;
  unsigned         Deceleration;
} LISTWHEEL_PROPS;

typedef struct {
  WIDGET                  Widget;
  GUI_ARRAY               ItemArray;
  WIDGET_DRAW_ITEM_FUNC * pfOwnerDraw;
  LISTWHEEL_PROPS         Props;
  WM_HMEM                 hTimer;
  unsigned                LBorder;
  unsigned                RBorder;
  unsigned                LineHeight;
  int                     Sel;
  GUI_TIMER_TIME          TimeTouched;      // Time stamp of last touch event
  GUI_TIMER_TIME          TimeTouchedLast;  // Time of the last touch
  int                     PosTouchedLast;   // Last touched position in pixels
  int                     Pos;              // Current position in pixels
  int                     Velocity;         // Motion in pixels
  int                     SnapPosition;     // Snap position in pixels
  int                     TouchPos;         // Y-position of last touch event
  int                     ySizeData;        // Data size in pixels
  int                     Destination;      // Destination position in pixels
  GUI_TIMER_TIME          TimerPeriod;      // Period of timer events
  #if GUI_DEBUG_LEVEL > 1
    U32 DebugId;
  #endif
} LISTWHEEL_OBJ;

/*********************************************************************
*
*       Macros for internal use
*
**********************************************************************
*/
#if GUI_DEBUG_LEVEL >= GUI_DEBUG_LEVEL_CHECK_ALL
  #define LISTWHEEL_INIT_ID(p)  (p->DebugId = LISTWHEEL_ID)
#else
  #define LISTWHEEL_INIT_ID(p)
#endif

#if GUI_DEBUG_LEVEL >= GUI_DEBUG_LEVEL_CHECK_ALL
  LISTWHEEL_OBJ * LISTWHEEL_LockH(LISTWHEEL_Handle h);
  #define LISTWHEEL_LOCK_H(h)   LISTWHEEL_LockH(h)
#else
  #define LISTWHEEL_LOCK_H(h)   (LISTWHEEL_OBJ *)GUI_LOCK_H(h)
#endif

/*********************************************************************
*
*       Private (module internal) data
*
**********************************************************************
*/
extern LISTWHEEL_PROPS LISTWHEEL_DefaultProps;

/*********************************************************************
*
*       Private (module internal) functions
*
**********************************************************************
*/
const char * LISTWHEEL__GetpStringLocked(LISTWHEEL_Handle hObj, int Index, LISTWHEEL_ITEM ** ppItem);

#endif // GUI_WINSUPPORT
#endif // LISTWHEEL_PRIVATE_H

/*************************** End of file ****************************/


text:
package com.bandwidth.iris.sdk.model;

import javax.xml.bind.annotation.*;
import java.util.List;

@XmlRootElement(name = "EmergencyNotificationEndpointOrder")
@XmlAccessorType(XmlAccessType.FIELD)
public class EmergencyNotificationEndpointOrder extends BaseModel {

    @XmlElement(name = "OrderId")
    private String orderId;

    @XmlElement(name = "OrderCreatedDate")
    private String crderCreatedDate;

    @XmlElement(name = "CreatedBy")
    private String CreatedBy;

    @XmlElement(name = "ProcessingStatus")
    private String processingStatus;

    @XmlElement(name = "CustomerOrderId")
    private String customerOrderId;

    @XmlElement(name = "EmergencyNotificationEndpointAssociations")
    private EmergencyNotificationEndpointAssociation emergencyNotificationEndpointAssociations;

    @XmlElement(name = "EmergencyNotificationEndpointAssociation")
    private EmergencyNotificationEndpointAssociation emergencyNotificationEndpointAssociation;

    public String getCustomerOrderId() {
        return customerOrderId;
    }

    public void setCustomerOrderId(String customerOrderId) {
        this.customerOrderId = customerOrderId;
    }

    public EmergencyNotificationEndpointAssociation getEmergencyNotificationEndpointAssociations() {
        return emergencyNotificationEndpointAssociations;
    }

    public void setEmergencyNotificationEndpointAssociations(EmergencyNotificationEndpointAssociation emergencyNotificationEndpointAssociations) {
        this.emergencyNotificationEndpointAssociations = emergencyNotificationEndpointAssociations;
    }

    public EmergencyNotificationEndpointAssociation getEmergencyNotificationEndpointAssociation() {
        return emergencyNotificationEndpointAssociation;
    }

    public void setEmergencyNotificationEndpointAssociation(EmergencyNotificationEndpointAssociation emergencyNotificationEndpointAssociation) {
        this.emergencyNotificationEndpointAssociation = emergencyNotificationEndpointAssociation;
    }

    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    public String getCrderCreatedDate() {
        return crderCreatedDate;
    }

    public void setCrderCreatedDate(String crderCreatedDate) {
        this.crderCreatedDate = crderCreatedDate;
    }

    public String getProcessingStatus() {
        return processingStatus;
    }

    public void setProcessingStatus(String processingStatus) {
        this.processingStatus = processingStatus;
    }

    public String getCreatedBy() {
        return CreatedBy;
    }

    public void setCreatedBy(String createdBy) {
        CreatedBy = createdBy;
    }
}


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

/**
 * @fileoverview Logging and debugging utilities.
 *
 * @see ../demos/debug.html
 */

goog.provide('goog.debug');

goog.require('goog.array');
goog.require('goog.html.SafeHtml');
goog.require('goog.html.SafeUrl');
goog.require('goog.html.uncheckedconversions');
goog.require('goog.string.Const');
goog.require('goog.structs.Set');
goog.require('goog.userAgent');

/** @define {boolean} Whether logging should be enabled. */
goog.define('goog.debug.LOGGING_ENABLED', goog.DEBUG);

/** @define {boolean} Whether to force "sloppy" stack building. */
goog.define('goog.debug.FORCE_SLOPPY_STACKS', false);

/**
 * Catches onerror events fired by windows and similar objects.
 * @param {function(Object)} logFunc The function to call with the error
 *    information.
 * @param {boolean=} opt_cancel Whether to stop the error from reaching the
 *    browser.
 * @param {Object=} opt_target Object that fires onerror events.
 */
goog.debug.catchErrors = function(logFunc, opt_cancel, opt_target) {
  var target = opt_target || goog.global;
  var oldErrorHandler = target.onerror;
  var retVal = !!opt_cancel;

  // Chrome interprets onerror return value backwards (http://crbug.com/92062)
  // until it was fixed in webkit revision r94061 (Webkit 535.3). This
  // workaround still needs to be skipped in Safari after the webkit change
  // gets pushed out in Safari.
  // See https://bugs.webkit.org/show_bug.cgi?id=67119
  if (goog.userAgent.WEBKIT && !goog.userAgent.isVersionOrHigher('535.3')) {
    retVal = !retVal;
  }

  /**
   * New onerror handler for this target. This onerror handler follows the spec
   * according to
   * http://www.whatwg.org/specs/web-apps/current-work/#runtime-script-errors
   * The spec was changed in August 2013 to support receiving column information
   * and an error object for all scripts on the same origin or cross origin
   * scripts with the proper headers. See
   * https://mikewest.org/2013/08/debugging-runtime-errors-with-window-onerror
   *
   * @param {string} message The error message. For cross-origin errors, this
   *     will be scrubbed to just "Script error.". For new browsers that have
   *     updated to follow the latest spec, errors that come from origins that
   *     have proper cross origin headers will not be scrubbed.
   * @param {string} url The URL of the script that caused the error. The URL
   *     will be scrubbed to "" for cross origin scripts unless the script has
   *     proper cross origin headers and the browser has updated to the latest
   *     spec.
   * @param {number} line The line number in the script that the error
   *     occurred on.
   * @param {number=} opt_col The optional column number that the error
   *     occurred on. Only browsers that have updated to the latest spec will
   *     include this.
   * @param {Error=} opt_error The optional actual error object for this
   *     error that should include the stack. Only browsers that have updated
   *     to the latest spec will inlude this parameter.
   * @return {boolean} Whether to prevent the error from reaching the browser.
   */
  target.onerror = function(message, url, line, opt_col, opt_error) {
    if (oldErrorHandler) {
      oldErrorHandler(message, url, line, opt_col, opt_error);
    }
    logFunc({
      message: message,
      fileName: url,
      line: line,
      col: opt_col,
      error: opt_error
    });
    return retVal;
  };
};

/**
 * Creates a string representing an object and all its properties.
 * @param {Object|null|undefined} obj Object to expose.
 * @param {boolean=} opt_showFn Show the functions as well as the properties,
 *     default is false.
 * @return {string} The string representation of {@code obj}.
 */
goog.debug.expose = function(obj, opt_showFn) {
  if (typeof obj == 'undefined') {
    return 'undefined';
  }
  if (obj == null) {
    return 'NULL';
  }
  var str = [];

  for (var x in obj) {
    if (!opt_showFn && goog.isFunction(obj[x])) {
      continue;
    }
    var s = x + ' = ';
    /** @preserveTry */
    try {
      s += obj[x];
    } catch (e) {
      s += '*** ' + e + ' ***';
    }
    str.push(s);
  }
  return str.join('\n');
};

/**
 * Creates a string representing a given primitive or object, and for an
 * object, all its properties and nested objects.  WARNING: If an object is
 * given, it and all its nested objects will be modified.  To detect reference
 * cycles, this method identifies objects using goog.getUid() which mutates the
 * object.
 * @param {*} obj Object to expose.
 * @param {boolean=} opt_showFn Also show properties that are functions (by
 *     default, functions are omitted).
 * @return {string} A string representation of {@code obj}.
 */
goog.debug.deepExpose = function(obj, opt_showFn) {
  var str = [];

  var helper = function(obj, space, parentSeen) {
    var nestspace = space + '  ';
    var seen = new goog.structs.Set(parentSeen);

    var indentMultiline = function(str) {
      return str.replace(/\n/g, '\n' + space);
    };

    /** @preserveTry */
    try {
      if (!goog.isDef(obj)) {
        str.push('undefined');
      } else if (goog.isNull(obj)) {
        str.push('NULL');
      } else if (goog.isString(obj)) {
        str.push('"' + indentMultiline(obj) + '"');
      } else if (goog.isFunction(obj)) {
        str.push(indentMultiline(String(obj)));
      } else if (goog.isObject(obj)) {
        if (seen.contains(obj)) {
          str.push('*** reference loop detected ***');
        } else {
          seen.add(obj);
          str.push('{');
          for (var x in obj) {
            if (!opt_showFn && goog.isFunction(obj[x])) {
              continue;
            }
            str.push('\n');
            str.push(nestspace);
            str.push(x + ' = ');
            helper(obj[x], nestspace, seen);
          }
          str.push('\n' + space + '}');
        }
      } else {
        str.push(obj);
      }
    } catch (e) {
      str.push('*** ' + e + ' ***');
    }
  };

  helper(obj, '', new goog.structs.Set());
  return str.join('');
};

/**
 * Recursively outputs a nested array as a string.
 * @param {Array<?>} arr The array.
 * @return {string} String representing nested array.
 */
goog.debug.exposeArray = function(arr) {
  var str = [];
  for (var i = 0; i < arr.length; i++) {
    if (goog.isArray(arr[i])) {
      str.push(goog.debug.exposeArray(arr[i]));
    } else {
      str.push(arr[i]);
    }
  }
  return '[ ' + str.join(', ') + ' ]';
};

/**
 * Exposes an exception that has been caught by a try...catch and outputs the
 * error as HTML with a stack trace.
 * @param {Object} err Error object or string.
 * @param {Function=} opt_fn Optional function to start stack trace from.
 * @return {string} Details of exception, as HTML.
 */
goog.debug.exposeException = function(err, opt_fn) {
  var html = goog.debug.exposeExceptionAsHtml(err, opt_fn);
  return goog.html.SafeHtml.unwrap(html);
};

/**
 * Exposes an exception that has been caught by a try...catch and outputs the
 * error with a stack trace.
 * @param {Object} err Error object or string.
 * @param {Function=} opt_fn Optional function to start stack trace from.
 * @return {!goog.html.SafeHtml} Details of exception.
 */
goog.debug.exposeExceptionAsHtml = function(err, opt_fn) {
  /** @preserveTry */
  try {
    var e = goog.debug.normalizeErrorObject(err);
    // Create the error message
    var viewSourceUrl = goog.debug.createViewSourceUrl_(e.fileName);
    var error = goog.html.SafeHtml.concat(
        goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(
            'Message: ' + e.message + '\nUrl: '),
        goog.html.SafeHtml.create(
            'a', {href: viewSourceUrl, target: '_new'}, e.fileName),
        goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(
            '\nLine: ' + e.lineNumber + '\n\nBrowser stack:\n' + e.stack +
            '-> ' +
            '[end]\n\nJS stack traversal:\n' +
            goog.debug.getStacktrace(opt_fn) + '-> '));
    return error;
  } catch (e2) {
    return goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(
        'Exception trying to expose exception! You win, we lose. ' + e2);
  }
};

/**
 * @param {?string=} opt_fileName
 * @return {!goog.html.SafeUrl} SafeUrl with view-source scheme, pointing at
 *     fileName.
 * @private
 */
goog.debug.createViewSourceUrl_ = function(opt_fileName) {
  if (!goog.isDefAndNotNull(opt_fileName)) {
    opt_fileName = '';
  }
  if (!/^https?:\/\//i.test(opt_fileName)) {
    return goog.html.SafeUrl.fromConstant(
        goog.string.Const.from('sanitizedviewsrc'));
  }
  var sanitizedFileName = goog.html.SafeUrl.sanitize(opt_fileName);
  return goog.html.uncheckedconversions
      .safeUrlFromStringKnownToSatisfyTypeContract(
          goog.string.Const.from('view-source scheme plus HTTP/HTTPS URL'),
          'view-source:' + goog.html.SafeUrl.unwrap(sanitizedFileName));
};

/**
 * Normalizes the error/exception object between browsers.
 * @param {Object} err Raw error object.
 * @return {!Object} Normalized error object.
 */
goog.debug.normalizeErrorObject = function(err) {
  var href = goog.getObjectByName('window.location.href');
  if (goog.isString(err)) {
    return {
      'message': err,
      'name': 'Unknown error',
      'lineNumber': 'Not available',
      'fileName': href,
      'stack': 'Not available'
    };
  }

  var lineNumber, fileName;
  var threwError = false;

  try {
    lineNumber = err.lineNumber || err.line || 'Not available';
  } catch (e) {
    // Firefox 2 sometimes throws an error when accessing 'lineNumber':
    // Message: Permission denied to get property UnnamedClass.lineNumber
    lineNumber = 'Not available';
    threwError = true;
  }

  try {
    fileName = err.fileName || err.filename || err.sourceURL ||
        // $googDebugFname may be set before a call to eval to set the filename
        // that the eval is supposed to present.
        goog.global['$googDebugFname'] || href;
  } catch (e) {
    // Firefox 2 may also throw an error when accessing 'filename'.
    fileName = 'Not available';
    threwError = true;
  }

  // The IE Error object contains only the name and the message.
  // The Safari Error object uses the line and sourceURL fields.
  if (threwError || !err.lineNumber || !err.fileName || !err.stack ||
      !err.message || !err.name) {
    return {
      'message': err.message || 'Not available',
      'name': err.name || 'UnknownError',
      'lineNumber': lineNumber,
      'fileName': fileName,
      'stack': err.stack || 'Not available'
    };
  }

  // Standards error object
  return err;
};

/**
 * Converts an object to an Error if it's a String,
 * adds a stacktrace if there isn't one,
 * and optionally adds an extra message.
 * @param {Error|string} err  the original thrown object or string.
 * @param {string=} opt_message  optional additional message to add to the
 *     error.
 * @return {!Error} If err is a string, it is used to create a new Error,
 *     which is enhanced and returned.  Otherwise err itself is enhanced
 *     and returned.
 */
goog.debug.enhanceError = function(err, opt_message) {
  var error;
  if (typeof err == 'string') {
    error = Error(err);
    if (Error.captureStackTrace) {
      // Trim this function off the call stack, if we can.
      Error.captureStackTrace(error, goog.debug.enhanceError);
    }
  } else {
    error = err;
  }

  if (!error.stack) {
    error.stack = goog.debug.getStacktrace(goog.debug.enhanceError);
  }
  if (opt_message) {
    // find the first unoccupied 'messageX' property
    var x = 0;
    while (error['message' + x]) {
      ++x;
    }
    error['message' + x] = String(opt_message);
  }
  return error;
};

/**
 * Gets the current stack trace. Simple and iterative - doesn't worry about
 * catching circular references or getting the args.
 * @param {number=} opt_depth Optional maximum depth to trace back to.
 * @return {string} A string with the function names of all functions in the
 *     stack, separated by \n.
 * @suppress {es5Strict}
 */
goog.debug.getStacktraceSimple = function(opt_depth) {
  if (!goog.debug.FORCE_SLOPPY_STACKS) {
    var stack = goog.debug.getNativeStackTrace_(goog.debug.getStacktraceSimple);
    if (stack) {
      return stack;
    }
    // NOTE: browsers that have strict mode support also have native "stack"
    // properties.  Fall-through for legacy browser support.
  }

  var sb = [];
  var fn = arguments.callee.caller;
  var depth = 0;

  while (fn && (!opt_depth || depth < opt_depth)) {
    sb.push(goog.debug.getFunctionName(fn));
    sb.push('()\n');
    /** @preserveTry */
    try {
      fn = fn.caller;
    } catch (e) {
      sb.push('[exception trying to get caller]\n');
      break;
    }
    depth++;
    if (depth >= goog.debug.MAX_STACK_DEPTH) {
      sb.push('[...long stack...]');
      break;
    }
  }
  if (opt_depth && depth >= opt_depth) {
    sb.push('[...reached max depth limit...]');
  } else {
    sb.push('[end]');
  }

  return sb.join('');
};

/**
 * Max length of stack to try and output
 * @type {number}
 */
goog.debug.MAX_STACK_DEPTH = 50;

/**
 * @param {Function} fn The function to start getting the trace from.
 * @return {?string}
 * @private
 */
goog.debug.getNativeStackTrace_ = function(fn) {
  var tempErr = new Error();
  if (Error.captureStackTrace) {
    Error.captureStackTrace(tempErr, fn);
    return String(tempErr.stack);
  } else {
    // IE10, only adds stack traces when an exception is thrown.
    try {
      throw tempErr;
    } catch (e) {
      tempErr = e;
    }
    var stack = tempErr.stack;
    if (stack) {
      return String(stack);
    }
  }
  return null;
};

/**
 * Gets the current stack trace, either starting from the caller or starting
 * from a specified function that's currently on the call stack.
 * @param {Function=} opt_fn Optional function to start getting the trace from.
 *     If not provided, defaults to the function that called this.
 * @return {string} Stack trace.
 * @suppress {es5Strict}
 */
goog.debug.getStacktrace = function(opt_fn) {
  var stack;
  if (!goog.debug.FORCE_SLOPPY_STACKS) {
    // Try to get the stack trace from the environment if it is available.
    var contextFn = opt_fn || goog.debug.getStacktrace;
    stack = goog.debug.getNativeStackTrace_(contextFn);
  }
  if (!stack) {
    // NOTE: browsers that have strict mode support also have native "stack"
    // properties. This function will throw in strict mode.
    stack =
        goog.debug.getStacktraceHelper_(opt_fn || arguments.callee.caller, []);
  }
  return stack;
};

/**
 * Private helper for getStacktrace().
 * @param {Function} fn Function to start getting the trace from.
 * @param {Array<!Function>} visited List of functions visited so far.
 * @return {string} Stack trace starting from function fn.
 * @suppress {es5Strict}
 * @private
 */
goog.debug.getStacktraceHelper_ = function(fn, visited) {
  var sb = [];

  // Circular reference, certain functions like bind seem to cause a recursive
  // loop so we need to catch circular references
  if (goog.array.contains(visited, fn)) {
    sb.push('[...circular reference...]');

    // Traverse the call stack until function not found or max depth is reached
  } else if (fn && visited.length < goog.debug.MAX_STACK_DEPTH) {
    sb.push(goog.debug.getFunctionName(fn) + '(');
    var args = fn.arguments;
    // Args may be null for some special functions such as host objects or eval.
    for (var i = 0; args && i < args.length; i++) {
      if (i > 0) {
        sb.push(', ');
      }
      var argDesc;
      var arg = args[i];
      switch (typeof arg) {
        case 'object':
          argDesc = arg ? 'object' : 'null';
          break;

        case 'string':
          argDesc = arg;
          break;

        case 'number':
          argDesc = String(arg);
          break;

        case 'boolean':
          argDesc = arg ? 'true' : 'false';
          break;

        case 'function':
          argDesc = goog.debug.getFunctionName(arg);
          argDesc = argDesc ? argDesc : '[fn]';
          break;

        case 'undefined':
        default:
          argDesc = typeof arg;
          break;
      }

      if (argDesc.length > 40) {
        argDesc = argDesc.substr(0, 40) + '...';
      }
      sb.push(argDesc);
    }
    visited.push(fn);
    sb.push(')\n');
    /** @preserveTry */
    try {
      sb.push(goog.debug.getStacktraceHelper_(fn.caller, visited));
    } catch (e) {
      sb.push('[exception trying to get caller]\n');
    }

  } else if (fn) {
    sb.push('[...long stack...]');
  } else {
    sb.push('[end]');
  }
  return sb.join('');
};

/**
 * Set a custom function name resolver.
 * @param {function(Function): string} resolver Resolves functions to their
 *     names.
 */
goog.debug.setFunctionResolver = function(resolver) {
  goog.debug.fnNameResolver_ = resolver;
};

/**
 * Gets a function name
 * @param {Function} fn Function to get name of.
 * @return {string} Function's name.
 */
goog.debug.getFunctionName = function(fn) {
  if (goog.debug.fnNameCache_[fn]) {
    return goog.debug.fnNameCache_[fn];
  }
  if (goog.debug.fnNameResolver_) {
    var name = goog.debug.fnNameResolver_(fn);
    if (name) {
      goog.debug.fnNameCache_[fn] = name;
      return name;
    }
  }

  // Heuristically determine function name based on code.
  var functionSource = String(fn);
  if (!goog.debug.fnNameCache_[functionSource]) {
    var matches = /function ([^\(]+)/.exec(functionSource);
    if (matches) {
      var method = matches[1];
      goog.debug.fnNameCache_[functionSource] = method;
    } else {
      goog.debug.fnNameCache_[functionSource] = '[Anonymous]';
    }
  }

  return goog.debug.fnNameCache_[functionSource];
};

/**
 * Makes whitespace visible by replacing it with printable characters.
 * This is useful in finding diffrences between the expected and the actual
 * output strings of a testcase.
 * @param {string} string whose whitespace needs to be made visible.
 * @return {string} string whose whitespace is made visible.
 */
goog.debug.makeWhitespaceVisible = function(string) {
  return string.replace(/ /g, '[_]')
      .replace(/\f/g, '[f]')
      .replace(/\n/g, '[n]\n')
      .replace(/\r/g, '[r]')
      .replace(/\t/g, '[t]');
};

/**
 * Returns the type of a value. If a constructor is passed, and a suitable
 * string cannot be found, 'unknown type name' will be returned.
 *
 * <p>Forked rather than moved from {@link goog.asserts.getType_}
 * to avoid adding a dependency to goog.asserts.
 * @param {*} value A constructor, object, or primitive.
 * @return {string} The best display name for the value, or 'unknown type name'.
 */
goog.debug.runtimeType = function(value) {
  if (value instanceof Function) {
    return value.displayName || value.name || 'unknown type name';
  } else if (value instanceof Object) {
    return value.constructor.displayName || value.constructor.name ||
        Object.prototype.toString.call(value);
  } else {
    return value === null ? 'null' : typeof value;
  }
};

/**
 * Hash map for storing function names that have already been looked up.
 * @type {Object}
 * @private
 */
goog.debug.fnNameCache_ = {};

/**
 * Resolves functions to their names.  Resolved function names will be cached.
 * @type {function(Function):string}
 * @private
 */
goog.debug.fnNameResolver_;


text:
from tests import BaseTestCase
from redash.models import ApiKey

class TestDashboardShareResourcePost(BaseTestCase):
    def test_creates_api_key(self):
        dashboard = self.factory.create_dashboard()

        res = self.make_request('post', '/api/dashboards/{}/share'.format(dashboard.id))
        self.assertEqual(res.status_code, 200)
        self.assertEqual(res.json['api_key'], ApiKey.get_by_object(dashboard).api_key)

    def test_requires_admin_or_owner(self):
        dashboard = self.factory.create_dashboard()
        user = self.factory.create_user()

        res = self.make_request('post', '/api/dashboards/{}/share'.format(dashboard.id), user=user)
        self.assertEqual(res.status_code, 403)

        user.groups.append(self.factory.org.admin_group.id)
        user.save()

        res = self.make_request('post', '/api/dashboards/{}/share'.format(dashboard.id), user=user)
        self.assertEqual(res.status_code, 200)

class TestDashboardShareResourceDelete(BaseTestCase):
    def test_disables_api_key(self):
        dashboard = self.factory.create_dashboard()
        ApiKey.create_for_object(dashboard, self.factory.user)

        res = self.make_request('delete', '/api/dashboards/{}/share'.format(dashboard.id))
        self.assertEqual(res.status_code, 200)
        self.assertIsNone(ApiKey.get_by_object(dashboard))

    def test_ignores_when_no_api_key_exists(self):
        dashboard = self.factory.create_dashboard()

        res = self.make_request('delete', '/api/dashboards/{}/share'.format(dashboard.id))
        self.assertEqual(res.status_code, 200)

    def test_requires_admin_or_owner(self):
        dashboard = self.factory.create_dashboard()
        user = self.factory.create_user()

        res = self.make_request('delete', '/api/dashboards/{}/share'.format(dashboard.id), user=user)
        self.assertEqual(res.status_code, 403)

        user.groups.append(self.factory.org.admin_group.id)
        user.save()

        res = self.make_request('delete', '/api/dashboards/{}/share'.format(dashboard.id), user=user)
        self.assertEqual(res.status_code, 200)


text:
import {Binding, resolveForwardRef, Injectable, Inject} from 'angular2/src/core/di';
import {DEFAULT_PIPES_TOKEN} from 'angular2/src/core/pipes';
import {
  Type,
  isBlank,
  isType,
  isPresent,
  normalizeBlank,
  stringify,
  isArray,
  isPromise
} from 'angular2/src/core/facade/lang';
import {BaseException} from 'angular2/src/core/facade/exceptions';
import {Promise, PromiseWrapper} from 'angular2/src/core/facade/async';
import {ListWrapper, Map, MapWrapper} from 'angular2/src/core/facade/collection';

import {DirectiveResolver} from './directive_resolver';

import {AppProtoView, AppProtoViewMergeMapping} from './view';
import {ProtoViewRef} from './view_ref';
import {DirectiveBinding} from './element_injector';
import {ViewResolver} from './view_resolver';
import {PipeResolver} from './pipe_resolver';
import {ViewMetadata} from 'angular2/src/core/metadata';
import {ComponentUrlMapper} from './component_url_mapper';
import {ProtoViewFactory} from './proto_view_factory';
import {UrlResolver} from 'angular2/src/core/services/url_resolver';
import {AppRootUrl} from 'angular2/src/core/services/app_root_url';
import {ElementBinder} from './element_binder';
import {wtfStartTimeRange, wtfEndTimeRange} from '../profile/profile';
import {PipeBinding} from '../pipes/pipe_binding';

import {
  RenderDirectiveMetadata,
  ViewDefinition,
  RenderCompiler,
  ViewType,
  RenderProtoViewMergeMapping,
  RenderProtoViewRef
} from 'angular2/src/core/render/api';

/**
 * Cache that stores the AppProtoView of the template of a component.
 * Used to prevent duplicate work and resolve cyclic dependencies.
 */
@Injectable()
export class CompilerCache {
  _cache = new Map<Type, AppProtoView>();
  _hostCache = new Map<Type, AppProtoView>();

  set(component: Type, protoView: AppProtoView): void { this._cache.set(component, protoView); }

  get(component: Type): AppProtoView {
    var result = this._cache.get(component);
    return normalizeBlank(result);
  }

  setHost(component: Type, protoView: AppProtoView): void {
    this._hostCache.set(component, protoView);
  }

  getHost(component: Type): AppProtoView {
    var result = this._hostCache.get(component);
    return normalizeBlank(result);
  }

  clear(): void {
    this._cache.clear();
    this._hostCache.clear();
  }
}

/*
 * ## URL Resolution
 *
 * ```
 * var appRootUrl: AppRootUrl = ...;
 * var componentUrlMapper: ComponentUrlMapper = ...;
 * var urlResolver: UrlResolver = ...;
 *
 * var componentType: Type = ...;
 * var componentAnnotation: ComponentAnnotation = ...;
 * var viewAnnotation: ViewAnnotation = ...;
 *
 * // Resolving a URL
 *
 * var url = viewAnnotation.templateUrl;
 * var componentUrl = componentUrlMapper.getUrl(componentType);
 * var componentResolvedUrl = urlResolver.resolve(appRootUrl.value, componentUrl);
 * var templateResolvedUrl = urlResolver.resolve(componentResolvedUrl, url);
 * ```
 */
/**
 * Low-level service for compiling {@link Component}s into {@link ProtoViewRef ProtoViews}s, which
 * can later be used to create and render a Component instance.
 *
 * Most applications should instead use higher-level {@link DynamicComponentLoader} service, which
 * both compiles and instantiates a Component.
 */
@Injectable()
export class Compiler {
  private _compiling = new Map<Type, Promise<AppProtoView>>();
  private _appUrl: string;
  private _defaultPipes: Type[];

  /**
   * @private
   */
  constructor(private _directiveResolver: DirectiveResolver, private _pipeResolver: PipeResolver,
              @Inject(DEFAULT_PIPES_TOKEN) _defaultPipes: Type[],
              private _compilerCache: CompilerCache, private _viewResolver: ViewResolver,
              private _componentUrlMapper: ComponentUrlMapper, private _urlResolver: UrlResolver,
              private _render: RenderCompiler, private _protoViewFactory: ProtoViewFactory,
              appUrl: AppRootUrl) {
    this._defaultPipes = _defaultPipes;
    this._appUrl = appUrl.value;
  }

  private _bindDirective(directiveTypeOrBinding): DirectiveBinding {
    if (directiveTypeOrBinding instanceof DirectiveBinding) {
      return directiveTypeOrBinding;
    } else if (directiveTypeOrBinding instanceof Binding) {
      let annotation = this._directiveResolver.resolve(directiveTypeOrBinding.token);
      return DirectiveBinding.createFromBinding(directiveTypeOrBinding, annotation);
    } else {
      let annotation = this._directiveResolver.resolve(directiveTypeOrBinding);
      return DirectiveBinding.createFromType(directiveTypeOrBinding, annotation);
    }
  }

  private _bindPipe(typeOrBinding): PipeBinding {
    let meta = this._pipeResolver.resolve(typeOrBinding);
    return PipeBinding.createFromType(typeOrBinding, meta);
  }

  /**
   * Compiles a {@link Component} and returns a promise for this component's {@link ProtoViewRef}.
   *
   * Returns `ProtoViewRef` that can be later used to instantiate a component via
   * {@link ViewContainerRef#createHostView} or {@link AppViewManager#createHostViewInContainer}.
   */
  compileInHost(componentType: Type): Promise<ProtoViewRef> {
    var r = wtfStartTimeRange('Compiler#compile()', stringify(componentType));

    var hostAppProtoView = this._compilerCache.getHost(componentType);
    var hostPvPromise;
    if (isPresent(hostAppProtoView)) {
      hostPvPromise = PromiseWrapper.resolve(hostAppProtoView);
    } else {
      var componentBinding: DirectiveBinding = this._bindDirective(componentType);
      Compiler._assertTypeIsComponent(componentBinding);

      var directiveMetadata = componentBinding.metadata;
      hostPvPromise = this._render.compileHost(directiveMetadata)
                          .then((hostRenderPv) => {
                            var protoViews = this._protoViewFactory.createAppProtoViews(
                                componentBinding, hostRenderPv, [componentBinding], []);
                            return this._compileNestedProtoViews(protoViews, componentType,
                                                                 new Map<Type, AppProtoView>());
                          })
                          .then((appProtoView) => {
                            this._compilerCache.setHost(componentType, appProtoView);
                            return appProtoView;
                          });
    }
    return hostPvPromise.then((hostAppProtoView) => {
      wtfEndTimeRange(r);
      return hostAppProtoView.ref;
    });
  }

  private _compile(componentBinding: DirectiveBinding,
                   componentPath: Map<Type, AppProtoView>): Promise<AppProtoView>|
      AppProtoView {
    var component = <Type>componentBinding.key.token;
    var protoView = this._compilerCache.get(component);
    if (isPresent(protoView)) {
      // The component has already been compiled into an AppProtoView,
      // returns a plain AppProtoView, not wrapped inside of a Promise, for performance reasons.
      return protoView;
    }
    var resultPromise = this._compiling.get(component);
    if (isPresent(resultPromise)) {
      // The component is already being compiled, attach to the existing Promise
      // instead of re-compiling the component.
      // It happens when a template references a component multiple times.
      return resultPromise;
    }
    var view = this._viewResolver.resolve(component);

    var directives = this._flattenDirectives(view);

    for (var i = 0; i < directives.length; i++) {
      if (!Compiler._isValidDirective(directives[i])) {
        throw new BaseException(
            `Unexpected directive value '${stringify(directives[i])}' on the View of component '${stringify(component)}'`);
      }
    }

    var boundDirectives = this._removeDuplicatedDirectives(
        directives.map(directive => this._bindDirective(directive)));

    var pipes = this._flattenPipes(view);
    var boundPipes = pipes.map(pipe => this._bindPipe(pipe));

    var renderTemplate = this._buildRenderTemplate(component, view, boundDirectives);
    resultPromise =
        this._render.compile(renderTemplate)
            .then((renderPv) => {
              var protoViews = this._protoViewFactory.createAppProtoViews(
                  componentBinding, renderPv, boundDirectives, boundPipes);
              return this._compileNestedProtoViews(protoViews, component, componentPath);
            })
            .then((appProtoView) => {
              this._compilerCache.set(component, appProtoView);
              MapWrapper.delete(this._compiling, component);
              return appProtoView;
            });
    this._compiling.set(component, resultPromise);
    return resultPromise;
  }

  private _removeDuplicatedDirectives(directives: DirectiveBinding[]): DirectiveBinding[] {
    var directivesMap = new Map<number, DirectiveBinding>();
    directives.forEach((dirBinding) => { directivesMap.set(dirBinding.key.id, dirBinding); });
    return MapWrapper.values(directivesMap);
  }

  private _compileNestedProtoViews(appProtoViews: AppProtoView[], componentType: Type,
                                   componentPath: Map<Type, AppProtoView>): Promise<AppProtoView> {
    var nestedPVPromises = [];
    componentPath = MapWrapper.clone(componentPath);
    if (appProtoViews[0].type === ViewType.COMPONENT) {
      componentPath.set(componentType, appProtoViews[0]);
    }
    appProtoViews.forEach(appProtoView => {
      this._collectComponentElementBinders(appProtoView)
          .forEach((elementBinder: ElementBinder) => {
            var nestedComponent = elementBinder.componentDirective;
            var nestedComponentType = <Type>nestedComponent.key.token;
            var elementBinderDone =
                (nestedPv: AppProtoView) => { elementBinder.nestedProtoView = nestedPv; };
            if (componentPath.has(nestedComponentType)) {
              // cycle...
              if (appProtoView.isEmbeddedFragment) {
                throw new BaseException(
                    `<ng-content> is used within the recursive path of ${stringify(nestedComponentType)}`);
              } else if (appProtoView.type === ViewType.COMPONENT) {
                throw new BaseException(
                    `Unconditional component cycle in ${stringify(nestedComponentType)}`);
              } else {
                elementBinderDone(componentPath.get(nestedComponentType));
              }
            } else {
              var nestedCall = this._compile(nestedComponent, componentPath);
              if (isPromise(nestedCall)) {
                nestedPVPromises.push((<Promise<AppProtoView>>nestedCall).then(elementBinderDone));
              } else {
                elementBinderDone(<AppProtoView>nestedCall);
              }
            }
          });
    });
    return PromiseWrapper.all(nestedPVPromises)
        .then(_ => PromiseWrapper.all(
                  appProtoViews.map(appProtoView => this._mergeProtoView(appProtoView))))
        .then(_ => appProtoViews[0]);
  }

  private _mergeProtoView(appProtoView: AppProtoView): Promise<any> {
    if (appProtoView.type !== ViewType.HOST && appProtoView.type !== ViewType.EMBEDDED) {
      return null;
    }
    return this._render.mergeProtoViewsRecursively(this._collectMergeRenderProtoViews(appProtoView))
        .then((mergeResult: RenderProtoViewMergeMapping) => {
          appProtoView.mergeMapping = new AppProtoViewMergeMapping(mergeResult);
        });
  }

  private _collectMergeRenderProtoViews(appProtoView:
                                            AppProtoView): Array<RenderProtoViewRef | any[]> {
    var result = [appProtoView.render];
    for (var i = 0; i < appProtoView.elementBinders.length; i++) {
      var binder = appProtoView.elementBinders[i];
      if (isPresent(binder.nestedProtoView)) {
        if (binder.hasStaticComponent() ||
            (binder.hasEmbeddedProtoView() && binder.nestedProtoView.isEmbeddedFragment)) {
          result.push(this._collectMergeRenderProtoViews(binder.nestedProtoView));
        } else {
          result.push(null);
        }
      }
    }
    return result;
  }

  private _collectComponentElementBinders(appProtoView: AppProtoView): ElementBinder[] {
    var componentElementBinders = [];
    appProtoView.elementBinders.forEach((elementBinder) => {
      if (isPresent(elementBinder.componentDirective)) {
        componentElementBinders.push(elementBinder);
      }
    });
    return componentElementBinders;
  }

  private _buildRenderTemplate(component, view, directives): ViewDefinition {
    var componentUrl =
        this._urlResolver.resolve(this._appUrl, this._componentUrlMapper.getUrl(component));
    var templateAbsUrl = null;
    var styleAbsUrls = null;
    if (isPresent(view.templateUrl) && view.templateUrl.trim().length > 0) {
      templateAbsUrl = this._urlResolver.resolve(componentUrl, view.templateUrl);
    } else if (isPresent(view.template)) {
      // Note: If we have an inline template, we also need to send
      // the url for the component to the render so that it
      // is able to resolve urls in stylesheets.
      templateAbsUrl = componentUrl;
    }
    if (isPresent(view.styleUrls)) {
      styleAbsUrls =
          ListWrapper.map(view.styleUrls, url => this._urlResolver.resolve(componentUrl, url));
    }
    return new ViewDefinition({
      componentId: stringify(component),
      templateAbsUrl: templateAbsUrl, template: view.template,
      styleAbsUrls: styleAbsUrls,
      styles: view.styles,
      directives: ListWrapper.map(directives, directiveBinding => directiveBinding.metadata),
      encapsulation: view.encapsulation
    });
  }

  private _flattenPipes(view: ViewMetadata): any[] {
    if (isBlank(view.pipes)) return this._defaultPipes;
    var pipes = ListWrapper.clone(this._defaultPipes);
    this._flattenList(view.pipes, pipes);
    return pipes;
  }

  private _flattenDirectives(view: ViewMetadata): Type[] {
    if (isBlank(view.directives)) return [];
    var directives = [];
    this._flattenList(view.directives, directives);
    return directives;
  }

  private _flattenList(tree: any[], out: Array<Type | Binding | any[]>): void {
    for (var i = 0; i < tree.length; i++) {
      var item = resolveForwardRef(tree[i]);
      if (isArray(item)) {
        this._flattenList(item, out);
      } else {
        out.push(item);
      }
    }
  }

  private static _isValidDirective(value: Type | Binding): boolean {
    return isPresent(value) && (value instanceof Type || value instanceof Binding);
  }

  private static _assertTypeIsComponent(directiveBinding: DirectiveBinding): void {
    if (directiveBinding.metadata.type !== RenderDirectiveMetadata.COMPONENT_TYPE) {
      throw new BaseException(
          `Could not load '${stringify(directiveBinding.key.token)}' because it is not a component.`);
    }
  }
}


text:
<?php
namespace MusicBrainz\HttpAdapters;

use GuzzleHttp\ClientInterface;
use MusicBrainz\Exception;

/**
 * Class GuzzleFiveAdapter
 *
 * Copied from https://github.com/powered-by-moe/MusicBrainz
 *
 * @package MusicBrainz\HttpAdapters
 */
class GuzzleFiveAdapter extends AbstractHttpAdapter
{
    /**
     * @var ClientInterface
     */
    private $client;

    /**
     * Initialize class
     *
     * @param ClientInterface $client
     * @param null $endpoint
     */
    public function __construct(ClientInterface $client, $endpoint = NULL)
    {
        $this->client = $client;

        if (filter_var($endpoint, FILTER_VALIDATE_URL)) {
            $this->endpoint = $endpoint;
        }
    }

    /**
     * Perform an HTTP request on MusicBrainz
     *
     * @param  string $path
     * @param  array $params
     * @param  array $options
     * @param  boolean $isAuthRequired
     * @param  boolean $returnArray
     *
     * @throws Exception
     * @return array
     */
    public function call($path, array $params = array(), array $options = array(), $isAuthRequired = FALSE, $returnArray = FALSE)
    {
        if ($options['user-agent'] == '') {
            throw new Exception('You must set a valid User Agent before accessing the MusicBrainz API');
        }

        $requestOptions = [
            'headers'        => [
                'Accept'     => 'application/json',
                'User-Agent' => $options['user-agent']
            ],
            'query' => $params
        ];

        if ($isAuthRequired) {
            if ($options['user'] != NULL && $options['password'] != NULL) {
                $requestOptions['auth'] = [
                    'username' => $options['user'],
                    'password' => $options['password'],
                    CURLAUTH_DIGEST
                ];
            } else {
                throw new Exception('Authentication is required');
            }
        }

        $request = $this->client->createRequest('GET', $this->endpoint . '/' . $path, $requestOptions);

        // musicbrainz throttle
        sleep(1);

        return $this->client->send($request)->json();
    }
}


text:
#if !defined(CETTY_CHANNEL_SOCKET_SERVERSOCKETCHANNEL_H)
#define CETTY_CHANNEL_SOCKET_SERVERSOCKETCHANNEL_H

/*
 * Copyright (c) 2010-2011 frankee zhou (frankee.zhou at gmail dot com)
 * Distributed under under the Apache License, version 2.0 (the "License").
 */

#include "cetty/channel/AbstractServerChannel.h"

namespace cetty { namespace channel  { namespace socket {

/**
 * A TCP/IP {@link ServerChannel} which accepts incoming TCP/IP connections.
 *
 *
 * @author Trustin Lee
 *
 * @author Frankee Zhou
 *
 * @apiviz.landmark
 * @apiviz.composedOf org.jboss.netty.channel.socket.ServerSocketChannelConfig
 */

class ServerSocketChannel : public ::cetty::channel::AbstractServerChannel {
protected:
    /**
     * Creates a new instance.
     *
     * @param factory
     *        the factory which created this channel
     * @param pipeline
     *        the pipeline which is going to be attached to this channel
     * @param sink
     *        the sink which will receive downstream events from the pipeline
     *        and send upstream events to the pipeline
     */
    ServerSocketChannel(
            ChannelFactory* factory,
            ChannelPipeline* pipeline,
            ChannelSink* sink) : AbstractServerChannel(factory, pipeline, sink) {
    }

    virtual ~ServerSocketChannel() {}
};

}}}

#endif //#if !defined(CETTY_CHANNEL_SOCKET_SERVERSOCKETCHANNEL_H)


text:
.. _jitclass:

===========================================
Compiling Python classes with ``@jitclass``
===========================================

.. note::

  This is a early version of jitclass support. Not all compiling features are
  exposed or implemented, yet.

Numba supports code generation for classes via the :func:`numba.jitclass`
decorator.  A class can be marked for optimization using this decorator along
with a specification of the types of each field.  We call the resulting class
object a *jitclass*.  All methods of a jitclass are compiled into nopython
functions.  The data of a jitclass instance is allocated on the heap as a
C-compatible structure so that any compiled functions can have direct access
to the underlying data, bypassing the interpreter.

Basic usage
===========

Here's an example of a jitclass:

.. literalinclude:: ../../../numba/tests/doc_examples/test_jitclass.py
   :language: python
   :start-after: magictoken.ex_jitclass.begin
   :end-before: magictoken.ex_jitclass.end
   :dedent: 8

In the above example, a ``spec`` is provided as a list of 2-tuples.  The tuples
contain the name of the field and the Numba type of the field.  Alternatively,
user can use a dictionary (an ``OrderedDict`` preferably for stable field
ordering), which maps field names to types.

The definition of the class requires at least a ``__init__`` method for
initializing each defined fields.  Uninitialized fields contains garbage data.
Methods and properties (getters and setters only) can be defined.  They will be
automatically compiled.

Specifying ``numba.typed`` containers as class members
======================================================
It is often desirable to use a ``numba.typed.Dict`` or a ``numba.typed.List`` as
a class member in a ``jitclass``. Methods for using these types and various
common patterns are presented in the following:

First, using explicit Numba types and explicit construction.

.. code-block:: python

    from numba import jitclass, types, typed

    # key and value types
    kv_ty = (types.int64, types.unicode_type)

    # A container class with:
    # * member 'd' holding a typed dictionary of int64 -> unicode string (kv_ty)
    # * member 'l' holding a typed list of float64
    @jitclass([('d', types.DictType(*kv_ty)),
               ('l', types.ListType(types.float64))])
    class ContainerHolder(object):
        def __init__(self):
            # initialize the containers
            self.d = typed.Dict.empty(*kv_ty)
            self.l = typed.List.empty_list(types.float64)

    container = ContainerHolder()
    container.d[1] = "apple"
    container.d[2] = "orange"
    container.l.append(123.)
    container.l.append(456.)
    print(container.d) # {1: apple, 2: orange}
    print(container.l) # [123.0, 456.0]

Another useful pattern is to use the ``numba.typed`` container attribute
``_numba_type_`` to find the type of a container, this can be accessed directly
from an instance of the container in the Python interpreter. The same
information can be obtained by calling :func:`numba.typeof` on the instance. For
example:

.. code-block:: python

    from numba import jitclass, typed, typeof

    d = typed.Dict()
    d[1] = "apple"
    d[2] = "orange"
    l = typed.List()
    l.append(123.)
    l.append(456.)

    @jitclass([('d', typeof(d)), ('l', typeof(l))])
    class ContainerInstHolder(object):
        def __init__(self, dict_inst, list_inst):
            self.d = dict_inst
            self.l = list_inst

    container = ContainerInstHolder(d, l)
    print(container.d) # {1: apple, 2: orange}
    print(container.l) # [123.0, 456.0]

It is worth noting that the instance of the container in a ``jitclass`` must be
initialized before use, for example, this will cause an invalid memory access
as ``self.d`` is written to without ``d`` being initialized as a ``type.Dict``
instance of the type specified.

.. code-block:: python

    from numba import jitclass, types

    dict_ty = types.DictType(types.int64, types.unicode_type)

    @jitclass([('d', dict_ty)])
    class NotInitilisingContainer(object):
        def __init__(self):
            self.d[10] = "apple" # this is invalid, `d` is not initialized

    NotInitilisingContainer() # segmentation fault/memory access violation

Support operations
==================

The following operations of jitclasses work in both the interpreter and Numba
compiled functions:

* calling the jitclass class object to construct a new instance
  (e.g. ``mybag = Bag(123)``);
* read/write access to attributes and properties (e.g. ``mybag.value``);
* calling methods (e.g. ``mybag.increment(3)``);
* calling static methods as instance attributes (e.g. ``mybag.add(1, 1)``);
* calling static methods as class attributes (e.g. ``Bag.add(1, 2)``);

Using jitclasses in Numba compiled function is more efficient.
Short methods can be inlined (at the discretion of LLVM inliner).
Attributes access are simply reading from a C structure.
Using jitclasses from the interpreter has the same overhead of calling any
Numba compiled function from the interpreter.  Arguments and return values
must be unboxed or boxed between Python objects and native representation.
Values encapsulated by a jitclass does not get boxed into Python object when
the jitclass instance is handed to the interpreter.  It is during attribute
access to the field values that they are boxed.
Calling static methods as class attributes is only supported outside of the
class definition (i.e. you can't call ``Bag.add()`` from within another method
of ``Bag``).

Limitations
===========

* A jitclass class object is treated as a function (the constructor) inside
  a Numba compiled function.
* ``isinstance()`` only works in the interpreter.
* Manipulating jitclass instances in the interpreter is not optimized, yet.
* Support for jitclasses are available on CPU only.
  (Note: Support for GPU devices is planned for a future release.)

The decorator: ``@jitclass``
============================

.. autofunction:: numba.experimental.jitclass