text:
PROXIED_API(PPB_X509Certificate_Private)

PROXIED_IFACE(PPB_X509CERTIFICATE_PRIVATE_INTERFACE_0_1,
              PPB_X509Certificate_Private_0_1)

#if !defined(OS_NACL)
PROXIED_API(PPB_Broker)

PROXIED_IFACE(PPB_BROKER_TRUSTED_INTERFACE_0_2,
              PPB_BrokerTrusted_0_2)
PROXIED_IFACE(PPB_BROKER_TRUSTED_INTERFACE_0_3,
              PPB_BrokerTrusted_0_3)
PROXIED_IFACE(PPB_BROWSERFONT_TRUSTED_INTERFACE_1_0,
              PPB_BrowserFont_Trusted_1_0)
PROXIED_IFACE(PPB_CONTENTDECRYPTOR_PRIVATE_INTERFACE_0_14,
              PPB_ContentDecryptor_Private_0_14)
PROXIED_IFACE(PPB_CHARSET_TRUSTED_INTERFACE_1_0,
              PPB_CharSet_Trusted_1_0)
PROXIED_IFACE(PPB_FILECHOOSER_TRUSTED_INTERFACE_0_5,
              PPB_FileChooserTrusted_0_5)
PROXIED_IFACE(PPB_FILECHOOSER_TRUSTED_INTERFACE_0_6,
              PPB_FileChooserTrusted_0_6)
PROXIED_IFACE(PPB_FILEREFPRIVATE_INTERFACE_0_1,
              PPB_FileRefPrivate_0_1)
PROXIED_IFACE(PPB_FIND_PRIVATE_INTERFACE_0_3,
              PPB_Find_Private_0_3)
PROXIED_IFACE(PPB_FLASHFULLSCREEN_INTERFACE_0_1,
              PPB_FlashFullscreen_0_1)
PROXIED_IFACE(PPB_FLASHFULLSCREEN_INTERFACE_1_0,
              PPB_FlashFullscreen_0_1)
PROXIED_IFACE(PPB_PDF_INTERFACE,
              PPB_PDF)
#if defined(OS_CHROMEOS)
PROXIED_IFACE(PPB_PLATFORMVERIFICATION_PRIVATE_INTERFACE_0_2,
              PPB_PlatformVerification_Private_0_2)
#endif

PROXIED_IFACE(PPB_URLLOADERTRUSTED_INTERFACE_0_3,
              PPB_URLLoaderTrusted_0_3)

PROXIED_IFACE(PPB_OUTPUTPROTECTION_PRIVATE_INTERFACE_0_1,
              PPB_OutputProtection_Private_0_1)
#endif  // !defined(OS_NACL)

#include "ppapi/thunk/interfaces_postamble.h"


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="QuitMessage.cs" company="Kephas Software SRL">
//   Copyright (c) Kephas Software SRL. All rights reserved.
//   Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
//   Implements the quit message class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Kephas.Commands.Messaging.Endpoints
{
    using Kephas.ComponentModel.DataAnnotations;
    using Kephas.Messaging;
    using Kephas.Security.Authorization;
    using Kephas.Security.Authorization.AttributedModel;

    /// <summary>
    /// A quit message.
    /// </summary>
    [DisplayInfo(Description = "Quits the application.")]
    [RequiresPermission(typeof(AppAdminPermission))]
    public class QuitMessage : IMessage
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
version=`git rev-parse --short=10 @`
private=""

if [ "$1" = "release" ]; then
    version=`cat ../../VERSION`
elif [ "$1" = "private" ]; then
    private="-p"
fi

echo "Generating documentation..."
documentation ../../src/js/pannellum.js ../../src/js/libpannellum.js -o generated_docs -f html --name Pannellum --project-version $version -g $private


text:
package org.elasticsearch.action.support.master;

import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;

import java.io.IOException;
import java.util.Objects;

import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg;

/**
 * A response that indicates that a request has been acknowledged
 */
public class AcknowledgedResponse extends ActionResponse implements ToXContentObject {

    private static final ParseField ACKNOWLEDGED = new ParseField("acknowledged");

    protected static <T extends AcknowledgedResponse> void declareAcknowledgedField(ConstructingObjectParser<T, Void> objectParser) {
        objectParser.declareField(constructorArg(), (parser, context) -> parser.booleanValue(), ACKNOWLEDGED,
            ObjectParser.ValueType.BOOLEAN);
    }

    protected boolean acknowledged;

    public AcknowledgedResponse() {
    }

    public AcknowledgedResponse(boolean acknowledged) {
        this.acknowledged = acknowledged;
    }

    /**
     * Returns whether the response is acknowledged or not
     * @return true if the response is acknowledged, false otherwise
     */
    public final boolean isAcknowledged() {
        return acknowledged;
    }

    @Override
    public void readFrom(StreamInput in) throws IOException {
        super.readFrom(in);
        acknowledged = in.readBoolean();
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        super.writeTo(out);
        out.writeBoolean(acknowledged);
    }

    @Override
    public final XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject();
        builder.field(ACKNOWLEDGED.getPreferredName(), isAcknowledged());
        addCustomFields(builder, params);
        builder.endObject();
        return builder;
    }

    protected void addCustomFields(XContentBuilder builder, Params params) throws IOException {

    }

    /**
     * A generic parser that simply parses the acknowledged flag
     */
    private static final ConstructingObjectParser<Boolean, Void> ACKNOWLEDGED_FLAG_PARSER = new ConstructingObjectParser<>(
            "acknowledged_flag", true, args -> (Boolean) args[0]);

    static {
        ACKNOWLEDGED_FLAG_PARSER.declareField(constructorArg(), (parser, context) -> parser.booleanValue(), ACKNOWLEDGED,
                ObjectParser.ValueType.BOOLEAN);
    }

    public static AcknowledgedResponse fromXContent(XContentParser parser) throws IOException {
        return new AcknowledgedResponse(ACKNOWLEDGED_FLAG_PARSER.apply(parser, null));
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        AcknowledgedResponse that = (AcknowledgedResponse) o;
        return isAcknowledged() == that.isAcknowledged();
    }

    @Override
    public int hashCode() {
        return Objects.hash(isAcknowledged());
    }
}


text:
#include <zephyr/kernel.h>
#include <host/crypto.h>
#include "mocks/hci_core.h"
#include "mocks/hci_core_expects.h"
#include "mocks/hmac_prng.h"
#include "mocks/hmac_prng_expects.h"
#include "mocks/crypto_help_utils.h"
#include "host_mocks/assert.h"

ZTEST_SUITE(prng_init_invalid_cases, NULL, NULL, NULL, NULL, NULL);

/*
 *  Test prng_init() fails when bt_hci_le_rand() fails
 *
 *  Constraints:
 *   - bt_hci_le_rand() fails and returns a negative error code.
 *
 *  Expected behaviour:
 *   - prng_init() returns a negative error code (failure)
 */
ZTEST(prng_init_invalid_cases, test_bt_hci_le_rand_fails)
{
	int err;
	uint8_t expected_args_history[] = {8};

	bt_hci_le_rand_fake.return_val = -1;

	err = prng_init();

	expect_call_count_bt_hci_le_rand(1, expected_args_history);

	zassert_true(err < 0, "'%s()' returned unexpected error code %d", test_unit_name, err);
}

/*
 *  Test prng_init() fails when tc_hmac_prng_init() fails
 *
 *  Constraints:
 *   - bt_hci_le_rand() succeeds and returns 0 (success)
 *   - tc_hmac_prng_init() fails and returns 'TC_CRYPTO_FAIL'.
 *
 *  Expected behaviour:
 *   - prng_init() returns a negative error code '-EIO' (failure)
 */
ZTEST(prng_init_invalid_cases, test_tc_hmac_prng_init_fails)
{
	int err;
	uint8_t expected_args_history[] = {8};
	struct tc_hmac_prng_struct *hmac_prng = bt_crypto_get_hmac_prng_instance();

	bt_hci_le_rand_fake.return_val = 0;
	tc_hmac_prng_init_fake.return_val = TC_CRYPTO_FAIL;

	err = prng_init();

	expect_call_count_bt_hci_le_rand(1, expected_args_history);
	expect_single_call_tc_hmac_prng_init(hmac_prng, 8);

	zassert_true(err == -EIO, "'%s()' returned unexpected error code %d", test_unit_name, err);
}

/*
 *  Test prng_init() fails when prng_reseed() fails
 *
 *  Constraints:
 *   - bt_hci_le_rand() succeeds and returns 0 (success)
 *   - tc_hmac_prng_init() succeeds and returns 'TC_CRYPTO_SUCCESS'.
 *   - tc_hmac_prng_reseed() fails and returns 'TC_CRYPTO_FAIL'.
 *
 *  Expected behaviour:
 *   - prng_init() returns a negative error code '-EIO' (failure)
 */
ZTEST(prng_init_invalid_cases, test_prng_reseed_fails)
{
	int err;
	uint8_t expected_args_history[] = {8, 32};
	struct tc_hmac_prng_struct *hmac_prng = bt_crypto_get_hmac_prng_instance();

	bt_hci_le_rand_fake.return_val = 0;
	tc_hmac_prng_init_fake.return_val = TC_CRYPTO_SUCCESS;
	tc_hmac_prng_reseed_fake.return_val = TC_CRYPTO_FAIL;

	err = prng_init();

	expect_call_count_bt_hci_le_rand(2, expected_args_history);
	expect_single_call_tc_hmac_prng_init(hmac_prng, 8);
	expect_single_call_tc_hmac_prng_reseed(hmac_prng, 32, sizeof(int64_t));

	zassert_true(err == -EIO, "'%s()' returned unexpected error code %d", test_unit_name, err);
}


text:
package org.docksidestage.mysql.dbflute.exbhv;

import org.docksidestage.mysql.dbflute.bsbhv.BsWhiteImplicitReverseFkRefBhv;

/**
 * The behavior of white_implicit_reverse_fk_ref.
 * <p>
 * You can implement your original methods here.
 * This class remains when re-generating.
 * </p>
 * @author DBFlute(AutoGenerator)
 */
public class WhiteImplicitReverseFkRefBhv extends BsWhiteImplicitReverseFkRefBhv {
}


text:
using System;
using System.Linq;
using System.Collections.Generic;

public class Student
{

    private string firstName;
    private string lastName;

    public Student(string firstName, string lastName, IList<Exam> exams = null)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Exams = exams;
    }

    public string FirstName
    {
        get
        {
            return this.firstName;
        }

        set
        {
            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentNullException("First name can not be null or empty");
            }

            this.firstName = value;
        }
    }

    public string LastName
    {
        get
        {
            return this.lastName;
        }

        set
        {
            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentNullException("First name can not be null or empty");
            }

            this.lastName = value;
        }
    }

    public IList<Exam> Exams { get; set; }

    public IList<ExamResult> CheckExams()
    {
        if (this.Exams == null)
        {
            throw new ArgumentNullException("this.Exam does not exist");
        }

        if (this.Exams.Count == 0)
        {
            throw new ArgumentOutOfRangeException("The Students has no exams");
        }

        IList<ExamResult> results = new List<ExamResult>();
        for (int i = 0; i < this.Exams.Count; i++)
        {
            results.Add(this.Exams[i].Check());
        }

        return results;
    }

    public double CalcAverageExamResultInPercents()
    {
        if (this.Exams == null)
        {
            throw new ArgumentNullException("this.Exam does not exist");
        }

        if (this.Exams.Count == 0)
        {
            // No exams --> return -1;
            return -1;
        }

        double[] examScore = new double[this.Exams.Count];
        IList<ExamResult> examResults = this.CheckExams();
        for (int i = 0; i < examResults.Count; i++)
        {
            examScore[i] =
                ((double)examResults[i].Grade - examResults[i].MinGrade) /
                (examResults[i].MaxGrade - examResults[i].MinGrade);
        }

        return examScore.Average();
    }
}


text: This repository is renamed and moved to https://github.com/mathildor/TF-SegNet.


text:
from GenericRequest import GenericRequest

class AddPlayerToClanWhitelistRequest(GenericRequest):
    def __init__(self, session, player, level, title=""):
        super(AddPlayerToClanWhitelistRequest, self).__init__(session)
        self.url = session.serverURL + "clan_whitelist.php"
        self.requestData["action"] = "add"
        self.requestData["pwd"] = session.pwd
        self.requestData["addwho"] = player
        self.requestData["level"] = level
        self.requestData["title"] = title


text:
@implementation MPUIColorToNSStringValueTransformer

+ (Class)transformedValueClass
{
    return [NSString class];
}

+ (BOOL)allowsReverseTransformation
{
    return YES;
}

- (id)transformedValue:(id)value
{
    if (value && [value isKindOfClass:[UIColor class]]) {
        UIColor *colorValue = (UIColor *)value;

        CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(CGColorGetColorSpace(colorValue.CGColor));
        if (colorSpaceModel == kCGColorSpaceModelMonochrome || colorSpaceModel == kCGColorSpaceModelRGB) {
            size_t numberOfComponents = CGColorGetNumberOfComponents(colorValue.CGColor);
            const CGFloat *components = CGColorGetComponents(colorValue.CGColor);

            if (colorSpaceModel == kCGColorSpaceModelMonochrome && numberOfComponents >= 1) {
                CGFloat w = (255 * components[0]);
                CGFloat a = (numberOfComponents > 1 ? components[1] : 1.0f);

                return [NSString stringWithFormat:@"rgba(%.0f, %.0f, %.0f, %.2f)", w, w, w, a];
            }
            else if (colorSpaceModel == kCGColorSpaceModelRGB && numberOfComponents >= 3)
            {
                CGFloat r = (255 * components[0]);
                CGFloat g = (255 * components[1]);
                CGFloat b = (255 * components[2]);
                CGFloat a = (numberOfComponents > 3 ? components[3] : 1.0f);

                return [NSString stringWithFormat:@"rgba(%.0f, %.0f, %.0f, %.2f)", r, g, b, a];
            }
        }
    }

    return nil;
}

- (id)reverseTransformedValue:(id)value
{
    if ([value isKindOfClass:[NSString class]]) {
        NSString *stringValue = (NSString *)value;

        NSScanner *scanner = [NSScanner scannerWithString:stringValue];
        [scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"rgba(), "]];
        [scanner setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];

        int r = 0, g = 0, b = 0;
        float a = 1.0f;
        if ([scanner scanInt:&r] &&
            [scanner scanInt:&g] &&
            [scanner scanInt:&b] &&
            [scanner scanFloat:&a])
        {
            UIColor *color = [[UIColor alloc] initWithRed:(r/255.0f) green:(g/255.0f) blue:(b/255.0f) alpha:a];
            return color;
        }
    }

    return nil;
}

@end


text:
using NUnit.Framework;

namespace EasyAssertions.UnitTests;

public class BufferTests
{
    [Test]
    public void EnumerateTwice_SourceIsEnumeratedOnce()
    {
        var source = new TestEnumerable<int>(new[] { 1 });
        var sut = Buffer.Create(source);

        CollectionAssert.AreEqual(new[] { 1 }, sut);
        CollectionAssert.AreEqual(new[] { 1 }, sut);

        Assert.AreEqual(1, source.EnumerationCount);
        Assert.IsTrue(source.EnumerationCompleted);
    }

    [Test]
    public void EnumeratePartially_SourceIsEnumeratedPartially()
    {
        var source = new TestEnumerable<int>(new[] { 1, 2 });
        var sut = Buffer.Create(source);

        Assert.AreEqual(1, sut.First());

        Assert.IsFalse(source.EnumerationCompleted);
    }

    [Test]
    public void Index_BeforeStart_ThrowsArgumentOutOfRangeException()
    {
        var source = new TestEnumerable<int>(new[] { 1 });
        var sut = Buffer.Create(source);

        Assert.Throws<ArgumentOutOfRangeException>(() => { var r = sut[-1]; });

        Assert.AreEqual(0, source.EnumerationCount);
    }

    [Test]
    public void Index_BeforeEnd_SourceIsEnumeratedPartially()
    {
        var source = new TestEnumerable<int>(new[] { 1, 2 });
        var sut = Buffer.Create(source);

        Assert.AreEqual(1, sut[0]);

        Assert.IsFalse(source.EnumerationCompleted);
    }

    [Test]
    public void Index_PastEnd_ThrowsArgumentOutOfRangeException()
    {
        var source = new TestEnumerable<int>(new[] { 1 });
        var sut = Buffer.Create(source);

        Assert.Throws<ArgumentOutOfRangeException>(() => { var r = sut[1]; });
        Assert.IsTrue(source.EnumerationCompleted);
    }

    [Test]
    public void Count_ReturnsLengthOfSource()
    {
        var source = new TestEnumerable<int>(new[] { 1, 2, 3 });
        var sut = Buffer.Create(source);

        var result = sut.Count;

        Assert.AreEqual(3, result);
        Assert.IsTrue(source.EnumerationCompleted);
    }
}


text:
CREATE TABLE java_vacancy(
    id serial PRIMARY KEY,
    name VARCHAR (1000),
    description VARCHAR (160),
    vacancy_reference VARCHAR (300),
    create_date TIMESTAMP
    );


text:
CREATE PROCEDURE [auth].[auth_ApiUsers_Update]
	@Id bigint,
	@Username varchar(2048),
	@PasswordHash varchar(max),
	@PasswordSalt varchar(max),
	@TokenExpireTimeMinutes int = null,
	@UpdatedByUsername varchar(2048) = null,
	@UpdatedByClientId varchar(32) = null,
	@FirstName nvarchar(256) = null,
	@LastName nvarchar(256) = null,
	@DisplayName nvarchar(512) = null
AS
begin
	declare @UpdatedByUserId int
	declare @UpdatedByClientIId int

	if @UpdatedByUsername is not null
		select @UpdatedByUserId=[Id] from [ApiUsers] where [Username]=@UpdatedByUsername

	if @UpdatedByClientId is not null
		select @UpdatedByClientIId=[Id] from [ApiClients] where [ClientId]=@UpdatedByClientId

	update [ApiUsers] set [Username]=@Username, [PasswordHash]=@PasswordHash, [PasswordSalt]=@PasswordSalt,[TokenExpireTimeMinutes]=@TokenExpireTimeMinutes,
			[UpdatedByClientId]=@UpdatedByClientIId, [UpdatedByUserId]=@UpdatedByUserId, [UpdatedDate]=getdate(), [FirstName]=@FirstName, [LastName]=@LastName, [DisplayName]=@DisplayName
	where [SystemId] = @Id
end


text:
import { Component, OnInit } from 'angular2/core';

import { TechDetailService } from './tech-detail.service';
import { Logger } from '../blocks/logger.service.ts';
import { Tech } from './tech';

@Component({
    selector: 'tech-list',
    styles: [`
        h2 {
            margin-left: 20px;
            font-size: 24px;
            font-weight: 400;
        }
    `],
    template: require('./tech-list.component.html'),
    directives: [],
    providers: [TechDetailService, Logger]
})
export class TechListComponent implements OnInit {
    constructor(private _service: TechDetailService, private _logger: Logger) { }
    technologies: Tech[];
    ngOnInit() {
        this._service.getTech()
            .then(technologies => this.technologies = technologies)
            .catch(error => this._logger.error(error));
    }
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/api/backend.proto

package com.google.api;

public final class BackendProto {
  private BackendProto() {}

  public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}

  public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
    registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
  }

  static final com.google.protobuf.Descriptors.Descriptor
      internal_static_google_api_Backend_descriptor;
  static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_api_Backend_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
      internal_static_google_api_BackendRule_descriptor;
  static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_api_BackendRule_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
    return descriptor;
  }

  private static com.google.protobuf.Descriptors.FileDescriptor descriptor;

  static {
    java.lang.String[] descriptorData = {
      "\n\030google/api/backend.proto\022\ngoogle.api\"1"
          + "\n\007Backend\022&\n\005rules\030\001 \003(\0132\027.google.api.Ba"
          + "ckendRule\"\366\002\n\013BackendRule\022\020\n\010selector\030\001 "
          + "\001(\t\022\017\n\007address\030\002 \001(\t\022\020\n\010deadline\030\003 \001(\001\022\030"
          + "\n\014min_deadline\030\004 \001(\001B\002\030\001\022\032\n\022operation_de"
          + "adline\030\005 \001(\001\022A\n\020path_translation\030\006 \001(\0162\'"
          + ".google.api.BackendRule.PathTranslation\022"
          + "\026\n\014jwt_audience\030\007 \001(\tH\000\022\026\n\014disable_auth\030"
          + "\010 \001(\010H\000\022\020\n\010protocol\030\t \001(\t\"e\n\017PathTransla"
          + "tion\022 \n\034PATH_TRANSLATION_UNSPECIFIED\020\000\022\024"
          + "\n\020CONSTANT_ADDRESS\020\001\022\032\n\026APPEND_PATH_TO_A"
          + "DDRESS\020\002B\020\n\016authenticationBn\n\016com.google"
          + ".apiB\014BackendProtoP\001ZEgoogle.golang.org/"
          + "genproto/googleapis/api/serviceconfig;se"
          + "rviceconfig\242\002\004GAPIb\006proto3"
    };
    descriptor =
        com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
            descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {});
    internal_static_google_api_Backend_descriptor = getDescriptor().getMessageTypes().get(0);
    internal_static_google_api_Backend_fieldAccessorTable =
        new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
            internal_static_google_api_Backend_descriptor,
            new java.lang.String[] {
              "Rules",
            });
    internal_static_google_api_BackendRule_descriptor = getDescriptor().getMessageTypes().get(1);
    internal_static_google_api_BackendRule_fieldAccessorTable =
        new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
            internal_static_google_api_BackendRule_descriptor,
            new java.lang.String[] {
              "Selector",
              "Address",
              "Deadline",
              "MinDeadline",
              "OperationDeadline",
              "PathTranslation",
              "JwtAudience",
              "DisableAuth",
              "Protocol",
              "Authentication",
            });
  }

  // @@protoc_insertion_point(outer_class_scope)
}


text:
This library allows you to insert in any html element on page music player like a soundcloud widget.
It uses [soundcloud-audio](https://www.npmjs.com/package/soundcloud-audio) for fetching and playing tracks from [soundcloud](https://soundcloud.com).

## Installation
```
npm install soundcloud-like-player --save
```
## Usage examples
#### Basic usage
```
import SoundCloudLikePlayer from 'soundcloud-like-player';

let player = new SoundCloudLikePlayer({
    container: document.getElementById('example'),
    clientId: 'cf92370f6c9691fab24bdf6791b57d61',
    redirectUri: 'http://localhost:3001/callback.html',
    autoplay: true
});
player.resolve('http://soundcloud.com/jxnblk/sets/yello');
```
#### Tracks search
```
player.search({q: 'buskers', limit: 20, offset: 10})
```
see https://developers.soundcloud.com/docs/api/guide#search for more search options

**NOTE You should use your correct clientId and redirectUri params for features, requiring authentication (e.g. like button).
See https://developers.soundcloud.com/docs/api/sdks#authentication for details.**
## API
Coming soon...


text:
package com.gemstone.gemfire.internal.cache.persistence.soplog;

import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.nio.ByteBuffer;
import java.util.EnumMap;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.gemstone.gemfire.internal.cache.persistence.soplog.AppendLog.AppendLogWriter;
import com.gemstone.gemfire.internal.util.LogService;

public class RecoverableSortedOplogSet extends AbstractSortedReader implements SortedOplogSet {
  private final ComponentLogWriter log;

  private final SortedOplogSet sos;
  private final long bufferSize;

  private final long maxBufferMemory;

  private final Lock rollLock;
  private AtomicReference<AppendLogWriter> writer;

  public RecoverableSortedOplogSet(SortedOplogSet sos, long bufferSize, double memLimit) throws IOException {
    this.sos = sos;
    this.bufferSize = bufferSize;

    log = ComponentLogWriter.getSoplogLogWriter(sos.getFactory().getConfiguration().getName(), LogService.logger());

    rollLock = new ReentrantLock();
    writer = new AtomicReference<AppendLogWriter>(AppendLog.create(nextLogFile()));

    maxBufferMemory = Math.round(memLimit * ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax());
  }

  @Override
  public boolean mightContain(byte[] key) throws IOException {
    return sos.mightContain(key);
  }

  @Override
  public ByteBuffer read(byte[] key) throws IOException {
    return sos.read(key);
  }

  @Override
  public SortedIterator<ByteBuffer> scan(byte[] from, boolean fromInclusive, byte[] to, boolean toInclusive) throws IOException {
    return sos.scan(from, fromInclusive, to, toInclusive);
  }

  @Override
  public SortedIterator<ByteBuffer> scan(
      byte[] from,
      boolean fromInclusive,
      byte[] to,
      boolean toInclusive,
      boolean ascending,
      MetadataFilter filter) throws IOException {
    return sos.scan(from, fromInclusive, to, toInclusive, ascending, filter);
  }

  @Override
  public SerializedComparator getComparator() {
    return sos.getComparator();
  }

  @Override
  public SortedOplogFactory getFactory() {
    return sos.getFactory();
  }

  @Override
  public SortedStatistics getStatistics() throws IOException {
    return sos.getStatistics();
  }

  @Override
  public void close() throws IOException {
    rollLock.lock();
    try {
      writer.get().close();
      writer.set(null);
      sos.close();
    } finally {
      rollLock.unlock();
    }
  }

  @Override
  public void put(byte[] key, byte[] value) throws IOException {
    throttle();
    if (sos.bufferSize() > bufferSize) {
      roll(false);
    }

    writer.get().append(key, value);
    sos.put(key, value);
  }

  @Override
  public long bufferSize() {
    return sos.bufferSize();
  }

  @Override
  public long unflushedSize() {
    return sos.unflushedSize();
  }

  @Override
  public void flush(EnumMap<Metadata, byte[]> metadata, FlushHandler handler) throws IOException {
    roll(true);
  }

  @Override
  public void flushAndClose(EnumMap<Metadata, byte[]> metadata) throws IOException {
    throw new RuntimeException("Not implemented");
  }

  @Override
  public Compactor getCompactor() {
    return sos.getCompactor();
  }

  @Override
  public void clear() throws IOException {
    rollLock.lock();
    try {
      roll(true);
      sos.clear();
    } finally {
      rollLock.unlock();
    }
  }

  @Override
  public void destroy() throws IOException {
    roll(true);
    sos.destroy();
  }

  @Override
  public boolean isClosed() {
    return sos.isClosed();
  }

  private void throttle() {
    int n = 0;
    while (sos.bufferSize() + sos.unflushedSize() > maxBufferMemory) {
      try {
        Thread.sleep(1 << n++);

      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        break;
      }
    }
  }

  private void roll(boolean wait) throws IOException {
    boolean locked = true;
    if (wait) {
      rollLock.lock();
    } else {
      locked = rollLock.tryLock();
    }

    if (locked) {
      try {
        AppendLogWriter next = AppendLog.create(nextLogFile());
        final AppendLogWriter old = writer.getAndSet(next);
        old.close();

        if (log.fineEnabled()) {
          log.fine(String.format("Rolling from %s to %s", old.getFile(), next.getFile()));
        }

        sos.flush(null, new FlushHandler() {
          @Override
          public void complete() {
            old.getFile().delete();
          }

          @Override
          public void error(Throwable t) {
          }
        });
      } finally {
        rollLock.unlock();
      }
    }
  }

  private File nextLogFile() {
    return new File(sos.getFactory().getConfiguration().getName()
        + "-" + UUID.randomUUID().toString() + ".aolog");
  }
}


text:
class CDataSourceControl;
class CDataBoundProperty;

// CCmdTarget
	class COleControlContainer;
	class COleControlSite;

class COccManager;
struct _AFX_OCC_DIALOG_INFO;

#define DISPID_DATASOURCE   0x80010001
#define DISPID_DATAFIELD    0x80010002

class COleControlSiteFactory;
__declspec(selectany) extern const CLSID CLSID_WinFormsControl =
{0xb7e7a666,0xd623,0x457f,{0xa3,0x0a,0x6a,0x49,0xa3,0xe5,0xb4,0x70}};
/////////////////////////////////////////////////////////////////////////////
// Control site factory interface - allow instantiation of different control sites

class IControlSiteFactory
{
public:
		virtual ~IControlSiteFactory() {}
		virtual COleControlSite* CreateSite(COleControlContainer* pCtrlCont,const CControlCreationInfo& creationInfo) = 0;
};

/////////////////////////////////////////////////////////////////////////////
// Control site factory collection manager class

class CControlSiteFactoryMgr : public CNoTrackObject {
public:
	CControlSiteFactoryMgr();
	virtual ~CControlSiteFactoryMgr();
	BOOL RegisterSiteFactory(IControlSiteFactory* pFactory);
	BOOL UnregisterSiteFactory(IControlSiteFactory* pFactory);
	COleControlSite* CreateSite(COleControlContainer* pCtrlCont,const CControlCreationInfo& creationInfo);
protected:
	CList <IControlSiteFactory*,IControlSiteFactory*> m_lstFactory;
	COleControlSiteFactory* m_pOleControlSiteDefaultFactory;
};

BOOL AFXAPI AfxRegisterSiteFactory(IControlSiteFactory* pFactory);
BOOL AFXAPI AfxUnregisterSiteFactory(IControlSiteFactory* pFactory);

class CControlCreationInfo {
public:
	CControlCreationInfo();
	enum HandleKind { ReflectionType,ControlInstance,NullHandle };
	BOOL IsManaged() const;
	HandleKind m_hk;
	intptr_t   m_nHandle;

	CLSID m_clsid;
};

/////////////////////////////////////////////////////////////////////////////
// Control containment helper functions

DLGTEMPLATE* _AfxSplitDialogTemplate(const DLGTEMPLATE* pTemplate,
	CMapWordToPtr* pOleItemMap);

void _AfxZOrderOleControls(CWnd* pWnd, CMapWordToPtr* pOleItemMap);

/////////////////////////////////////////////////////////////////////////////
// COleControlContainer

class COleControlContainer : public CCmdTarget
{
public:
// Constructor
	explicit COleControlContainer(CWnd*  pWnd);

// Operations
	virtual void BroadcastAmbientPropertyChange(DISPID dispid);
	BOOL CreateControl(CWnd* pWndCtrl, REFCLSID clsid,
		LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, UINT nID,
		CFile* pPersist=NULL, BOOL bStorage=FALSE, BSTR bstrLicKey=NULL,
		COleControlSite** ppNewSite=NULL);
   // Overload to allow creation of default-sized controls
	BOOL CreateControl(CWnd* pWndCtrl, REFCLSID clsid,
		LPCTSTR lpszWindowName, DWORD dwStyle, const POINT* ppt,
	  const SIZE* psize, UINT nID, CFile* pPersist=NULL, BOOL bStorage=FALSE,
	  BSTR bstrLicKey=NULL, COleControlSite** ppNewSite=NULL);
	//Overload to create managed controls
	BOOL CreateControl(CWnd* pWndCtrl,const CControlCreationInfo& creationInfo,
			DWORD dwStyle, const POINT* ppt, const SIZE* psize,UINT nID);

	BOOL CreateControlCommon(CWnd* pWndCtrl, REFCLSID clsid,const CControlCreationInfo& creationInfo,
			LPCTSTR lpszWindowName, DWORD dwStyle, const POINT* ppt, const SIZE* psize,
		   UINT nID, CFile* pPersist=NULL, BOOL bStorage=FALSE, BSTR bstrLicKey=NULL, COleControlSite** ppNewSite=NULL);

	virtual COleControlSite* FindItem(UINT nID) const;
	virtual BOOL GetAmbientProp(COleControlSite* pSite, DISPID dispid,
		VARIANT* pvarResult);
	void CreateOleFont(CFont* pFont);
	void FreezeAllEvents(BOOL bFreeze);
	virtual void ScrollChildren(int dx, int dy);
	virtual void OnUIActivate(COleControlSite* pSite);
	virtual void OnUIDeactivate(COleControlSite* pSite);

	virtual void CheckDlgButton(int nIDButton, UINT nCheck);
	virtual void CheckRadioButton(int nIDFirstButton, int nIDLastButton,
		int nIDCheckButton);
	virtual CWnd* GetDlgItem(int nID) const;
	virtual void GetDlgItem(int nID, HWND* phWnd) const;
	virtual UINT GetDlgItemInt(int nID, BOOL* lpTrans, BOOL bSigned) const;
	virtual int GetDlgItemText(__in int nID, __out_ecount_part(nMaxCount, return + 1) __out_z LPTSTR lpStr, __in int nMaxCount) const;
	virtual LRESULT SendDlgItemMessage(int nID, UINT message, WPARAM wParam,
		LPARAM lParam);
	virtual void SetDlgItemInt(int nID, UINT nValue, BOOL bSigned);
	virtual void SetDlgItemText(int nID, LPCTSTR lpszString);
	virtual UINT IsDlgButtonChecked(int nIDButton) const;

   virtual BOOL HandleSetFocus();
   virtual BOOL HandleWindowlessMessage(UINT message, WPARAM wParam,
	  LPARAM lParam, LRESULT* plResult );
   virtual BOOL OnPaint(CDC* pDC);
#ifndef _AFXDLL
	virtual void AttachControlSite(CWnd* pWnd, UINT nIDC = 0);
#else
	void AttachControlSite(CWnd* pWnd, UINT nIDC = 0);
#endif
	virtual BOOL FillListSitesOrWnds(_AFX_OCC_DIALOG_INFO* pOccDlgInfo);
// Attributes
	CWnd* m_pWnd;
	CMapPtrToPtr m_siteMap;
	CTypedPtrList< CPtrList, COleControlSiteOrWnd* > m_listSitesOrWnds;
	COLORREF m_crBack;
	COLORREF m_crFore;
	LPFONTDISP m_pOleFont;
	COleControlSite* m_pSiteUIActive;
	COleControlSite* m_pSiteCapture;
	COleControlSite* m_pSiteFocus;
	int m_nWindowlessControls;

// Implementation
public:
	virtual ~COleControlContainer();

public:
	// Interface maps
	BEGIN_INTERFACE_PART(OleIPFrame, IOleInPlaceFrame)
		INIT_INTERFACE_PART(COleControlContainer, OleIPFrame)
		STDMETHOD(GetWindow)(HWND*);
		STDMETHOD(ContextSensitiveHelp)(BOOL);
		STDMETHOD(GetBorder)(LPRECT);
		STDMETHOD(RequestBorderSpace)(LPCBORDERWIDTHS);
		STDMETHOD(SetBorderSpace)(LPCBORDERWIDTHS);
		STDMETHOD(SetActiveObject)(LPOLEINPLACEACTIVEOBJECT, LPCOLESTR);
		STDMETHOD(InsertMenus)(HMENU, LPOLEMENUGROUPWIDTHS);
		STDMETHOD(SetMenu)(HMENU, HOLEMENU, HWND);
		STDMETHOD(RemoveMenus)(HMENU);
		STDMETHOD(SetStatusText)(LPCOLESTR);
		STDMETHOD(EnableModeless)(BOOL);
		STDMETHOD(TranslateAccelerator)(LPMSG, WORD);
	END_INTERFACE_PART(OleIPFrame)

	BEGIN_INTERFACE_PART(OleContainer, IOleContainer)
		INIT_INTERFACE_PART(COleControlContainer, OleContainer)
		STDMETHOD(ParseDisplayName)(LPBINDCTX, LPOLESTR, ULONG*, LPMONIKER*);
		STDMETHOD(EnumObjects)(DWORD, LPENUMUNKNOWN*);
		STDMETHOD(LockContainer)(BOOL);
	END_INTERFACE_PART(OleContainer)

	DECLARE_INTERFACE_MAP()
	DECLARE_DISPATCH_MAP()
};

/////////////////////////////////////////////////////////////////////////////
// COleControlSite

#define VT_MFCFORCEPUTREF   0x8000  // force DISPATCH_PROPERTYPUTREF

class COleControlSite : public CCmdTarget
{
public:
// Constructor
	explicit COleControlSite(COleControlContainer* pCtrlCont);

// Operations
	virtual HRESULT CreateControl(CWnd* pWndCtrl, REFCLSID clsid,
		LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, UINT nID,
		CFile* pPersist=NULL, BOOL bStorage=FALSE, BSTR bstrLicKey=NULL);
   // Overload to allow creation of default-sized controls
	virtual HRESULT CreateControl(CWnd* pWndCtrl, REFCLSID clsid,
		LPCTSTR lpszWindowName, DWORD dwStyle, const POINT* ppt,
	  const SIZE* psize, UINT nID, CFile* pPersist=NULL, BOOL bStorage=FALSE,
	  BSTR bstrLicKey=NULL);

	HRESULT CreateControl(CWnd* pWndCtrl, const CControlCreationInfo& creationInfo,
			 DWORD dwStyle, const POINT* ppt, const SIZE* psize,UINT nID);

	virtual BOOL DestroyControl();
	BOOL GetEventIID(IID* piid);
	virtual HRESULT DoVerb(LONG nVerb, LPMSG lpMsg = NULL);
	BOOL IsDefaultButton();
	DWORD GetDefBtnCode();
	void SetDefaultButton(BOOL bDefault);
	void FreezeEvents(BOOL bFreeze);

	virtual void InvokeHelperV(DISPID dwDispID, WORD wFlags, VARTYPE vtRet,
		void* pvRet, const BYTE* pbParamInfo, va_list argList);
	virtual void SetPropertyV(DISPID dwDispID, VARTYPE vtProp, va_list argList);
	virtual void AFX_CDECL InvokeHelper(DISPID dwDispID, WORD wFlags, VARTYPE vtRet,
		void* pvRet, const BYTE* pbParamInfo, ...);
	virtual void GetProperty(DISPID dwDispID, VARTYPE vtProp, void* pvProp) const;
	virtual void AFX_CDECL SetProperty(DISPID dwDispID, VARTYPE vtProp, ...);
	virtual BOOL AFX_CDECL SafeSetProperty(DISPID dwDispID, VARTYPE vtProp, ...);

	virtual DWORD GetStyle() const;
	virtual DWORD GetExStyle() const;
	virtual BOOL ModifyStyle(DWORD dwRemove, DWORD dwAdd, UINT nFlags);
	virtual BOOL ModifyStyleEx(DWORD dwRemove, DWORD dwAdd, UINT nFlags);
	virtual void SetWindowText(LPCTSTR lpszString);
	virtual void GetWindowText(CString& str) const;
	virtual int GetDlgCtrlID() const;
	virtual int SetDlgCtrlID(int nID);
	virtual void MoveWindow(int x, int y, int nWidth, int nHeight);
	virtual BOOL SetWindowPos(const CWnd* pWndInsertAfter, int x, int y,
		int cx, int cy, UINT nFlags);
	virtual BOOL ShowWindow(int nCmdShow);
	virtual BOOL IsWindowEnabled() const;
	virtual BOOL EnableWindow(BOOL bEnable);
	virtual CWnd* SetFocus();
	virtual CWnd* SetFocus(LPMSG lpmsg);
	virtual void EnableDSC();
	virtual void BindDefaultProperty(DISPID dwDispID, VARTYPE vtProp, LPCTSTR szFieldName, CWnd* pDSCWnd);
	virtual void BindProperty(DISPID dwDispId, CWnd* pWndDSC);

// Overridables
	virtual BOOL QuickActivate();

// Attributes
	COleControlContainer* m_pCtrlCont;
	HWND m_hWnd;
	CWnd* m_pWndCtrl;
	UINT m_nID;
	CRect m_rect;
	IID m_iidEvents;
	LPOLEOBJECT m_pObject;
	LPOLEINPLACEOBJECT m_pInPlaceObject;
	LPOLEINPLACEACTIVEOBJECT m_pActiveObject;
	IOleInPlaceObjectWindowless* m_pWindowlessObject;
	DWORD m_dwEventSink;
	DWORD m_dwPropNotifySink;
	DWORD m_dwStyleMask;
	DWORD m_dwStyle;
	DWORD m_dwMiscStatus;
	BOOL m_bIsWindowless;
	CONTROLINFO m_ctlInfo;

protected:
	void GetControlInfo();

	virtual HRESULT CreateControlCommon(CWnd* pWndCtrl, REFCLSID clsid,const CControlCreationInfo& creationInfo,
		LPCTSTR lpszWindowName, DWORD dwStyle, const POINT* ppt, const SIZE* psize, UINT nID,
		CFile* pPersist, BOOL bStorage, BSTR bstrLicKey);

// Implementation
public:
	~COleControlSite();

	BOOL IsMatchingMnemonic(LPMSG lpMsg);
	void SendMnemonic(LPMSG lpMsg);

	void AttachWindow();
	void DetachWindow();
protected:
	BOOL SetExtent();

	virtual HRESULT CreateOrLoad(const CControlCreationInfo& creationInfo);
	virtual	HRESULT CreateOrLoad(REFCLSID clsid, CFile* pPersist, BOOL bStorage,
		BSTR bstrLicKey);

	DWORD ConnectSink(REFIID iid, LPUNKNOWN punkSink);
	void DisconnectSink(REFIID iid, DWORD dwCookie);

	BOOL OnEvent(AFX_EVENT* pEvent);
	HRESULT GetCursor(DISPID dispid, LPUNKNOWN* ppcursorOut, LPVOID *ppcidOut);

public:
	// Databound control stuff
	BOOL m_bIgnoreNotify;
	DWORD m_dwNotifyDBEvents; // INotifyDBEvents sink cookie
	CDataSourceControl* m_pDataSourceControl;
	CDataBoundProperty* m_pBindings;
	union {
		COleControlSite *m_pDSCSite;
		WORD m_ctlidRowSource;
	};
	DISPID m_defdispid;
	UINT m_dwType;
	CString m_strDataField;
	BOOL m_bIsDirty;
	VARIANT m_varResult;

protected:
	COleDispatchDriver m_dispDriver;
   CDC* m_pDC;

public:
// Interface maps
	BEGIN_INTERFACE_PART(OleClientSite, IOleClientSite)
		INIT_INTERFACE_PART(COleControlSite, OleClientSite)
		STDMETHOD(SaveObject)();
		STDMETHOD(GetMoniker)(DWORD, DWORD, LPMONIKER*);
		STDMETHOD(GetContainer)(LPOLECONTAINER*);
		STDMETHOD(ShowObject)();
		STDMETHOD(OnShowWindow)(BOOL);
		STDMETHOD(RequestNewObjectLayout)();
	END_INTERFACE_PART(OleClientSite)

	BEGIN_INTERFACE_PART(OleIPSite, IOleInPlaceSiteWindowless)
		INIT_INTERFACE_PART(COleControlSite, OleIPSite)
		STDMETHOD(GetWindow)(HWND*);
		STDMETHOD(ContextSensitiveHelp)(BOOL);

		STDMETHOD(CanInPlaceActivate)();
		STDMETHOD(OnInPlaceActivate)();
		STDMETHOD(OnUIActivate)();
		STDMETHOD(GetWindowContext)(LPOLEINPLACEFRAME*,
			LPOLEINPLACEUIWINDOW*, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO);
		STDMETHOD(Scroll)(SIZE);
		STDMETHOD(OnUIDeactivate)(BOOL);
		STDMETHOD(OnInPlaceDeactivate)();
		STDMETHOD(DiscardUndoState)();
		STDMETHOD(DeactivateAndUndo)();
		STDMETHOD(OnPosRectChange)(LPCRECT);

	  STDMETHOD(OnInPlaceActivateEx)( BOOL* ptNoRedraw, DWORD dwFlags );
	  STDMETHOD(OnInPlaceDeactivateEx)( BOOL tNoRedraw );
	  STDMETHOD(RequestUIActivate)();

	  STDMETHOD(AdjustRect)( LPRECT prect );
	  STDMETHOD(CanWindowlessActivate)();
	  STDMETHOD(GetCapture)();
	  STDMETHOD(GetDC)( LPCRECT prect, DWORD dwFlags, HDC* phDC );
	  STDMETHOD(GetFocus)();
	  STDMETHOD(InvalidateRect)( LPCRECT prect, BOOL tErase );
	  STDMETHOD(InvalidateRgn)( HRGN hRgn, BOOL tErase );
	  STDMETHOD(OnDefWindowMessage)( UINT nMessage, WPARAM wParam,
		 LPARAM lParam, LRESULT* plResult );
	  STDMETHOD(ReleaseDC)( HDC hDC );
	  STDMETHOD(ScrollRect)( int dx, int dy, LPCRECT prectScroll,
		 LPCRECT prectClip );
	  STDMETHOD(SetCapture)( BOOL tCapture );
	  STDMETHOD(SetFocus)( BOOL tFocus );
   END_INTERFACE_PART(OleIPSite)

	BEGIN_INTERFACE_PART(OleControlSite, IOleControlSite)
		INIT_INTERFACE_PART(COleControlSite, OleControlSite)
		STDMETHOD(OnControlInfoChanged)();
		STDMETHOD(LockInPlaceActive)(BOOL fLock);
		STDMETHOD(GetExtendedControl)(LPDISPATCH* ppDisp);
		STDMETHOD(TransformCoords)(POINTL* lpptlHimetric,
			POINTF* lpptfContainer, DWORD flags);
		STDMETHOD(TranslateAccelerator)(LPMSG lpMsg, DWORD grfModifiers);
		STDMETHOD(OnFocus)(BOOL fGotFocus);
		STDMETHOD(ShowPropertyFrame)();
	END_INTERFACE_PART(OleControlSite)

	BEGIN_INTERFACE_PART(AmbientProps, IDispatch)
		INIT_INTERFACE_PART(COleControlSite, AmbientProps)
		STDMETHOD(GetTypeInfoCount)(unsigned int*);
		STDMETHOD(GetTypeInfo)(unsigned int, LCID, ITypeInfo**);
		STDMETHOD(GetIDsOfNames)(REFIID, LPOLESTR*, unsigned int, LCID, DISPID*);
		STDMETHOD(Invoke)(DISPID, REFIID, LCID, unsigned short, DISPPARAMS*,
						  VARIANT*, EXCEPINFO*, unsigned int*);
	END_INTERFACE_PART(AmbientProps)

	BEGIN_INTERFACE_PART(PropertyNotifySink, IPropertyNotifySink)
		INIT_INTERFACE_PART(COleControlSite, PropertyNotifySink)
		STDMETHOD(OnChanged)(DISPID dispid);
		STDMETHOD(OnRequestEdit)(DISPID dispid);
	END_INTERFACE_PART(PropertyNotifySink)

	BEGIN_INTERFACE_PART(EventSink, IDispatch)
		INIT_INTERFACE_PART(COleControlSite, EventSink)
		STDMETHOD(GetTypeInfoCount)(unsigned int*);
		STDMETHOD(GetTypeInfo)(unsigned int, LCID, ITypeInfo**);
		STDMETHOD(GetIDsOfNames)(REFIID, LPOLESTR*, unsigned int, LCID, DISPID*);
		STDMETHOD(Invoke)(DISPID, REFIID, LCID, unsigned short, DISPPARAMS*,
						  VARIANT*, EXCEPINFO*, unsigned int*);
	END_INTERFACE_PART(EventSink)

	BEGIN_INTERFACE_PART(BoundObjectSite, IBoundObjectSite)
		STDMETHOD(GetCursor)(DISPID dispid, LPLPCURSOR ppcursorOut, LPVOID *ppcidOut);
	END_INTERFACE_PART(BoundObjectSite)

	BEGIN_INTERFACE_PART(NotifyDBEvents, INotifyDBEvents)
		STDMETHOD(OKToDo)(DWORD dwEventWhat, ULONG cReasons, DBNOTIFYREASON rgReasons[]);
		STDMETHOD(Cancelled)(DWORD dwEventWhat, ULONG cReasons, DBNOTIFYREASON rgReasons[]);
		STDMETHOD(SyncBefore)(DWORD dwEventWhat, ULONG cReasons, DBNOTIFYREASON rgReasons[]);
		STDMETHOD(AboutToDo)(DWORD dwEventWhat, ULONG cReasons, DBNOTIFYREASON rgReasons[]);
		STDMETHOD(FailedToDo)(DWORD dwEventWhat, ULONG cReasons, DBNOTIFYREASON rgReasons[]);
		STDMETHOD(SyncAfter)(DWORD dwEventWhat, ULONG cReasons, DBNOTIFYREASON rgReasons[]);
		STDMETHOD(DidEvent)(DWORD dwEventWhat, ULONG cReasons, DBNOTIFYREASON rgReasons[]);

		// Not part of i/f - just a helper
		HRESULT FireEvent(DWORD dwEventWhat, ULONG cReasons,
			DBNOTIFYREASON rgReasons[], DSCSTATE nState);
	END_INTERFACE_PART(NotifyDBEvents)

	BEGIN_INTERFACE_PART(RowsetNotify, IRowsetNotify)
		STDMETHOD(OnFieldChange)(IRowset* pRowset, HROW hRow, DBORDINAL cColumns, DBORDINAL rgColumns[], DBREASON eReason, DBEVENTPHASE ePhase, BOOL fCantDeny);
		STDMETHOD(OnRowChange)(IRowset* pRowset, DBCOUNTITEM cRows, const HROW rghRows[], DBREASON eReason, DBEVENTPHASE ePhase, BOOL fCantDeny);
		STDMETHOD(OnRowsetChange)(IRowset* pRowset, DBREASON eReason, DBEVENTPHASE ePhase, BOOL fCantDeny);
	END_INTERFACE_PART(RowsetNotify)

	DECLARE_INTERFACE_MAP()
};

/////////////////////////////////////////////////////////////////////////////
// COleControlSiteOrWnd (helper)
struct COleControlSiteOrWnd
{
	COleControlSiteOrWnd();
	COleControlSiteOrWnd(COleControlSite *pSite);
	COleControlSiteOrWnd(HWND hWnd, BOOL bAutoRadioButton);
	~COleControlSiteOrWnd();

	DWORD GetStyle() const;

	HWND m_hWnd;
	COleControlSite *m_pSite;
	BOOL m_bAutoRadioButton;
};

COleControlSiteOrWnd* AFXAPI _AfxFindSiteOrWnd(CWnd *pWndDlg, CWnd *pWnd);

/////////////////////////////////////////////////////////////////////////////
// OLE control container manager

class COccManager : public CNoTrackObject
{
// Operations
public:
	// Event handling
	virtual BOOL OnEvent(CCmdTarget* pCmdTarget, UINT idCtrl, AFX_EVENT* pEvent,
		AFX_CMDHANDLERINFO* pHandlerInfo);

	// Internal object creation
	virtual COleControlContainer* CreateContainer(CWnd* pWnd);
	virtual COleControlSite* CreateSite(COleControlContainer* pCtrlCont);
	virtual COleControlSite* CreateSite(COleControlContainer* pCtrlCont,const CControlCreationInfo& creationInfo);

	// Dialog creation
	virtual const DLGTEMPLATE* PreCreateDialog(_AFX_OCC_DIALOG_INFO* pOccDialogInfo,
		const DLGTEMPLATE* pOrigTemplate);
	virtual void PostCreateDialog(_AFX_OCC_DIALOG_INFO* pOccDialogInfo);
	virtual DLGTEMPLATE* SplitDialogTemplate(const DLGTEMPLATE* pTemplate,
		DLGITEMTEMPLATE** ppOleDlgItems);
	virtual BOOL CreateDlgControls(CWnd* pWndParent, LPCTSTR lpszResourceName,
		_AFX_OCC_DIALOG_INFO* pOccDialogInfo);
	virtual BOOL CreateDlgControls(CWnd* pWndParent, void* lpResource,
		_AFX_OCC_DIALOG_INFO* pOccDialogInfo);

	// Dialog manager
	virtual BOOL IsDialogMessage(CWnd* pWndDlg, LPMSG lpMsg);
	static BOOL AFX_CDECL IsLabelControl(CWnd* pWnd);
	static BOOL AFX_CDECL IsLabelControl(COleControlSiteOrWnd* pWnd);
	static BOOL AFX_CDECL IsMatchingMnemonic(CWnd* pWnd, LPMSG lpMsg);
	static BOOL AFX_CDECL IsMatchingMnemonic(COleControlSiteOrWnd* pWnd, LPMSG lpMsg);
	static void AFX_CDECL SetDefaultButton(CWnd* pWnd, BOOL bDefault);
	static DWORD AFX_CDECL GetDefBtnCode(CWnd* pWnd);

// Implementation
protected:
	// Dialog creation
	BOOL CreateDlgControl(CWnd* pWndParent, HWND hwAfter, BOOL bDialogEx,
		LPDLGITEMTEMPLATE pDlgItem, WORD nMsg, BYTE* lpData, DWORD cb, HWND* phWnd);

	// Databinding
	void BindControls(CWnd* pWndParent);

	// Dialog manager
	static void AFX_CDECL UIActivateControl(CWnd* pWndNewFocus);
	static void AFX_CDECL UIDeactivateIfNecessary(CWnd* pWndOldFocus, CWnd* pWndNewFocus);
};

struct _AFX_OCC_DIALOG_INFO
{
	DLGTEMPLATE* m_pNewTemplate;
	DLGITEMTEMPLATE** m_ppOleDlgItems;

	unsigned m_cItems;
	struct ItemInfo
	{
		unsigned nId;
		BOOL bAutoRadioButton;
	};
	ItemInfo *m_pItemInfo;
};

#endif // !_AFX_NO_OCC_SUPPORT
#endif // __AFXOCC_H__


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Spokes Server Test Client</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">


text:
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.Data.Edm.Validation;

namespace Microsoft.Data.Edm.Library.Internal
{
    internal class BadEntityTypeReference : EdmEntityTypeReference, IEdmCheckable
    {
        private readonly IEnumerable<EdmError> errors;

        public BadEntityTypeReference(string qualifiedName, bool isNullable, IEnumerable<EdmError> errors)
            : base(new BadEntityType(qualifiedName, errors), isNullable)
        {
            this.errors = errors;
        }

        public IEnumerable<EdmError> Errors
        {
            get { return this.errors; }
        }

        public override string ToString()
        {
            EdmError error = this.Errors.FirstOrDefault();
            Debug.Assert(error != null, "error != null");
            string prefix = error != null ? error.ErrorCode.ToString() + ":" : "";
            return prefix + this.ToTraceString();
        }
    }
}


text:
#ifndef IDL_WALK_H
#define IDL_WALK_H

#include "c_base.h"
#include "c_typebase.h"
#include "c_iterator.h"

#include "idl_program.h"
#include "idl_tmplExp.h"

void
idl_walkPresetFile(
    const char *fileName);

void
idl_walkPresetModule(
    const char *moduleName);

void
idl_walk(
    c_base base,
    const char *fileName,
    c_iter objects,
    c_bool traceWalk,
    idl_program program);

idl_typeSpec
idl_makeTypeCollection(
    c_collectionType type);

idl_typeSpec
idl_makeTypeSpec(
    c_type type);

void
idl_freeTypeSpec(
    idl_typeSpec typeSpec);

idl_scope
idl_buildScope (
    c_metaObject o);

#endif /* IDL_WALK_H */


text:
import tensorflow as tf
from tensorflow.python.framework import ops
from tensorflow.python.ops import math_ops
from tensorflow.python.training import moving_averages

import tensorlayer as tl
from tensorlayer import logging
from tensorlayer.layers.core import Layer

__all__ = [
    'LocalResponseNorm',
    'BatchNorm',  # FIXME: wthether to keep BatchNorm
    'BatchNorm1d',
    'BatchNorm2d',
    'BatchNorm3d',
    'InstanceNorm',
    'InstanceNorm1d',
    'InstanceNorm2d',
    'InstanceNorm3d',
    'LayerNorm',
    'GroupNorm',
    'SwitchNorm',
]

class LocalResponseNorm(Layer):
    """The :class:`LocalResponseNorm` layer is for Local Response Normalization.
    See ``tf.nn.local_response_normalization`` or ``tf.nn.lrn`` for new TF version.
    The 4-D input tensor is a 3-D array of 1-D vectors (along the last dimension), and each vector is normalized independently.
    Within a given vector, each component is divided by the weighted square-sum of inputs within depth_radius.

    Parameters
    -----------
    depth_radius : int
        Depth radius. 0-D. Half-width of the 1-D normalization window.
    bias : float
        An offset which is usually positive and shall avoid dividing by 0.
    alpha : float
        A scale factor which is usually positive.
    beta : float
        An exponent.
    name : None or str
        A unique layer name.

    """

    def __init__(
        self,
        depth_radius=None,
        bias=None,
        alpha=None,
        beta=None,
        name=None,  #'lrn',
    ):
        # super(LocalResponseNorm, self).__init__(prev_layer=prev_layer, name=name)
        super().__init__(name)
        self.depth_radius = depth_radius
        self.bias = bias
        self.alpha = alpha
        self.beta = beta

        logging.info(
            "LocalResponseNorm %s: depth_radius: %s, bias: %s, alpha: %s, beta: %s" %
            (self.name, str(depth_radius), str(bias), str(alpha), str(beta))
        )

    def build(self, inputs):
        pass

    def forward(self, inputs):
        """
        prev_layer : :class:`Layer`
            The previous layer with a 4D output shape.
        """
        outputs = tf.nn.lrn(inputs, depth_radius=self.depth_radius, bias=self.bias, alpha=self.alpha, beta=self.beta)
        return outputs

def _to_channel_first_bias(b):
    """Reshape [c] to [c, 1, 1]."""
    channel_size = int(b.shape[0])
    new_shape = (channel_size, 1, 1)
    # new_shape = [-1, 1, 1]  # doesn't work with tensorRT
    return tf.reshape(b, new_shape)

def _bias_scale(x, b, data_format):
    """The multiplication counter part of tf.nn.bias_add."""
    if data_format == 'NHWC':
        return x * b
    elif data_format == 'NCHW':
        return x * b
    else:
        raise ValueError('invalid data_format: %s' % data_format)

def _bias_add(x, b, data_format):
    """Alternative implementation of tf.nn.bias_add which is compatiable with tensorRT."""
    if data_format == 'NHWC':
        return tf.add(x, b)
    elif data_format == 'NCHW':
        return tf.add(x, b)
    else:
        raise ValueError('invalid data_format: %s' % data_format)

def _compute_shape(tensors):
    if isinstance(tensors, list):
        shape_mem = [t.get_shape().as_list() for t in tensors]
    else:
        shape_mem = tensors.get_shape().as_list()
    return shape_mem

def batch_normalization(x, mean, variance, offset, scale, variance_epsilon, data_format, name=None):
    """Data Format aware version of tf.nn.batch_normalization."""
    if data_format == 'channels_last':
        mean = tf.reshape(mean, [1] * (len(x.shape) - 1) + [-1])
        variance = tf.reshape(variance, [1] * (len(x.shape) - 1) + [-1])
        offset = tf.reshape(offset, [1] * (len(x.shape) - 1) + [-1])
        scale = tf.reshape(scale, [1] * (len(x.shape) - 1) + [-1])
    elif data_format == 'channels_first':
        mean = tf.reshape(mean, [1] + [-1] + [1] * (len(x.shape) - 2))
        variance = tf.reshape(variance, [1] + [-1] + [1] * (len(x.shape) - 2))
        offset = tf.reshape(offset, [1] + [-1] + [1] * (len(x.shape) - 2))
        scale = tf.reshape(scale, [1] + [-1] + [1] * (len(x.shape) - 2))
    else:
        raise ValueError('invalid data_format: %s' % data_format)

    with ops.name_scope(name, 'batchnorm', [x, mean, variance, scale, offset]):
        inv = math_ops.rsqrt(variance + variance_epsilon)
        if scale is not None:
            inv *= scale

        a = math_ops.cast(inv, x.dtype)
        b = math_ops.cast(offset - mean * inv if offset is not None else -mean * inv, x.dtype)

        # Return a * x + b with customized data_format.
        # Currently TF doesn't have bias_scale, and tensorRT has bug in converting tf.nn.bias_add
        # So we reimplemted them to allow make the model work with tensorRT.
        # See https://github.com/tensorlayer/openpose-plus/issues/75 for more details.
        df = {'channels_first': 'NCHW', 'channels_last': 'NHWC'}
        return _bias_add(_bias_scale(x, a, df[data_format]), b, df[data_format])

class BatchNorm(Layer):
    """
    The :class:`BatchNorm` is a batch normalization layer for both fully-connected and convolution outputs.
    See ``tf.nn.batch_normalization`` and ``tf.nn.moments``.

    Parameters
    ----------
    decay : float
        A decay factor for `ExponentialMovingAverage`.
        Suggest to use a large value for large dataset.
    epsilon : float
        Eplison.
    act : activation function
        The activation function of this layer.
    is_train : boolean
        Is being used for training or inference.
    beta_init : initializer or None
        The initializer for initializing beta, if None, skip beta.
        Usually you should not skip beta unless you know what happened.
    gamma_init : initializer or None
        The initializer for initializing gamma, if None, skip gamma.
        When the batch normalization layer is use instead of 'biases', or the next layer is linear, this can be
        disabled since the scaling can be done by the next layer. see `Inception-ResNet-v2 <https://github.com/tensorflow/models/blob/master/research/slim/nets/inception_resnet_v2.py>`__
    moving_mean_init : initializer or None
        The initializer for initializing moving mean, if None, skip moving mean.
    moving_var_init : initializer or None
        The initializer for initializing moving var, if None, skip moving var.
    num_features: int
        Number of features for input tensor. Useful to build layer if using BatchNorm1d, BatchNorm2d or BatchNorm3d,
        but should be left as None if using BatchNorm. Default None.
    data_format : str
        channels_last 'channel_last' (default) or channels_first.
    name : None or str
        A unique layer name.

    Examples
    ---------
    With TensorLayer

    >>> net = tl.layers.Input([None, 50, 50, 32], name='input')
    >>> net = tl.layers.BatchNorm()(net)

    Notes
    -----
    The :class:`BatchNorm` is universally suitable for 3D/4D/5D input in static model, but should not be used
    in dynamic model where layer is built upon class initialization. So the argument 'num_features' should only be used
    for subclasses :class:`BatchNorm1d`, :class:`BatchNorm2d` and :class:`BatchNorm3d`. All the three subclasses are
    suitable under all kinds of conditions.

    References
    ----------
    - `Source <https://github.com/ry/tensorflow-resnet/blob/master/resnet.py>`__
    - `stackoverflow <http://stackoverflow.com/questions/38312668/how-does-one-do-inference-with-batch-normalization-with-tensor-flow>`__

    """

    def __init__(
        self,
        decay=0.9,
        epsilon=0.00001,
        act=None,
        is_train=False,
        beta_init=tl.initializers.zeros(),
        gamma_init=tl.initializers.random_normal(mean=1.0, stddev=0.002),
        moving_mean_init=tl.initializers.zeros(),
        moving_var_init=tl.initializers.zeros(),
        num_features=None,
        data_format='channels_last',
        name=None,
    ):
        super(BatchNorm, self).__init__(name=name, act=act)
        self.decay = decay
        self.epsilon = epsilon
        self.data_format = data_format
        self.beta_init = beta_init
        self.gamma_init = gamma_init
        self.moving_mean_init = moving_mean_init
        self.moving_var_init = moving_var_init
        self.num_features = num_features

        self.axes = None

        if num_features is not None:
            self.build(None)
            self._built = True

        if self.decay < 0.0 or 1.0 < self.decay:
            raise ValueError("decay should be between 0 to 1")

        logging.info(
            "BatchNorm %s: decay: %f epsilon: %f act: %s is_train: %s" %
            (self.name, decay, epsilon, self.act.__name__ if self.act is not None else 'No Activation', is_train)
        )

    def __repr__(self):
        actstr = self.act.__name__ if self.act is not None else 'No Activation'
        s = ('{classname}(num_features={num_features}, decay={decay}' ', epsilon={epsilon}')
        s += (', ' + actstr)
        if self.name is not None:
            s += ', name="{name}"'
        s += ')'
        return s.format(classname=self.__class__.__name__, **self.__dict__)

    def _get_param_shape(self, inputs_shape):
        if self.data_format == 'channels_last':
            axis = -1
        elif self.data_format == 'channels_first':
            axis = 1
        else:
            raise ValueError('data_format should be either %s or %s' % ('channels_last', 'channels_first'))

        channels = inputs_shape[axis]
        params_shape = [channels]

        return params_shape

    def _check_input_shape(self, inputs):
        inputs_shape = _compute_shape(inputs)
        if len(inputs_shape) <= 1:
            raise ValueError('expected input at least 2D, but got {}D input'.format(inputs.ndim))

    def build(self, inputs_shape):
        params_shape = [self.num_features] if self.num_features is not None else self._get_param_shape(inputs_shape)

        self.beta, self.gamma = None, None
        if self.beta_init:
            self.beta = self._get_weights("beta", shape=params_shape, init=self.beta_init)

        if self.gamma_init:
            self.gamma = self._get_weights("gamma", shape=params_shape, init=self.gamma_init)

        self.moving_mean = self._get_weights(
            "moving_mean", shape=params_shape, init=self.moving_mean_init, trainable=False
        )
        self.moving_var = self._get_weights(
            "moving_var", shape=params_shape, init=self.moving_var_init, trainable=False
        )

    def forward(self, inputs):
        self._check_input_shape(inputs)

        self.channel_axis = len(inputs.shape) - 1 if self.data_format == 'channels_last' else 1
        if self.axes is None:
            self.axes = [i for i in range(len(inputs.shape)) if i != self.channel_axis]

        mean, var = tf.nn.moments(inputs, self.axes, keepdims=False)
        if self.is_train:
            # update moving_mean and moving_var
            self.moving_mean = moving_averages.assign_moving_average(
                self.moving_mean, mean, self.decay, zero_debias=False
            )
            self.moving_var = moving_averages.assign_moving_average(self.moving_var, var, self.decay, zero_debias=False)
            outputs = batch_normalization(inputs, mean, var, self.beta, self.gamma, self.epsilon, self.data_format)
        else:
            outputs = batch_normalization(
                inputs, self.moving_mean, self.moving_var, self.beta, self.gamma, self.epsilon, self.data_format
            )
        if self.act:
            outputs = self.act(outputs)
        return outputs

class BatchNorm1d(BatchNorm):
    """The :class:`BatchNorm1d` applies Batch Normalization over 2D/3D input (a mini-batch of 1D
    inputs (optional) with additional channel dimension), of shape (N, C) or (N, L, C) or (N, C, L).
    See more details in :class:`BatchNorm`.

    Examples
    ---------
    With TensorLayer

    >>> # in static model, no need to specify num_features
    >>> net = tl.layers.Input([None, 50, 32], name='input')
    >>> net = tl.layers.BatchNorm1d()(net)
    >>> # in dynamic model, build by specifying num_features
    >>> conv = tl.layers.Conv1d(32, 5, 1, in_channels=3)
    >>> bn = tl.layers.BatchNorm1d(num_features=32)

    """

    def _check_input_shape(self, inputs):
        inputs_shape = _compute_shape(inputs)
        if len(inputs_shape) != 2 and len(inputs_shape) != 3:
            raise ValueError('expected input to be 2D or 3D, but got {}D input'.format(inputs.ndim))

class BatchNorm2d(BatchNorm):
    """The :class:`BatchNorm2d` applies Batch Normalization over 4D input (a mini-batch of 2D
    inputs with additional channel dimension) of shape (N, H, W, C) or (N, C, H, W).
    See more details in :class:`BatchNorm`.

    Examples
    ---------
    With TensorLayer

    >>> # in static model, no need to specify num_features
    >>> net = tl.layers.Input([None, 50, 50, 32], name='input')
    >>> net = tl.layers.BatchNorm2d()(net)
    >>> # in dynamic model, build by specifying num_features
    >>> conv = tl.layers.Conv2d(32, (5, 5), (1, 1), in_channels=3)
    >>> bn = tl.layers.BatchNorm2d(num_features=32)

    """

    def _check_input_shape(self, inputs):
        inputs_shape = _compute_shape(inputs)
        if len(inputs_shape) != 4:
            raise ValueError('expected input to be 4D, but got {}D input'.format(inputs.ndim))

class BatchNorm3d(BatchNorm):
    """The :class:`BatchNorm3d` applies Batch Normalization over 5D input (a mini-batch of 3D
    inputs with additional channel dimension) with shape (N, D, H, W, C) or (N, C, D, H, W).
    See more details in :class:`BatchNorm`.

    Examples
    ---------
    With TensorLayer

    >>> # in static model, no need to specify num_features
    >>> net = tl.layers.Input([None, 50, 50, 50, 32], name='input')
    >>> net = tl.layers.BatchNorm3d()(net)
    >>> # in dynamic model, build by specifying num_features
    >>> conv = tl.layers.Conv3d(32, (5, 5, 5), (1, 1), in_channels=3)
    >>> bn = tl.layers.BatchNorm3d(num_features=32)

    """

    def _check_input_shape(self, inputs):
        inputs_shape = _compute_shape(inputs)
        if len(inputs_shape) != 5:
            raise ValueError('expected input to be 5D, but got {}D input'.format(inputs.ndim))

class InstanceNorm(Layer):
    """
    The :class:`InstanceNorm` is an instance normalization layer for both fully-connected and convolution outputs.
    See ``tf.nn.batch_normalization`` and  ``tf.nn.moments``.

    Parameters
    -----------
    act : activation function.
        The activation function of this layer.
    epsilon : float
        Eplison.
    beta_init : initializer or None
        The initializer for initializing beta, if None, skip beta.
        Usually you should not skip beta unless you know what happened.
    gamma_init : initializer or None
        The initializer for initializing gamma, if None, skip gamma.
        When the instance normalization layer is use instead of 'biases', or the next layer is linear, this can be
        disabled since the scaling can be done by the next layer. see `Inception-ResNet-v2 <https://github.com/tensorflow/models/blob/master/research/slim/nets/inception_resnet_v2.py>`__
    num_features: int
        Number of features for input tensor. Useful to build layer if using InstanceNorm1d, InstanceNorm2d or InstanceNorm3d,
        but should be left as None if using InstanceNorm. Default None.
    data_format : str
        channels_last 'channel_last' (default) or channels_first.
    name : None or str
        A unique layer name.

    Examples
    ---------
    With TensorLayer

    >>> net = tl.layers.Input([None, 50, 50, 32], name='input')
    >>> net = tl.layers.InstanceNorm()(net)

    Notes
    -----
    The :class:`InstanceNorm` is universally suitable for 3D/4D/5D input in static model, but should not be used
    in dynamic model where layer is built upon class initialization. So the argument 'num_features' should only be used
    for subclasses :class:`InstanceNorm1d`, :class:`InstanceNorm2d` and :class:`InstanceNorm3d`. All the three subclasses are
    suitable under all kinds of conditions.
    """

    def __init__(
        self, act=None, epsilon=0.00001, beta_init=tl.initializers.zeros(),
        gamma_init=tl.initializers.random_normal(mean=1.0, stddev=0.002), num_features=None,
        data_format='channels_last', name=None
    ):
        super(InstanceNorm, self).__init__(name=name, act=act)
        self.epsilon = epsilon
        self.beta_init = beta_init
        self.gamma_init = gamma_init
        self.num_features = num_features
        self.data_format = data_format

        if num_features is not None:
            if not isinstance(self, InstanceNorm1d) and not isinstance(self, InstanceNorm2d) and not isinstance(
                    self, InstanceNorm3d):
                raise ValueError(
                    "Please use InstanceNorm1d or InstanceNorm2d or InstanceNorm3d instead of InstanceNorm "
                    "if you want to specify 'num_features'."
                )
            self.build(None)
            self._built = True

        logging.info(
            "InstanceNorm %s: epsilon: %f act: %s " %
            (self.name, epsilon, self.act.__name__ if self.act is not None else 'No Activation')
        )

    def __repr__(self):
        actstr = self.act.__name__ if self.act is not None else 'No Activation'
        s = '{classname}(num_features=num_features, epsilon={epsilon}' + actstr
        if self.name is not None:
            s += ', name="{name}"'
        s += ')'
        return s.format(classname=self.__class__.__name__, **self.__dict__)

    def _get_param_shape(self, inputs_shape):
        if self.data_format == 'channels_last':
            axis = len(inputs_shape) - 1
        elif self.data_format == 'channels_first':
            axis = 1
        else:
            raise ValueError('data_format should be either %s or %s' % ('channels_last', 'channels_first'))

        channels = inputs_shape[axis]
        params_shape = [1] * len(inputs_shape)
        params_shape[axis] = channels

        axes = [i for i in range(len(inputs_shape)) if i != 0 and i != axis]
        return params_shape, axes

    def build(self, inputs_shape):
        params_shape, self.axes = self._get_param_shape(inputs_shape)

        self.beta, self.gamma = None, None
        if self.beta_init:
            self.beta = self._get_weights("beta", shape=params_shape, init=self.beta_init)

        if self.gamma_init:
            self.gamma = self._get_weights("gamma", shape=params_shape, init=self.gamma_init)

    def forward(self, inputs):
        mean, var = tf.nn.moments(inputs, self.axes, keepdims=True)
        outputs = batch_normalization(inputs, mean, var, self.beta, self.gamma, self.epsilon, self.data_format)
        if self.act:
            outputs = self.act(outputs)
        return outputs

class InstanceNorm1d(InstanceNorm):
    """The :class:`InstanceNorm1d` applies Instance Normalization over 3D input (a mini-instance of 1D
    inputs with additional channel dimension), of shape (N, L, C) or (N, C, L).
    See more details in :class:`InstanceNorm`.

    Examples
    ---------
    With TensorLayer

    >>> # in static model, no need to specify num_features
    >>> net = tl.layers.Input([None, 50, 32], name='input')
    >>> net = tl.layers.InstanceNorm1d()(net)
    >>> # in dynamic model, build by specifying num_features
    >>> conv = tl.layers.Conv1d(32, 5, 1, in_channels=3)
    >>> bn = tl.layers.InstanceNorm1d(num_features=32)

    """

    def _get_param_shape(self, inputs_shape):
        if self.data_format == 'channels_last':
            axis = 2
        elif self.data_format == 'channels_first':
            axis = 1
        else:
            raise ValueError('data_format should be either %s or %s' % ('channels_last', 'channels_first'))

        if self.num_features is None:
            channels = inputs_shape[axis]
        else:
            channels = self.num_features
        params_shape = [1] * 3
        params_shape[axis] = channels

        axes = [i for i in range(3) if i != 0 and i != axis]
        return params_shape, axes

class InstanceNorm2d(InstanceNorm):
    """The :class:`InstanceNorm2d` applies Instance Normalization over 4D input (a mini-instance of 2D
    inputs with additional channel dimension) of shape (N, H, W, C) or (N, C, H, W).
    See more details in :class:`InstanceNorm`.

    Examples
    ---------
    With TensorLayer

    >>> # in static model, no need to specify num_features
    >>> net = tl.layers.Input([None, 50, 50, 32], name='input')
    >>> net = tl.layers.InstanceNorm2d()(net)
    >>> # in dynamic model, build by specifying num_features
    >>> conv = tl.layers.Conv2d(32, (5, 5), (1, 1), in_channels=3)
    >>> bn = tl.layers.InstanceNorm2d(num_features=32)

    """

    def _get_param_shape(self, inputs_shape):
        if self.data_format == 'channels_last':
            axis = 3
        elif self.data_format == 'channels_first':
            axis = 1
        else:
            raise ValueError('data_format should be either %s or %s' % ('channels_last', 'channels_first'))

        if self.num_features is None:
            channels = inputs_shape[axis]
        else:
            channels = self.num_features
        params_shape = [1] * 4
        params_shape[axis] = channels

        axes = [i for i in range(4) if i != 0 and i != axis]
        return params_shape, axes

class InstanceNorm3d(InstanceNorm):
    """The :class:`InstanceNorm3d` applies Instance Normalization over 5D input (a mini-instance of 3D
    inputs with additional channel dimension) with shape (N, D, H, W, C) or (N, C, D, H, W).
    See more details in :class:`InstanceNorm`.

    Examples
    ---------
    With TensorLayer

    >>> # in static model, no need to specify num_features
    >>> net = tl.layers.Input([None, 50, 50, 50, 32], name='input')
    >>> net = tl.layers.InstanceNorm3d()(net)
    >>> # in dynamic model, build by specifying num_features
    >>> conv = tl.layers.Conv3d(32, (5, 5, 5), (1, 1), in_channels=3)
    >>> bn = tl.layers.InstanceNorm3d(num_features=32)

    """

    def _get_param_shape(self, inputs_shape):
        if self.data_format == 'channels_last':
            axis = 4
        elif self.data_format == 'channels_first':
            axis = 1
        else:
            raise ValueError('data_format should be either %s or %s' % ('channels_last', 'channels_first'))

        if self.num_features is None:
            channels = inputs_shape[axis]
        else:
            channels = self.num_features
        params_shape = [1] * 5
        params_shape[axis] = channels

        axes = [i for i in range(5) if i != 0 and i != axis]
        return params_shape, axes

# FIXME : not sure about the correctness, need testing
class LayerNorm(Layer):
    """
    The :class:`LayerNorm` class is for layer normalization, see `tf.contrib.layers.layer_norm <https://www.tensorflow.org/api_docs/python/tf/contrib/layers/layer_norm>`__.

    Parameters
    ----------
    prev_layer : :class:`Layer`
        The previous layer.
    act : activation function
        The activation function of this layer.
    others : _
        `tf.contrib.layers.layer_norm <https://www.tensorflow.org/api_docs/python/tf/contrib/layers/layer_norm>`__.

    """

    def __init__(
        self,  #prev_layer,
        center=True,
        scale=True,
        act=None,
        # reuse=None,
        # variables_collections=None,
        # outputs_collections=None,
        # trainable=True,
        epsilon=1e-12,
        begin_norm_axis=1,
        begin_params_axis=-1,
        beta_init=tl.initializers.zeros(),
        gamma_init=tl.initializers.ones(),
        data_format='channels_last',
        name=None,
    ):

        # super(LayerNorm, self).__init__(prev_layer=prev_layer, act=act, name=name)
        super(LayerNorm, self).__init__(name, act=act)
        self.center = center
        self.scale = scale
        self.epsilon = epsilon
        self.begin_norm_axis = begin_norm_axis
        self.begin_params_axis = begin_params_axis
        self.beta_init = beta_init
        self.gamma_init = gamma_init
        self.data_format = data_format

        logging.info(
            "LayerNorm %s: act: %s" % (self.name, self.act.__name__ if self.act is not None else 'No Activation')
        )

    def build(self, inputs_shape):
        params_shape = inputs_shape[self.begin_params_axis:]
        self.beta, self.gamma = None, None
        if self.center:
            self.beta = self._get_weights("beta", shape=params_shape, init=self.beta_init)
        if self.scale:
            self.gamma = self._get_weights("gamma", shape=params_shape, init=self.gamma_init)

        self.norm_axes = range(self.begin_norm_axis, len(inputs_shape))

    def forward(self, inputs):
        mean, var = tf.nn.moments(inputs, self.norm_axes, keepdims=True)
        # compute layer normalization using batch_normalization function
        outputs = batch_normalization(
            inputs, mean, var, self.beta, self.gamma, self.epsilon, data_format=self.data_format
        )
        if self.act:
            outputs = self.act(outputs)
        return outputs

    #     with tf.compat.v1.variable_scope(name) as vs:
    #         self.outputs = tf.contrib.layers.layer_norm(
    #             self.inputs,
    #             center=center,
    #             scale=scale,
    #             activation_fn=self.act,
    #             reuse=reuse,
    #             variables_collections=variables_collections,
    #             outputs_collections=outputs_collections,
    #             trainable=trainable,
    #             begin_norm_axis=begin_norm_axis,
    #             begin_params_axis=begin_params_axis,
    #             scope='var',
    #         )
    #
    #         variables = tf.compat.v1.get_collection("TF_GRAPHKEYS_VARIABLES", scope=vs.name)
    #
    #     self._add_layers(self.outputs)
    #     self._add_params(variables)

class GroupNorm(Layer):
    """The :class:`GroupNorm` layer is for Group Normalization.
    See `tf.contrib.layers.group_norm <https://www.tensorflow.org/api_docs/python/tf/contrib/layers/group_norm>`__.

    Parameters
    -----------
    # prev_layer : :class:`Layer`
    #     The previous layer.
    groups : int
        The number of groups
    act : activation function
        The activation function of this layer.
    epsilon : float
        Eplison.
    data_format : str
        channels_last 'channel_last' (default) or channels_first.
    name : None or str
        A unique layer name

    """

    def __init__(self, groups=32, epsilon=1e-06, act=None, data_format='channels_last', name=None):  #'groupnorm'):
        # super(GroupNorm, self).__init__(prev_layer=prev_layer, act=act, name=name)
        super().__init__(name, act=act)
        self.groups = groups
        self.epsilon = epsilon
        self.data_format = data_format

        logging.info(
            "GroupNorm %s: act: %s" % (self.name, self.act.__name__ if self.act is not None else 'No Activation')
        )

    def build(self, inputs_shape):
        # shape = inputs.get_shape().as_list()
        if len(inputs_shape) != 4:
            raise Exception("This GroupNorm only supports 2D images.")

        if self.data_format == 'channels_last':
            channels = inputs_shape[-1]
            self.int_shape = tf.concat(
                [#tf.shape(input=self.inputs)[0:3],
                inputs_shape[0:3],
                tf.convert_to_tensor(value=[self.groups, channels // self.groups])], axis=0
            )
        elif self.data_format == 'channels_first':
            channels = inputs_shape[1]
            self.int_shape = tf.concat(
                [
                    # tf.shape(input=self.inputs)[0:1],
                    inputs_shape[0:1],
                    tf.convert_to_tensor(value=[self.groups, channels // self.groups]),
                    # tf.shape(input=self.inputs)[2:4]
                    inputs_shape[2:4],
                ],
                axis=0
            )
        else:
            raise ValueError("data_format must be 'channels_last' or 'channels_first'.")

        if self.groups > channels:
            raise ValueError('Invalid groups %d for %d channels.' % (self.groups, channels))
        if channels % self.groups != 0:
            raise ValueError('%d channels is not commensurate with %d groups.' % (channels, self.groups))

        if self.data_format == 'channels_last':
            # mean, var = tf.nn.moments(x, [1, 2, 4], keep_dims=True)
            self.gamma = self._get_weights("gamma", shape=channels, init=tl.initializers.ones())
            # self.gamma = tf.compat.v1.get_variable('gamma', channels, initializer=tf.compat.v1.initializers.ones())
            self.beta = self._get_weights("beta", shape=channels, init=tl.initializers.zeros())
            # self.beta = tf.compat.v1.get_variable('beta', channels, initializer=tf.compat.v1.initializers.zeros())
        elif self.data_format == 'channels_first':
            # mean, var = tf.nn.moments(x, [2, 3, 4], keep_dims=True)
            self.gamma = self._get_weights("gamma", shape=[1, channels, 1, 1], init=tl.initializers.ones())
            # self.gamma = tf.compat.v1.get_variable('gamma', [1, channels, 1, 1], initializer=tf.compat.v1.initializers.ones())
            self.beta = self._get_weights("beta", shape=[1, channels, 1, 1], init=tl.initializers.zeros())
            # self.beta = tf.compat.v1.get_variable('beta', [1, channels, 1, 1], initializer=tf.compat.v1.initializers.zeros())
        # self.add_weights([self.gamma, self.bata])

    def forward(self, inputs):
        x = tf.reshape(inputs, self.int_shape)
        if self.data_format == 'channels_last':
            mean, var = tf.nn.moments(x=x, axes=[1, 2, 4], keepdims=True)
        elif self.data_format == 'channels_first':
            mean, var = tf.nn.moments(x=x, axes=[2, 3, 4], keepdims=True)
        else:
            raise Exception("unknown data_format")
        x = (x - mean) / tf.sqrt(var + self.epsilon)

        outputs = tf.reshape(x, tf.shape(input=inputs)) * self.gamma + self.beta
        if self.act:
            outputs = self.act(outputs)
        return outputs

class SwitchNorm(Layer):
    """
    The :class:`SwitchNorm` is a switchable normalization.

    Parameters
    ----------
    act : activation function
        The activation function of this layer.
    epsilon : float
        Eplison.
    beta_init : initializer or None
        The initializer for initializing beta, if None, skip beta.
        Usually you should not skip beta unless you know what happened.
    gamma_init : initializer or None
        The initializer for initializing gamma, if None, skip gamma.
        When the batch normalization layer is use instead of 'biases', or the next layer is linear, this can be
        disabled since the scaling can be done by the next layer. see `Inception-ResNet-v2 <https://github.com/tensorflow/models/blob/master/research/slim/nets/inception_resnet_v2.py>`__
    moving_mean_init : initializer or None
        The initializer for initializing moving mean, if None, skip moving mean.
    data_format : str
        channels_last 'channel_last' (default) or channels_first.
    name : None or str
        A unique layer name.

    References
    ----------
    - `Differentiable Learning-to-Normalize via Switchable Normalization <https://arxiv.org/abs/1806.10779>`__
    - `Zhihu (CN) <https://zhuanlan.zhihu.com/p/39296570?utm_source=wechat_session&utm_medium=social&utm_oi=984862267107651584>`__

    """

    def __init__(
        self,
        act=None,
        epsilon=1e-5,
        beta_init=tl.initializers.constant(0.0),
        gamma_init=tl.initializers.constant(1.0),
        moving_mean_init=tl.initializers.zeros(),
        # beta_init=tf.compat.v1.initializers.constant(0.0),
        # gamma_init=tf.compat.v1.initializers.constant(1.0),
        # moving_mean_init=tf.compat.v1.initializers.zeros(),
        data_format='channels_last',
        name=None,  #'switchnorm',
    ):
        # super(SwitchNorm, self).__init__(prev_layer=prev_layer, act=act, name=name)
        super().__init__(name, act=act)
        self.epsilon = epsilon
        self.beta_init = beta_init
        self.gamma_init = gamma_init
        self.moving_mean_init = moving_mean_init
        self.data_format = data_format

        logging.info(
            "SwitchNorm %s: epsilon: %f act: %s" %
            (self.name, epsilon, self.act.__name__ if self.act is not None else 'No Activation')
        )

    def build(self, inputs_shape):
        if len(inputs_shape) != 4:
            raise Exception("This SwitchNorm only supports 2D images.")
        if self.data_format != 'channels_last':
            raise Exception("This SwitchNorm only supports channels_last.")
        ch = inputs_shape[-1]
        self.gamma = self._get_weights("gamma", shape=[ch], init=self.gamma_init)
        # self.gamma = tf.compat.v1.get_variable("gamma", [ch], initializer=gamma_init)
        self.beta = self._get_weights("beta", shape=[ch], init=self.beta_init)
        # self.beta = tf.compat.v1.get_variable("beta", [ch], initializer=beta_init)

        self.mean_weight_var = self._get_weights("mean_weight", shape=[3], init=tl.initializers.constant(1.0))
        # self.mean_weight_var = tf.compat.v1.get_variable("mean_weight", [3], initializer=tf.compat.v1.initializers.constant(1.0))
        self.var_weight_var = self._get_weights("var_weight", shape=[3], init=tl.initializers.constant(1.0))
        # self.var_weight_var = tf.compat.v1.get_variable("var_weight", [3], initializer=tf.compat.v1.initializers.constant(1.0))

        # self.add_weights([self.gamma, self.beta, self.mean_weight_var, self.var_weight_var])

    def forward(self, inputs):

        batch_mean, batch_var = tf.nn.moments(x=inputs, axes=[0, 1, 2], keepdims=True)
        ins_mean, ins_var = tf.nn.moments(x=inputs, axes=[1, 2], keepdims=True)
        layer_mean, layer_var = tf.nn.moments(x=inputs, axes=[1, 2, 3], keepdims=True)

        mean_weight = tf.nn.softmax(self.mean_weight_var)
        var_weight = tf.nn.softmax(self.var_weight_var)

        mean = mean_weight[0] * batch_mean + mean_weight[1] * ins_mean + mean_weight[2] * layer_mean
        var = var_weight[0] * batch_var + var_weight[1] * ins_var + var_weight[2] * layer_var

        inputs = (inputs - mean) / (tf.sqrt(var + self.epsilon))
        outputs = inputs * self.gamma + self.beta
        if self.act:
            outputs = self.act(outputs)
        return outputs


text:
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
    {
        "file": "plugins/org.apache.cordova.contacts/www/contacts.js",
        "id": "org.apache.cordova.contacts.contacts",
        "clobbers": [
            "navigator.contacts"
        ]
    },
    {
        "file": "plugins/org.apache.cordova.contacts/www/Contact.js",
        "id": "org.apache.cordova.contacts.Contact",
        "clobbers": [
            "Contact"
        ]
    },
    {
        "file": "plugins/org.apache.cordova.contacts/www/ContactAddress.js",
        "id": "org.apache.cordova.contacts.ContactAddress",
        "clobbers": [
            "ContactAddress"
        ]
    },
    {
        "file": "plugins/org.apache.cordova.contacts/www/ContactError.js",
        "id": "org.apache.cordova.contacts.ContactError",
        "clobbers": [
            "ContactError"
        ]
    },
    {
        "file": "plugins/org.apache.cordova.contacts/www/ContactField.js",
        "id": "org.apache.cordova.contacts.ContactField",
        "clobbers": [
            "ContactField"
        ]
    },
    {
        "file": "plugins/org.apache.cordova.contacts/www/ContactFindOptions.js",
        "id": "org.apache.cordova.contacts.ContactFindOptions",
        "clobbers": [
            "ContactFindOptions"
        ]
    },
    {
        "file": "plugins/org.apache.cordova.contacts/www/ContactName.js",
        "id": "org.apache.cordova.contacts.ContactName",
        "clobbers": [
            "ContactName"
        ]
    },
    {
        "file": "plugins/org.apache.cordova.contacts/www/ContactOrganization.js",
        "id": "org.apache.cordova.contacts.ContactOrganization",
        "clobbers": [
            "ContactOrganization"
        ]
    }
]
});


text:
  <mat-radio-button (click)="changeViewType(viewTypes.split)" [checked]="activeViewType === viewTypes.split" [value]="viewTypes.split"
                    class="custom-control-input"
                    id="radio-splitscreen"
                    name="radio-group-screen"></mat-radio-button>

      <fa-icon [icon]="faSquare" size="lg" style="color:white;"></fa-icon>
      <fa-icon [icon]="faSquare" size="lg" style="color:white;"></fa-icon>

  <mat-radio-button (click)="changeViewType(viewTypes.merged)" [checked]="activeViewType === viewTypes.merged" [value]="viewTypes.merged"
                    class="custom-control-input"
                    id="radio-fullscreen"
                    name="radio-group-screen"></mat-radio-button>

      <fa-icon [icon]="faClone" size="lg" style="color:white;"></fa-icon>


text:
package com.jkoolcloud.tnt4j.streams.inputs;

/**
 * A streamed items accounting notifications listener interface. This interface can be implemented by classes that are
 * interested in streamed items accounting for lost/filtered/skipped/processed items and streamed bytes counts.
 *
 * @version $Revision: 1 $
 *
 * @see com.jkoolcloud.tnt4j.streams.inputs.TNTInputStream#addStreamItemAccountingListener(StreamItemAccountingListener)
 */
public interface StreamItemAccountingListener {
	/**
	 * This method gets called when streamed item gets lost.
	 */
	void onItemLost();

	/**
	 * This method gets called when streamed item gets filtered.
	 */
	void onItemFiltered();

	/**
	 * This method gets called when streamed item gets skipped.
	 */
	void onItemSkipped();

	/**
	 * This method gets called when streamed item gets processed.
	 */
	void onItemProcessed();

	/**
	 * Updates streamed bytes count.
	 *
	 * @param bytes
	 *            streamed item bytes count
	 */
	void onBytesStreamed(long bytes);

	/**
	 * Updates total count of bytes to be streamed.
	 *
	 * @param stream
	 *            stream instance updating totals
	 * @param bytes
	 *            total count of bytes to be streamed
	 * @param activities
	 *            total count of activities to be streamed
	 *
	 */
	void updateTotal(TNTInputStream<?, ?> stream, long bytes, int activities);

}


text:
namespace Loki
{
    namespace Private
    {
////////////////////////////////////////////////////////////////////////////////
// class LifetimeTracker
// Helper class for SetLongevity
////////////////////////////////////////////////////////////////////////////////

        class LifetimeTracker
        {
        public:
            LifetimeTracker(unsigned int x) : longevity_(x)
            {}

            virtual ~LifetimeTracker() = 0;

            static bool Compare(const LifetimeTracker* lhs,
                const LifetimeTracker* rhs)
            {
                return lhs->longevity_ > rhs->longevity_;
            }

        private:
            unsigned int longevity_;
        };

        // Definition required
        inline LifetimeTracker::~LifetimeTracker() {}

        // Helper data
        typedef LifetimeTracker** TrackerArray;
        extern TrackerArray pTrackerArray;
        extern unsigned int elements;

        // Helper destroyer function
        template <typename T>
        struct Deleter
        {
            static void Delete(T* pObj)
            { delete pObj; }
        };

        // Concrete lifetime tracker for objects of type T
        template <typename T, typename Destroyer>
        class ConcreteLifetimeTracker : public LifetimeTracker
        {
        public:
            ConcreteLifetimeTracker(T* p,unsigned int longevity, Destroyer d)
                : LifetimeTracker(longevity)
                , pTracked_(p)
                , destroyer_(d)
            {}

            ~ConcreteLifetimeTracker()
            { destroyer_(pTracked_); }

        private:
            T* pTracked_;
            Destroyer destroyer_;
        };

        void AtExitFn(); // declaration needed below

    } // namespace Private

////////////////////////////////////////////////////////////////////////////////
// function template SetLongevity
// Assigns an object a longevity; ensures ordered destructions of objects
//     registered thusly during the exit sequence of the application
////////////////////////////////////////////////////////////////////////////////

    template <typename T, typename Destroyer>
    void SetLongevity(T* pDynObject, unsigned int longevity,
        Destroyer d = Private::Deleter<T>::Delete)
    {
        using namespace Private;

        TrackerArray pNewArray = static_cast<TrackerArray>(
                std::realloc(pTrackerArray, sizeof(*pTrackerArray) * (elements + 1)));
        if (!pNewArray) throw std::bad_alloc();

        // Delayed assignment for exception safety
        pTrackerArray = pNewArray;

        LifetimeTracker* p = new ConcreteLifetimeTracker<T, Destroyer>(
            pDynObject, longevity, d);

        // Insert a pointer to the object into the queue
        TrackerArray pos = std::upper_bound(
            pTrackerArray,
            pTrackerArray + elements,
            p,
            LifetimeTracker::Compare);
        std::copy_backward(
            pos,
            pTrackerArray + elements,
            pTrackerArray + elements + 1);
        *pos = p;
        ++elements;

        // Register a call to AtExitFn
        std::atexit(Private::AtExitFn);
    }

////////////////////////////////////////////////////////////////////////////////
// class template CreateUsingNew
// Implementation of the CreationPolicy used by SingletonHolder
// Creates objects using a straight call to the new operator
////////////////////////////////////////////////////////////////////////////////

    template <class T> struct CreateUsingNew
    {
        static T* Create()
        { return new T; }

        static void Destroy(T* p)
        { delete p; }
    };

////////////////////////////////////////////////////////////////////////////////
// class template CreateUsingNew
// Implementation of the CreationPolicy used by SingletonHolder
// Creates objects using a call to std::malloc, followed by a call to the
//     placement new operator
////////////////////////////////////////////////////////////////////////////////

    template <class T> struct CreateUsingMalloc
    {
        static T* Create()
        {
            void* p = std::malloc(sizeof(T));
            if (!p) return 0;
            return new(p) T;
        }

        static void Destroy(T* p)
        {
            p->~T();
            std::free(p);
        }
    };

////////////////////////////////////////////////////////////////////////////////
// class template CreateStatic
// Implementation of the CreationPolicy used by SingletonHolder
// Creates an object in static memory
// Implementation is slightly nonportable because it uses the MaxAlign trick
//     (an union of all types to ensure proper memory alignment). This trick is
//     nonportable in theory but highly portable in practice.
////////////////////////////////////////////////////////////////////////////////

    template <class T> struct CreateStatic
    {
#ifdef _MSC_VER
#pragma warning( push )
 // alignment of a member was sensitive to packing
#pragma warning( disable : 4121 )
#endif // _MSC_VER
        union MaxAlign
        {
            char t_[sizeof(T)];
            short int shortInt_;
            int int_;
            long int longInt_;
            float float_;
            double double_;
            long double longDouble_;
            struct Test;
            int Test::* pMember_;
            int (Test::*pMemberFn_)(int);
        };
#ifdef _MSC_VER
#pragma warning( pop )
#endif // _MSC_VER

        static T* Create()
        {
            static MaxAlign staticMemory_;
            return new(&staticMemory_) T;
        }

        static void Destroy(T* p)
        {
            p->~T();
        }
    };

////////////////////////////////////////////////////////////////////////////////
// class template DefaultLifetime
// Implementation of the LifetimePolicy used by SingletonHolder
// Schedules an object's destruction as per C++ rules
// Forwards to std::atexit
////////////////////////////////////////////////////////////////////////////////

    template <class T>
    struct DefaultLifetime
    {
        static void ScheduleDestruction(T*, void (*pFun)())
        { std::atexit(pFun); }

        static void OnDeadReference()
        { throw std::logic_error("Dead Reference Detected"); }
    };

////////////////////////////////////////////////////////////////////////////////
// class template PhoenixSingleton
// Implementation of the LifetimePolicy used by SingletonHolder
// Schedules an object's destruction as per C++ rules, and it allows object
//    recreation by not throwing an exception from OnDeadReference
////////////////////////////////////////////////////////////////////////////////

    template <class T>
    class PhoenixSingleton
    {
    public:
        static void ScheduleDestruction(T*, void (*pFun)())
        {
#ifndef ATEXIT_FIXED
            if (!destroyedOnce_)
#endif
                std::atexit(pFun);
        }

        static void OnDeadReference()
        {
#ifndef ATEXIT_FIXED
            destroyedOnce_ = true;
#endif
        }

    private:
#ifndef ATEXIT_FIXED
        static bool destroyedOnce_;
#endif
    };

#ifndef ATEXIT_FIXED
    template <class T> bool PhoenixSingleton<T>::destroyedOnce_ = false;
#endif

////////////////////////////////////////////////////////////////////////////////
// class template Adapter
// Helper for SingletonWithLongevity below
////////////////////////////////////////////////////////////////////////////////

    namespace Private
    {
        template <class T>
        struct Adapter
        {
            void operator()(T*) { return pFun_(); }
            void (*pFun_)();
        };
    }

////////////////////////////////////////////////////////////////////////////////
// class template SingletonWithLongevity
// Implementation of the LifetimePolicy used by SingletonHolder
// Schedules an object's destruction in order of their longevities
// Assumes a visible function GetLongevity(T*) that returns the longevity of the
//     object
////////////////////////////////////////////////////////////////////////////////

    template <class T>
    class SingletonWithLongevity
    {
    public:
        static void ScheduleDestruction(T* pObj, void (*pFun)())
        {
            Private::Adapter<T> adapter = { pFun };
            SetLongevity(pObj, GetLongevity(pObj), adapter);
        }

        static void OnDeadReference()
        { throw std::logic_error("Dead Reference Detected"); }
    };

////////////////////////////////////////////////////////////////////////////////
// class template NoDestroy
// Implementation of the LifetimePolicy used by SingletonHolder
// Never destroys the object
////////////////////////////////////////////////////////////////////////////////

    template <class T>
    struct NoDestroy
    {
        static void ScheduleDestruction(T*, void (*)())
        {}

        static void OnDeadReference()
        {}
    };

////////////////////////////////////////////////////////////////////////////////
// class template SingletonHolder
// Provides Singleton amenities for a type T
// To protect that type from spurious instantiations, you have to protect it
//     yourself.
////////////////////////////////////////////////////////////////////////////////

    template
    <
        class ClientType,
        class ThreadingModelType,
        class PtrInstanceType
    >
    class SingletonHolderStaticData
    {
        friend ClientType; // illegal (11.4/2) but works with VC
        static PtrInstanceType    s_pInstance;
        static bool               s_destroyed;
    };

    template<class C, class M, class P>
    P SingletonHolderStaticData<C, M, P>::s_pInstance;

    template<class C, class M, class P>
    bool SingletonHolderStaticData<C, M, P>::s_destroyed;

    template
    <
        typename T,
        template <class> class CreationPolicy = CreateUsingNew,
        template <class> class LifetimePolicy = DefaultLifetime,
        template <class> class ThreadingModel = SingleThreaded
    >
    class SingletonHolder
    {
        typedef typename ThreadingModel<T*>::VolatileType PtrInstanceType;

        typedef SingletonHolderStaticData
        <
            SingletonHolder,
            ThreadingModel<T>,
            PtrInstanceType
        >
        MySingletonHolderStaticData;

    public:
        static T& Instance()
        {
            if (!pInstance_())
            {
                MakeInstance();
            }
            return *pInstance_();
        }

    private:
        // Helpers
        static void MakeInstance()
        {
            typename ThreadingModel<SingletonHolder>::Lock guard;
            (void)guard;

            if (!pInstance_())
            {
                if (destroyed_())
                {
                    LifetimePolicy<T>::OnDeadReference();
                    destroyed_() = false;
                }

                pInstance_() = CreationPolicy<T>::Create();

                LifetimePolicy<T>::ScheduleDestruction
                (
                    pInstance_(),
                    &DestroySingleton
                );
            }
        }

        static void DestroySingleton()
        {
            assert(!destroyed_());
            CreationPolicy<T>::Destroy(pInstance_());
            pInstance_() = 0;
            destroyed_() = true;
        }

        // Protection
        SingletonHolder();

        // Data
        static PtrInstanceType &pInstance_()
        {
            return MySingletonHolderStaticData::s_pInstance;
        }

        static bool &destroyed_()
        {
            return MySingletonHolderStaticData::s_destroyed;
        }
    };

} // namespace Loki

////////////////////////////////////////////////////////////////////////////////
// Change log:
// May 21, 2001: Correct the volatile qualifier - credit due to Darin Adler
// June 20, 2001: ported by Nick Thurn to gcc 2.95.3. Kudos, Nick!!!
// May  10, 2002: ported by Rani Sharoni to VC7 (RTM - 9466)
////////////////////////////////////////////////////////////////////////////////

#endif // SINGLETON_INC_