text:
require 'fileutils'

require 'archive/tar/minitar'
require "json"
require "log4r"

require "vagrant/util/platform"

module Vagrant
  # Represents a "box," which is a package Vagrant environment that is used
  # as a base image when creating a new guest machine.
  class Box
    include Comparable

    # The box name. This is the logical name used when adding the box.
    #
    # @return [String]
    attr_reader :name

    # This is the provider that this box is built for.
    #
    # @return [Symbol]
    attr_reader :provider

    # This is the directory on disk where this box exists.
    #
    # @return [Pathname]
    attr_reader :directory

    # This is the metadata for the box. This is read from the "metadata.json"
    # file that all boxes require.
    #
    # @return [Hash]
    attr_reader :metadata

    # This is used to initialize a box.
    #
    # @param [String] name Logical name of the box.
    # @param [Symbol] provider The provider that this box implements.
    # @param [Pathname] directory The directory where this box exists on
    #   disk.
    def initialize(name, provider, directory)
      @name      = name
      @provider  = provider
      @directory = directory
      @metadata  = JSON.parse(directory.join("metadata.json").read)

      @logger = Log4r::Logger.new("vagrant::box")
    end

    # This deletes the box. This is NOT undoable.
    def destroy!
      # Delete the directory to delete the box.
      FileUtils.rm_r(@directory)

      # Just return true always
      true
    rescue Errno::ENOENT
      # This means the directory didn't exist. Not a problem.
      return true
    end

    # This repackages this box and outputs it to the given path.
    #
    # @param [Pathname] path The full path (filename included) of where
    #   to output this box.
    # @return [Boolean] true if this succeeds.
    def repackage(path)
      @logger.debug("Repackaging box '#{@name}' to: #{path}")

      path.open(Util::Platform.tar_file_options) do |f|
        Archive::Tar::Minitar::Output.open(f) do |output|
          # Store the current working directory since we need to change
          # for the tar library.
          current_dir = FileUtils.pwd

          begin
            FileUtils.cd(@directory)

            # Find all the files in our current directory and tar it up!
            Dir.glob(File.join(".", "**", "*")).each do |entry|
              @logger.debug("Packing file: #{entry}")
              Archive::Tar::Minitar.pack_file(entry, output)
            end
          ensure
            # Make sure we always cd back into our previous working
            # directory.
            FileUtils.cd(current_dir)
          end
        end
      end

      @logger.info("Repackaged box '#{@name}' successfully: #{path}")

      true
    end

    # Implemented for comparison with other boxes. Comparison is
    # implemented by comparing names and providers.
    def <=>(other)
      return super if !other.is_a?(self.class)

      # Comparison is done by composing the name and provider
      "#{@name}-#{@provider}" <=> "#{other.name}-#{other.provider}"
    end
  end
end


text: README: organiserSettings

redpajama_set_name: RedPajamaGithub


text:
package software.amazon.awssdk.core.document.internal;

import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkNumber;
import software.amazon.awssdk.core.document.Document;
import software.amazon.awssdk.core.document.DocumentVisitor;
import software.amazon.awssdk.core.document.VoidDocumentVisitor;

/**
 * Represents a Boolean Document.
 */
@SdkInternalApi
@Immutable
public final class BooleanDocument implements Document {

    private static final long serialVersionUID = 1L;

    private final boolean value;

    /**
     * Create a New {@link BooleanDocument} with boolean value as passed in constructor
     * @param value boolean value.
     */
    public BooleanDocument(boolean value) {
        this.value = value;
    }

    /**
     * Unwraps the Document Boolean to a Boolean Object.
     * @return  boolean value.
     */
    @Override
    public Object unwrap() {
        return value;
    }

    /**
     * Indicates this is a Boolean Document.
     * @return true since this is a Boolean Document.
     */
    @Override
    public boolean isBoolean() {
        return true;
    }

    /**
     * Gets the boolean value of the Document.
     * @return boolean value.
     */
    @Override
    public boolean asBoolean() {
        return value;
    }

    /**
     * {@inheritdoc}
     */
    @Override
    public String asString() {
        throw new UnsupportedOperationException("A Document Boolean cannot be converted to a String.");
    }

    /**
     * {@inheritdoc}
     */
    @Override
    public SdkNumber asNumber() {
        throw new UnsupportedOperationException("A Document Boolean cannot be converted to a Number.");
    }

    /**
     * {@inheritdoc}
     */
    @Override
    public Map<String, Document> asMap() {
        throw new UnsupportedOperationException("A Document Boolean cannot be converted to a Map.");
    }

    /**
     * {@inheritdoc}
     */
    @Override
    public List<Document> asList() {
        throw new UnsupportedOperationException("A Document Boolean cannot be converted to a List.");
    }

    /**
     * Accepts a visitor with the Document.
     * @param <R> visitor return type.
     * @param visitor Visitor to dispatch to.
     * @return Returns the accepted result by calling visitBoolean of visitor.
     */
    @Override
    public <R> R accept(DocumentVisitor<? extends R> visitor) {
        return visitor.visitBoolean(asBoolean());
    }

    /**
     * Accepts a visitor with the Document. Calls visitBoolean of visitor.
     * @param visitor Visitor to dispatch to.
     */
    @Override
    public void accept(VoidDocumentVisitor visitor) {
        visitor.visitBoolean(asBoolean());
    }

    @Override
    public String toString() {
        return Boolean.toString(value);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof BooleanDocument)) {
            return false;
        }
        BooleanDocument that = (BooleanDocument) o;
        return value == that.value;
    }

    @Override
    public int hashCode() {
        return Boolean.hashCode(value);
    }
}


text:
goog.provide('foo.bar.Baz');

// NestedClass and NestedEnum are not provided because this is against JS
// closure's style guide.
// https://google.github.io/styleguide/javascriptguide.xml?showone=Providing_Dependencies_With_goog.provide#Providing_Dependencies_With_goog.provide

/** @constructor */
foo.bar.Baz = function() {
  /** @type {string} */
  this.field = 'a';
  // Surprisingly, defining the same field on the prototype and in
  // the constructor with different signatures doesn't throw a type error.
  // The type of the prototype is preferred and as far as types are
  // concerned `avalue` lives on the prototype object.
  /** @type {string} */
  this.avalue = 0;
};

/**
 * @param {string} a
 * @return {number}
 */
foo.bar.Baz.staticMethod = function(a) {
  return +a;
};

/** @const {!Function} */
// A static property of type Function, not to be confused with a real ctor.
foo.bar.Baz.FUNCTION_PROP_ = foo.bar.Baz.staticMethod;

/**
 * @type {number}
 */
foo.bar.Baz.prototype.avalue = 0;

/**
 * @param {string} a
 * @return {number}
 */
foo.bar.Baz.prototype.method = function(a) {
  return +a;
};

/**
 * @param {!foo.bar.Baz.NestedClass} b
 * @return {boolean}
 */
foo.bar.Baz.prototype.equals = function(b) {
  return false;
};

/** @constructor */
foo.bar.Baz.NestedClass = function() {};

/** @enum */
foo.bar.Baz.NestedEnum = {
  // XD goes before B to test for enum value sorting. B should go first in the
  // declarations file.
  XD: 2,
  B: 1
};


text:
<?php

namespace fXmlRpc\Client\Tests\Integration;

use fXmlRpc\Client\Client;
use fXmlRpc\Client\Exception\TransportException;

/**
 * @large
 * @group integration
 * @group node
 *
 * @author Lars Strojny <lstrojny@php.net>
 */
class NodeCallClientIntegrationTest extends AbstractCallClientIntegrationTest
{
    protected static $endpoint = 'http://127.0.0.1:9090/';

    protected static $errorEndpoint = 'http://127.0.0.1:9091/';

    protected static $command = 'exec node server.js';

    /**
     * @dataProvider getClients
     */
    public function testServerNotReachableViaTcpIp(Client $client)
    {
        $client->setUri('http://127.0.0.1:12345/');

        try {
            $client->call('system.failure');
            $this->fail('Exception expected');
        } catch (TransportException $e) {
            $this->assertInstanceOf('fXmlRpc\Client\Exception\TransportException', $e);
            $this->assertInstanceOf('fXmlRpc\Exception', $e);
            $this->assertInstanceOf('RuntimeException', $e);
            $this->assertStringStartsWith('Transport error occurred:', $e->getMessage());
            $this->assertSame(0, $e->getCode());
        }
    }

    /**
     * @dataProvider getClients
     */
    public function testServerReturnsInvalidResult(Client $client)
    {
        $this->executeSystemFailureTest($client);
    }
}


text:
define(['modules/forms/module', 'ionslider'], function (module) {

    'use strict';

    return module.registerDirective('smartIonslider', function () {
        return {
            restrict: 'A',
            compile: function (tElement, tAttributes) {
                tElement.removeAttr('smart-ionslider data-smart-ionslider');

                tElement.ionRangeSlider();
            }
        }
    });
});


text:
//
//  BumbleBSound.h
//  Pods
//
//  Created by Ram Greenberg on 10/8/15.
//
//

#import <Foundation/Foundation.h>

@interface BumbleBSound : NSObject

/**
 URL of sound (audio file)
 */
@property (readonly, strong, nonatomic) NSURL * url;

/**
 size of sound
 */
@property (readonly, nonatomic) NSInteger size;

/**
 construct sound from json
 */
- (instancetype) initWithDictionary:(NSDictionary *) dictionary;

@end


text:
package com.asakusafw.testdriver.core;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;

import org.junit.Rule;
import org.junit.rules.TemporaryFolder;

/**
 * SPI testing base class.
 * @since 0.2.0
 */
public abstract class SpiTestRoot {

    /**
     * Temporary Folder.
     */
    @Rule
    public TemporaryFolder temporaryFolder = new TemporaryFolder() {
        @Override
        protected void before() throws Throwable {
            super.before();
            classpath = newFolder();
        }
    };

    File classpath;

    /**
     * Creates META-INF/services/API.
     * @param api API class
     * @param services service classes
     * @return service class loader
     * @throws IOException if failed
     */
    public ClassLoader register(Class<?> api, Class<?>... services) throws IOException {
        assert classpath != null;
        try {
            File serviceFolder = new File(classpath, "META-INF/services");
            serviceFolder.mkdirs();
            try (PrintWriter output = new PrintWriter(new File(serviceFolder, api.getName()))) {
                for (Class<?> serviceClass : services) {
                    output.println(serviceClass.getName());
                }
            }
            return new URLClassLoader(new URL[] { classpath.toURI().toURL() });
        } catch (IOException e) {
            throw new AssertionError(e);
        }
    }

    /**
     * Creates {@link DataModelSource} from values.
     * @param <E> type of data model objects
     * @param definition the data model definition
     * @param values source values
     * @return the created object
     */
    @SafeVarargs
    public static <E> DataModelSource source(DataModelDefinition<E> definition, E... values) {
        return new IteratorDataModelSource(definition, Arrays.asList(values).iterator());
    }
}


text:
package com.google.api.auth;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.LowLevelHttpRequest;
import com.google.api.client.http.LowLevelHttpResponse;
import com.google.api.client.json.Json;
import com.google.api.client.testing.http.MockHttpTransport;
import com.google.api.client.testing.http.MockLowLevelHttpRequest;
import com.google.api.client.testing.http.MockLowLevelHttpResponse;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;

import org.apache.http.HttpStatus;
import org.bouncycastle.util.encoders.Hex;
import org.jose4j.jwk.JsonWebKey;
import org.jose4j.jwk.JsonWebKeySet;
import org.jose4j.jwk.RsaJsonWebKey;
import org.jose4j.jwk.RsaJwkGenerator;
import org.jose4j.lang.JoseException;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * Tests for {@link DefaultJwksSupplier};
 *
 * @author yangguan@google.com
 *
 */
public class DefaultJwksSupplierTest {
  private static final String ISSUER = "issuer";
  private static final GenericUrl URI = new GenericUrl("https://jwks.uri/");
  private static ObjectWriter OBJECT_WRITER = new ObjectMapper().writer();

  private final KeyUriSupplier keyUriSupplier = mock(KeyUriSupplier.class);

  @Before
  public void setUp() throws JoseException {
    when(this.keyUriSupplier.supply(ISSUER)).thenReturn(Optional.of(URI));
  }

  @Test
  public void testSupplyJwks() throws JoseException {
    RsaJsonWebKey rsaJwk = RsaJwkGenerator.generateJwk(2048);
    JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(rsaJwk);
    HttpTransport httpTransport = new TestingHttpTransport(jsonWebKeySet.toJson(), null);
    DefaultJwksSupplier jwksSupplier =
        new DefaultJwksSupplier(httpTransport.createRequestFactory(), keyUriSupplier);
    List<JsonWebKey> jsonWebKeys = jwksSupplier.supply(ISSUER).getJsonWebKeys();
    JsonWebKey jsonWebKey = Iterables.getOnlyElement(jsonWebKeys);

    assertKeysEqual(rsaJwk.getKey(), jsonWebKey.getKey());
  }

  @Test
  public void testSupplyJwksFromX509Certificate() throws
      NoSuchAlgorithmException, JsonProcessingException {
    RsaJsonWebKey rsaJsonWebKey = TestUtils.generateRsaJsonWebKey("key-id");
    String cert = TestUtils.generateX509Cert(rsaJsonWebKey);
    String keyId = "key-id";
    String json = OBJECT_WRITER.writeValueAsString(ImmutableMap.of(keyId, cert));

    HttpTransport httpTransport = new TestingHttpTransport(json, null);
    DefaultJwksSupplier jwksSupplier =
        new DefaultJwksSupplier(httpTransport.createRequestFactory(), keyUriSupplier);
    JsonWebKeySet jsonWebKeySet = jwksSupplier.supply(ISSUER);
    JsonWebKey jsonWebKey = Iterables.getOnlyElement(jsonWebKeySet.getJsonWebKeys());

    assertEquals(keyId, jsonWebKey.getKeyId());
    assertKeysEqual(rsaJsonWebKey.getPublicKey(), jsonWebKey.getKey());
  }

  @Test
  public void testSupplyWithIoException() {
    HttpTransport httpTransport = new TestingHttpTransport(null, new IOException());
    DefaultJwksSupplier jwksSupplier =
        new DefaultJwksSupplier(httpTransport.createRequestFactory(), keyUriSupplier);
    try {
      jwksSupplier.supply(ISSUER);
    } catch (UnauthenticatedException exception) {
      assertTrue(exception.getCause() instanceof IOException);
    }
  }

  @Test
  public void testSupplyWithUnknownIssuer() {
    TestingHttpTransport httpTransport = new TestingHttpTransport(null, null);
    DefaultJwksSupplier jwksSupplier =
        new DefaultJwksSupplier(httpTransport.createRequestFactory(), keyUriSupplier);

    when(keyUriSupplier.supply(ISSUER)).thenReturn(Optional.<GenericUrl>absent());
    try {
      jwksSupplier.supply(ISSUER);
      fail();
    } catch (Exception exception) {
      assertTrue(
          exception.getMessage().startsWith("Cannot find the jwks_uri for issuer " + ISSUER));
    }
  }

  private static void assertKeysEqual(Key expected, Key actual) {
    assertEquals(expected.getAlgorithm(), actual.getAlgorithm());
    assertEquals(
        new String(Hex.encode(expected.getEncoded())),
        new String(Hex.encode(actual.getEncoded())));
    assertEquals(expected.getFormat(), actual.getFormat());
  }

  private static final class TestingHttpTransport extends MockHttpTransport {
    private final String content;
    private final IOException ioException;

    public TestingHttpTransport(String content, IOException exception) {
      this.content = content;
      this.ioException = exception;
    }

    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          if (ioException != null) {
            throw ioException;
          }
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(HttpStatus.SC_ACCEPTED);
          response.setContentType(Json.MEDIA_TYPE);
          response.setContent(content);
          return response;
        }
      };
    }
  }
}


text:
package com.netflix.priam.defaultimpl;

import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
import com.netflix.priam.aws.S3CrossAccountFileSystem;
import com.netflix.priam.aws.S3EncryptedFileSystem;
import com.netflix.priam.aws.S3FileSystem;
import com.netflix.priam.aws.auth.IS3Credential;
import com.netflix.priam.aws.auth.S3RoleAssumptionCredential;
import com.netflix.priam.backup.BackupFileSystemContext;
import com.netflix.priam.backup.IBackupFileSystem;
import com.netflix.priam.backup.IFileSystemContext;
import com.netflix.priam.backup.IncrementalBackup;
import com.netflix.priam.backup.parallel.CassandraBackupQueueMgr;
import com.netflix.priam.backup.parallel.ITaskQueueMgr;
import com.netflix.priam.cryptography.IFileCryptography;
import com.netflix.priam.cryptography.pgp.PgpCredential;
import com.netflix.priam.cryptography.pgp.PgpCryptography;
import com.netflix.priam.google.GcsCredential;
import com.netflix.priam.google.GoogleEncryptedFileSystem;
import com.netflix.priam.identity.AwsInstanceEnvIdentity;
import com.netflix.priam.identity.InstanceEnvIdentity;
import com.netflix.priam.identity.token.DeadTokenRetriever;
import com.netflix.priam.identity.token.IDeadTokenRetriever;
import com.netflix.priam.identity.token.INewTokenRetriever;
import com.netflix.priam.identity.token.IPreGeneratedTokenRetriever;
import com.netflix.priam.identity.token.NewTokenRetriever;
import com.netflix.priam.identity.token.PreGeneratedTokenRetriever;
import com.netflix.priam.ICredentialGeneric;
import com.netflix.priam.restore.EncryptedRestoreStrategy;
import com.netflix.priam.restore.IRestoreStrategy;
import com.netflix.priam.ICredential;

public class PriamGuiceModule extends AbstractModule
{
    @Override
    protected void configure()
    {
        bind(SchedulerFactory.class).to(StdSchedulerFactory.class).asEagerSingleton();

        bind(IBackupFileSystem.class).annotatedWith(Names.named("backup")).to(S3FileSystem.class);
        bind(IBackupFileSystem.class).annotatedWith(Names.named("encryptedbackup")).to(S3EncryptedFileSystem.class);
        bind(IBackupFileSystem.class).annotatedWith(Names.named("incr_restore")).to(S3FileSystem.class);
        bind(IBackupFileSystem.class).annotatedWith(Names.named("backup_status")).to(S3FileSystem.class);

        bind(S3CrossAccountFileSystem.class);
        bind(IFileSystemContext.class).annotatedWith(Names.named("backup")).to(BackupFileSystemContext.class);

        bind(IBackupFileSystem.class).annotatedWith(Names.named("gcsencryptedbackup")).to(GoogleEncryptedFileSystem.class);
        bind(IS3Credential.class).annotatedWith(Names.named("awsroleassumption")).to(S3RoleAssumptionCredential.class);
        bind(IFileCryptography.class).annotatedWith(Names.named("filecryptoalgorithm")).to(PgpCryptography.class);
        bind(ICredentialGeneric.class).annotatedWith(Names.named("gcscredential")).to(GcsCredential.class);
        bind(ICredentialGeneric.class).annotatedWith(Names.named("pgpcredential")).to(PgpCredential.class);
        bind(IRestoreStrategy.class).annotatedWith(Names.named("encryptedrestore")).to(EncryptedRestoreStrategy.class);
        bind(ICredential.class).to(ClearCredential.class);
        bind(IDeadTokenRetriever.class).to(DeadTokenRetriever.class);
        bind(IPreGeneratedTokenRetriever.class).to(PreGeneratedTokenRetriever.class);
        bind(INewTokenRetriever.class).to(NewTokenRetriever.class);
        bind(ITaskQueueMgr.class).annotatedWith(Names.named("backup")).to(CassandraBackupQueueMgr.class);
        bind(InstanceEnvIdentity.class).to(AwsInstanceEnvIdentity.class);

    }
}


text:
module Plottable {
  export module Formatter {
    export class Custom extends Abstract.Formatter {
      constructor(precision: number, customFormatFunction: (d: any, formatter: Formatter.Custom) => string) {
        super(precision);
        this._onlyShowUnchanged = false;
        this._formatFunction = function(d: any) {
          return customFormatFunction(d, this);
        };
      }
    }
  }
}


text:
'use strict';

//************************ Change these values to match your server settings ****************/
var databaseUrl = "localhost";
var databaseUsername = "cassandra";
var databasePassword = "cassandra";
//*******************************************************************************************/

var myApp = require('../app');
var should = require('chai').should();
var request = require('supertest')(myApp);

describe('general request', function () {
    it('return the homepage', function (done) {
        request
            .get('/')
            .expect(200, 'The homepage is loaded', done());
    });
});

describe('cassdb API', function () {

    describe('POST /api/connect', function (done) {

        it('should connect to the database and return an API Key', function (done) {
            var databaseuser = {
                address: databaseUrl,
                username: databaseUsername,
                password: databasePassword
            };

            request
                .post('/api/connect')
                .set('Content-Type', 'application/json')
                .send(databaseuser)
                .expect(200, function (err, res) {
                    res.body.should.have.property('apiKey');
                    done();
                });
        });

    });

    describe('POST /api/execute_cql', function (done) {

        it('should execute a CQL query and return 200 if the query was correct', function (done) {
            var databaseuser = {
                address: databaseUrl,
                username: databaseUsername,
                password: databasePassword
            };

            request
                .post('/api/connect')
                .set('Content-Type', 'application/json')
                .send(databaseuser)
                .expect(200, function (err, res) {
                    var apiKey = res.body.apiKey;
                    var cqlRequest = "select * from system.schema_columns";
                    request
                        .post('/api/execute_cql?apiKey=' + apiKey)
                        .set('Content-Type', 'application/json')
                        .send({query: cqlRequest})
                        .expect(200, done);
                });
        });

        it('should execute a CQL query and return 400 if the query was wrong', function (done) {
            var databaseuser = {
                address: databaseUrl,
                username: databaseUsername,
                password: databasePassword
            };

            request
                .post('/api/connect')
                .set('Content-Type', 'application/json')
                .send(databaseuser)
                .expect(200, function (err, res) {
                    var apiKey = res.body.apiKey;
                    var cqlRequest = "select * from schema_column";
                    request
                        .post('/api/execute_cql?apiKey=' + apiKey)
                        .set('Content-Type', 'application/json')
                        .send({query: cqlRequest})
                        .expect(400, done);
                });

        });

    });
});


text:
//
// CMSampleBuffer.cs: Implements the managed CMSampleBuffer
//
// Authors: Mono Team
//			Marek Safar (marek.safar@gmail.com)
//
// Copyright 2010 Novell, Inc
// Copyright 2012 Xamarin Inc
//
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Collections.Generic;

using MonoMac;
using MonoMac.Foundation;
using MonoMac.CoreFoundation;
using MonoMac.ObjCRuntime;

#if !COREBUILD
using MonoMac.AudioToolbox;
using MonoMac.CoreVideo;
#if !MONOMAC
using MonoTouch.UIKit;
#endif
#endif

namespace MonoMac.CoreMedia {

	public enum CMSampleBufferError {
		None							= 0,
		AllocationFailed				= -12730,
		RequiredParameterMissing		= -12731,
		AlreadyHasDataBuffer			= -12732,
		BufferNotReady					= -12733,
		SampleIndexOutOfRange			= -12734,
		BufferHasNoSampleSizes			= -12735,
		BufferHasNoSampleTimingInfo		= -12736,
		ArrayTooSmall					= -12737,
		InvalidEntryCount				= -12738,
		CannotSubdivide					= -12739,
		SampleTimingInfoInvalid			= -12740,
		InvalidMediaTypeForOperation	= -12741,
		InvalidSampleData				= -12742,
		InvalidMediaFormat				= -12743,
		Invalidated						= -12744,
	}

	[Since (4,0)]
	public class CMSampleBuffer : INativeObject, IDisposable {
		internal IntPtr handle;

		internal CMSampleBuffer (IntPtr handle)
		{
			this.handle = handle;
		}

		[Preserve (Conditional=true)]
		internal CMSampleBuffer (IntPtr handle, bool owns)
		{
			if (!owns)
				CFObject.CFRetain (handle);

			this.handle = handle;
		}

		~CMSampleBuffer ()
		{
			Dispose (false);
		}

		public void Dispose ()
		{
			Dispose (true);
			GC.SuppressFinalize (this);
		}

		public IntPtr Handle {
			get { return handle; }
		}

		protected virtual void Dispose (bool disposing)
		{
			if (handle != IntPtr.Zero){
				CFObject.CFRelease (handle);
				handle = IntPtr.Zero;
			}
		}

#if !COREBUILD
		[DllImport(Constants.CoreMediaLibrary)]
		extern static CMSampleBufferError CMAudioSampleBufferCreateWithPacketDescriptions (
		   IntPtr allocator,
		   IntPtr dataBuffer,
		   bool dataReady,
		   IntPtr makeDataReadyCallback,
		   IntPtr makeDataReadyRefcon,
		   IntPtr formatDescription,
		   int numSamples,
		   CMTime sbufPTS,
		   AudioStreamPacketDescription[] packetDescriptions,
		   out IntPtr sBufOut);

		public static CMSampleBuffer CreateWithPacketDescriptions (CMBlockBuffer dataBuffer, CMFormatDescription formatDescription, int samplesCount,
			CMTime sampleTimestamp, AudioStreamPacketDescription[] packetDescriptions, out CMSampleBufferError error)
		{
			if (formatDescription == null)
				throw new ArgumentNullException ("formatDescription");
			if (samplesCount <= 0)
				throw new ArgumentOutOfRangeException ("samplesCount");

			IntPtr buffer;
			error = CMAudioSampleBufferCreateWithPacketDescriptions (IntPtr.Zero,
				dataBuffer == null ? IntPtr.Zero : dataBuffer.handle,
				true, IntPtr.Zero, IntPtr.Zero,
				formatDescription.handle,
				samplesCount, sampleTimestamp,
				packetDescriptions,
				out buffer);

			if (error != CMSampleBufferError.None)
				return null;

			return new CMSampleBuffer (buffer, true);
		}
/*
		[DllImport(Constants.CoreMediaLibrary)]
		int CMSampleBufferCallForEachSample (
		   CMSampleBufferRef sbuf,
		   int (*callback)(CMSampleBufferRef sampleBuffer, int index, void *refcon),
		   void *refcon
		);

		[DllImport(Constants.CoreMediaLibrary)]
		int CMSampleBufferCopySampleBufferForRange (
		   CFAllocatorRef allocator,
		   CMSampleBufferRef sbuf,
		   CFRange sampleRange,
		   CMSampleBufferRef *sBufOut
		);

		[DllImport(Constants.CoreMediaLibrary)]
		int CMSampleBufferCreate (
		   CFAllocatorRef allocator,
		   CMBlockBufferRef dataBuffer,
		   Boolean dataReady,
		   CMSampleBufferMakeDataReadyCallback makeDataReadyCallback,
		   void *makeDataReadyRefcon,
		   CMFormatDescriptionRef formatDescription,
		   int numSamples,
		   int numSampleTimingEntries,
		   const CMSampleTimingInfo *sampleTimingArray,
		   int numSampleSizeEntries,
		   const uint *sampleSizeArray,
		   CMSampleBufferRef *sBufOut
		);

		[DllImport(Constants.CoreMediaLibrary)]
		int CMSampleBufferCreateCopy (
		   CFAllocatorRef allocator,
		   CMSampleBufferRef sbuf,
		   CMSampleBufferRef *sbufCopyOut
		);

		[DllImport(Constants.CoreMediaLibrary)]
		int CMSampleBufferCreateCopyWithNewTiming (
		   CFAllocatorRef allocator,
		   CMSampleBufferRef originalSBuf,
		   int numSampleTimingEntries,
		   const CMSampleTimingInfo *sampleTimingArray,
		   CMSampleBufferRef *sBufCopyOut
		);*/

		[DllImport(Constants.CoreMediaLibrary)]
		static extern CMSampleBufferError CMSampleBufferCreateForImageBuffer (IntPtr allocator,
		   IntPtr imageBuffer, bool dataReady,
		   IntPtr makeDataReadyCallback, IntPtr makeDataReadyRefcon,
		   IntPtr formatDescription,
		   ref CMSampleTimingInfo sampleTiming,
		   out IntPtr bufOut
		);

		public static CMSampleBuffer CreateForImageBuffer (CVImageBuffer imageBuffer, bool dataReady, CMVideoFormatDescription formatDescription, CMSampleTimingInfo sampleTiming, out CMSampleBufferError error)
		{
			if (imageBuffer == null)
				throw new ArgumentNullException ("imageBuffer");
			if (formatDescription == null)
				throw new ArgumentNullException ("formatDescription");

			IntPtr buffer;
			error = CMSampleBufferCreateForImageBuffer (IntPtr.Zero,
				imageBuffer.handle, dataReady,
				IntPtr.Zero, IntPtr.Zero,
				formatDescription.handle,
				ref sampleTiming,
				out buffer);

			if (error != CMSampleBufferError.None)
				return null;

			return new CMSampleBuffer (buffer, true);
		}
#endif
		[DllImport(Constants.CoreMediaLibrary)]
		extern static bool CMSampleBufferDataIsReady (IntPtr handle);

		public bool DataIsReady
		{
			get
			{
				return CMSampleBufferDataIsReady (handle);
			}
		}

		/*[DllImport(Constants.CoreMediaLibrary)]
		int CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer (
		   CMSampleBufferRef sbuf,
		   uint *bufferListSizeNeededOut,
		   AudioBufferList *bufferListOut,
		   uint bufferListSize,
		   CFAllocatorRef bbufStructAllocator,
		   CFAllocatorRef bbufMemoryAllocator,
		   uint32_t flags,
		   CMBlockBufferRef *blockBufferOut
		);

		[DllImport(Constants.CoreMediaLibrary)]
		int CMSampleBufferGetAudioStreamPacketDescriptions (
		   CMSampleBufferRef sbuf,
		   uint packetDescriptionsSize,
		   AudioStreamPacketDescription *packetDescriptionsOut,
		   uint *packetDescriptionsSizeNeededOut
		);

		[DllImport(Constants.CoreMediaLibrary)]
		int CMSampleBufferGetAudioStreamPacketDescriptionsPtr (
		   CMSampleBufferRef sbuf,
		   const AudioStreamPacketDescription **packetDescriptionsPtrOut,
		   uint *packetDescriptionsSizeOut
		);*/

		[DllImport(Constants.CoreMediaLibrary)]
		extern static IntPtr CMSampleBufferGetDataBuffer (IntPtr handle);

		public CMBlockBuffer GetDataBuffer ()
		{
			var blockHandle = CMSampleBufferGetDataBuffer (handle);
			if (blockHandle == IntPtr.Zero)
			{
				return null;
			}
			else
			{
				return new CMBlockBuffer (blockHandle, false);
			}
		}

		[DllImport(Constants.CoreMediaLibrary)]
		extern static CMTime CMSampleBufferGetDecodeTimeStamp (IntPtr handle);

		public CMTime DecodeTimeStamp
		{
			get
			{
				return CMSampleBufferGetDecodeTimeStamp (handle);
			}
		}

		[DllImport(Constants.CoreMediaLibrary)]
		extern static CMTime CMSampleBufferGetDuration (IntPtr handle);

		public CMTime Duration
		{
			get
			{
				return CMSampleBufferGetDuration (handle);
			}
		}

		[DllImport(Constants.CoreMediaLibrary)]
		extern static IntPtr CMSampleBufferGetFormatDescription (IntPtr handle);

		[Obsolete ("Use GetAudioFormatDescription or GetVideoFormatDescription")]
		public CMFormatDescription GetFormatDescription ()
		{
			var desc = default(CMFormatDescription);
			var descHandle = CMSampleBufferGetFormatDescription (handle);
			if (descHandle != IntPtr.Zero)
			{
				desc = new CMFormatDescription (descHandle, false);
			}
			return desc;
		}

		public CMAudioFormatDescription GetAudioFormatDescription ()
		{
			var descHandle = CMSampleBufferGetFormatDescription (handle);
			if (descHandle == IntPtr.Zero)
				return null;

			return new CMAudioFormatDescription (descHandle, false);
		}

		public CMVideoFormatDescription GetVideoFormatDescription ()
		{
			var descHandle = CMSampleBufferGetFormatDescription (handle);
			if (descHandle == IntPtr.Zero)
				return null;

			return new CMVideoFormatDescription (descHandle, false);
		}

#if !COREBUILD

		[DllImport(Constants.CoreMediaLibrary)]
		extern static IntPtr CMSampleBufferGetImageBuffer (IntPtr handle);

		public CVImageBuffer GetImageBuffer ()
		{
			IntPtr ib = CMSampleBufferGetImageBuffer (handle);
			if (ib == IntPtr.Zero)
				return null;

			var ibt = CFType.GetTypeID (ib);
			if (ibt == CVPixelBuffer.CVImageBufferType)
				return new CVPixelBuffer (ib, false);
			return new CVImageBuffer (ib, false);
		}

#endif

		[DllImport(Constants.CoreMediaLibrary)]
		extern static int CMSampleBufferGetNumSamples (IntPtr handle);

		public int NumSamples
		{
			get
			{
				return CMSampleBufferGetNumSamples (handle);
			}
		}

		[DllImport(Constants.CoreMediaLibrary)]
		extern static CMTime CMSampleBufferGetOutputDecodeTimeStamp (IntPtr handle);

		public CMTime OutputDecodeTimeStamp
		{
			get
			{
				return CMSampleBufferGetOutputDecodeTimeStamp (handle);
			}
		}

		[DllImport(Constants.CoreMediaLibrary)]
		extern static CMTime CMSampleBufferGetOutputDuration (IntPtr handle);

		public CMTime OutputDuration
		{
			get
			{
				return CMSampleBufferGetOutputDuration (handle);
			}
		}

		[DllImport(Constants.CoreMediaLibrary)]
		extern static CMTime CMSampleBufferGetOutputPresentationTimeStamp (IntPtr handle);

		public CMTime OutputPresentationTimeStamp
		{
			get
			{
				return CMSampleBufferGetOutputPresentationTimeStamp (handle);
			}
		}

		[DllImport(Constants.CoreMediaLibrary)]
		extern static CMSampleBufferError CMSampleBufferSetOutputPresentationTimeStamp (IntPtr handle, CMTime outputPresentationTimeStamp);

		public int /*CMSampleBufferError*/ SetOutputPresentationTimeStamp (CMTime outputPresentationTimeStamp)
		{
			return (int)CMSampleBufferSetOutputPresentationTimeStamp (handle, outputPresentationTimeStamp);
		}

		/*[DllImport(Constants.CoreMediaLibrary)]
		int CMSampleBufferGetOutputSampleTimingInfoArray (
		   CMSampleBufferRef sbuf,
		   int timingArrayEntries,
		   CMSampleTimingInfo *timingArrayOut,
		   int *timingArrayEntriesNeededOut
		);*/

		[DllImport(Constants.CoreMediaLibrary)]
		extern static CMTime CMSampleBufferGetPresentationTimeStamp (IntPtr handle);

		public CMTime PresentationTimeStamp
		{
			get
			{
				return CMSampleBufferGetPresentationTimeStamp (handle);
			}
		}

#if !COREBUILD

		[DllImport(Constants.CoreMediaLibrary)]
		extern static IntPtr CMSampleBufferGetSampleAttachmentsArray (IntPtr handle, bool createIfNecessary);

		public CMSampleBufferAttachmentSettings [] GetSampleAttachments (bool createIfNecessary)
		{
			var cfArrayRef = CMSampleBufferGetSampleAttachmentsArray (handle, createIfNecessary);
			if (cfArrayRef == IntPtr.Zero)
			{
				return new CMSampleBufferAttachmentSettings [0];
			}
			else
			{
				return NSArray.ArrayFromHandle (cfArrayRef, h => new CMSampleBufferAttachmentSettings ((NSMutableDictionary) Runtime.GetNSObject (h)));
			}
		}

#endif

		[DllImport(Constants.CoreMediaLibrary)]
		extern static uint CMSampleBufferGetSampleSize (IntPtr handle, int sampleIndex);

		public uint GetSampleSize (int sampleIndex)
		{
			return CMSampleBufferGetSampleSize (handle, sampleIndex);
		}

		/*[DllImport(Constants.CoreMediaLibrary)]
		int CMSampleBufferGetSampleSizeArray (
		   CMSampleBufferRef sbuf,
		   int sizeArrayEntries,
		   uint *sizeArrayOut,
		   int *sizeArrayEntriesNeededOut
		);

		[DllImport(Constants.CoreMediaLibrary)]
		int CMSampleBufferGetSampleTimingInfo (
		   CMSampleBufferRef sbuf,
		   int sampleIndex,
		   CMSampleTimingInfo *timingInfoOut
		);

		[DllImport(Constants.CoreMediaLibrary)]
		int CMSampleBufferGetSampleTimingInfoArray (
		   CMSampleBufferRef sbuf,
		   int timingArrayEntries,
		   CMSampleTimingInfo *timingArrayOut,
		   int *timingArrayEntriesNeededOut
		);*/

		[DllImport(Constants.CoreMediaLibrary)]
		extern static uint CMSampleBufferGetTotalSampleSize (IntPtr handle);

		public uint TotalSampleSize
		{
			get
			{
				return CMSampleBufferGetTotalSampleSize (handle);
			}
		}

		[DllImport(Constants.CoreMediaLibrary)]
		extern static int CMSampleBufferGetTypeID ();

		public static int GetTypeID ()
		{
			return CMSampleBufferGetTypeID ();
		}

		[DllImport(Constants.CoreMediaLibrary)]
		extern static CMSampleBufferError CMSampleBufferInvalidate (IntPtr handle);

		public int /*CMSampleBufferError*/ Invalidate()
		{
			return (int)CMSampleBufferInvalidate (handle);
		}

		[DllImport(Constants.CoreMediaLibrary)]
		extern static bool CMSampleBufferIsValid (IntPtr handle);

		public bool IsValid
		{
			get
			{
				return CMSampleBufferIsValid (handle);
			}
		}

		[DllImport(Constants.CoreMediaLibrary)]
		extern static CMSampleBufferError CMSampleBufferMakeDataReady (IntPtr handle);

		public int /*CMSampleBufferError*/ MakeDataReady ()
		{
			return (int)CMSampleBufferMakeDataReady (handle);
		}

		[DllImport(Constants.CoreMediaLibrary)]
		extern static CMSampleBufferError CMSampleBufferSetDataBuffer (IntPtr handle, IntPtr dataBufferHandle);

		public int /*CMSampleBufferError*/ SetDataBuffer (CMBlockBuffer dataBuffer)
		{
			var dataBufferHandle = IntPtr.Zero;
			if (dataBuffer != null)
			{
				dataBufferHandle = dataBuffer.handle;
			}
			return (int)CMSampleBufferSetDataBuffer (handle, dataBufferHandle);
		}

		/*[DllImport(Constants.CoreMediaLibrary)]
		int CMSampleBufferSetDataBufferFromAudioBufferList (
		   CMSampleBufferRef sbuf,
		   CFAllocatorRef bbufStructAllocator,
		   CFAllocatorRef bbufMemoryAllocator,
		   uint32_t flags,
		   const AudioBufferList *bufferList
		);*/

		[DllImport(Constants.CoreMediaLibrary)]
		extern static CMSampleBufferError CMSampleBufferSetDataReady (IntPtr handle);

		public int/*CMSampleBufferError*/ SetDataReady ()
		{
			return (int)CMSampleBufferSetDataReady (handle);
		}

		/*[DllImport(Constants.CoreMediaLibrary)]
		int CMSampleBufferSetInvalidateCallback (
		   CMSampleBufferRef sbuf,
		   CMSampleBufferInvalidateCallback invalidateCallback,
		   uint64_t invalidateRefCon
		);*/

		[DllImport(Constants.CoreMediaLibrary)]
		extern static CMSampleBufferError CMSampleBufferTrackDataReadiness (IntPtr handle, IntPtr handleToTrack);

		public int/*CMSampleBufferError*/ TrackDataReadiness (CMSampleBuffer bufferToTrack)
		{
			var handleToTrack = IntPtr.Zero;
			if (bufferToTrack != null) {
				handleToTrack = bufferToTrack.handle;
			}
			return (int)CMSampleBufferTrackDataReadiness (handle, handleToTrack);
		}

	}

#if !COREBUILD
	public class CMSampleBufferAttachmentSettings : DictionaryContainer
	{
		static class Selectors
		{
			public static readonly NSString NotSync;
			public static readonly NSString PartialSync;
			public static readonly NSString HasRedundantCoding;
			public static readonly NSString IsDependedOnByOthers;
			public static readonly NSString DependsOnOthers;
			public static readonly NSString EarlierDisplayTimesAllowed;
			public static readonly NSString DisplayImmediately;
			public static readonly NSString DoNotDisplay;
			public static readonly NSString ResetDecoderBeforeDecoding;
			public static readonly NSString DrainAfterDecoding;
			public static readonly NSString PostNotificationWhenConsumed;
			public static readonly NSString ResumeOutput;
			public static readonly NSString TransitionID;
			public static readonly NSString TrimDurationAtStart;
			public static readonly NSString TrimDurationAtEnd;
			public static readonly NSString SpeedMultiplier;
			public static readonly NSString Reverse;
			public static readonly NSString FillDiscontinuitiesWithSilence;
			public static readonly NSString EmptyMedia;
			public static readonly NSString PermanentEmptyMedia;
			public static readonly NSString DisplayEmptyMediaImmediately;
			public static readonly NSString EndsPreviousSampleDuration;
			public static readonly NSString SampleReferenceURL;
			public static readonly NSString SampleReferenceByteOffset;
			public static readonly NSString GradualDecoderRefresh;
			// Since 6,0
			public static readonly NSString DroppedFrameReason;

			static Selectors ()
			{
				var handle = Dlfcn.dlopen (Constants.CoreMediaLibrary, 0);
				if (handle == IntPtr.Zero)
					return;
				try {
					NotSync    	= Dlfcn.GetStringConstant (handle, "kCMSampleAttachmentKey_NotSync");
					PartialSync = Dlfcn.GetStringConstant (handle, "kCMSampleAttachmentKey_PartialSync");
					HasRedundantCoding    		= Dlfcn.GetStringConstant (handle, "kCMSampleAttachmentKey_HasRedundantCoding");
					IsDependedOnByOthers		= Dlfcn.GetStringConstant (handle, "kCMSampleAttachmentKey_IsDependedOnByOthers");
					DependsOnOthers				= Dlfcn.GetStringConstant (handle, "kCMSampleAttachmentKey_DependsOnOthers");
					EarlierDisplayTimesAllowed	= Dlfcn.GetStringConstant (handle, "kCMSampleAttachmentKey_EarlierDisplayTimesAllowed");
					DisplayImmediately			= Dlfcn.GetStringConstant (handle, "kCMSampleAttachmentKey_DisplayImmediately");
					DoNotDisplay				= Dlfcn.GetStringConstant (handle, "kCMSampleAttachmentKey_DoNotDisplay");
					ResetDecoderBeforeDecoding	= Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_ResetDecoderBeforeDecoding");
					DrainAfterDecoding			= Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_DrainAfterDecoding");
					PostNotificationWhenConsumed	= Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_PostNotificationWhenConsumed");
					ResumeOutput				= Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_ResumeOutput");
					TransitionID				= Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_TransitionID");
					TrimDurationAtStart			= Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_TrimDurationAtStart");
					TrimDurationAtEnd			= Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_TrimDurationAtEnd");
					SpeedMultiplier				= Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_SpeedMultiplier");
					Reverse						= Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_Reverse");
					FillDiscontinuitiesWithSilence	= Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_FillDiscontinuitiesWithSilence");
					EmptyMedia					= Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_EmptyMedia");
					PermanentEmptyMedia			= Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_PermanentEmptyMedia");

					DisplayEmptyMediaImmediately	= Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_DisplayEmptyMediaImmediately");
					EndsPreviousSampleDuration	= Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_EndsPreviousSampleDuration");
					SampleReferenceURL			= Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_SampleReferenceURL");
					SampleReferenceByteOffset	= Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_SampleReferenceByteOffset");
					GradualDecoderRefresh		= Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_GradualDecoderRefresh");
#if !MONOMAC
					var version = new Version (UIDevice.CurrentDevice.SystemVersion);
					if (version.Major >= 6) {
						DroppedFrameReason		= Dlfcn.GetStringConstant (handle, "kCMSampleBufferAttachmentKey_DroppedFrameReason");
					}
#endif
				} finally {
					Dlfcn.dlclose (handle);
				}
			}
		}

		internal CMSampleBufferAttachmentSettings (NSMutableDictionary dictionary)
			: base (dictionary)
		{
		}

		public bool? NotSync {
			get {
				return GetBoolValue (Selectors.NotSync);
			}
			set {
				SetBooleanValue (Selectors.NotSync, value);
			}
		}

		public bool? PartialSync {
			get {
				return GetBoolValue (Selectors.PartialSync);
			}
			set {
				SetBooleanValue (Selectors.PartialSync, value);
			}
		}

		public bool? RedundantCoding {
			get {
				return GetBoolValue (Selectors.HasRedundantCoding);
			}
			set {
				SetBooleanValue (Selectors.HasRedundantCoding, value);
			}
		}

		public bool? DependedOnByOthers {
			get {
				return GetBoolValue (Selectors.IsDependedOnByOthers);
			}
			set {
				SetBooleanValue (Selectors.IsDependedOnByOthers, value);
			}
		}

		public bool? DependsOnOthers {
			get {
				return GetBoolValue (Selectors.DependsOnOthers);
			}
			set {
				SetBooleanValue (Selectors.DependsOnOthers, value);
			}
		}

		public bool? EarlierDisplayTimesAllowed {
			get {
				return GetBoolValue (Selectors.EarlierDisplayTimesAllowed);
			}
			set {
				SetBooleanValue (Selectors.EarlierDisplayTimesAllowed, value);
			}
		}

		public bool? DisplayImmediately {
			get {
				return GetBoolValue (Selectors.DisplayImmediately);
			}
			set {
				SetBooleanValue (Selectors.DisplayImmediately, value);
			}
		}

		public bool? DoNotDisplay {
			get {
				return GetBoolValue (Selectors.DoNotDisplay);
			}
			set {
				SetBooleanValue (Selectors.DoNotDisplay, value);
			}
		}

		public bool? ResetDecoderBeforeDecoding {
			get {
				return GetBoolValue (Selectors.ResetDecoderBeforeDecoding);
			}
			set {
				SetBooleanValue (Selectors.ResetDecoderBeforeDecoding, value);
			}
		}

		public bool? DrainAfterDecoding {
			get {
				return GetBoolValue (Selectors.DrainAfterDecoding);
			}
			set {
				SetBooleanValue (Selectors.DrainAfterDecoding, value);
			}
		}

		public bool? Reverse {
			get {
				return GetBoolValue (Selectors.Reverse);
			}
			set {
				SetBooleanValue (Selectors.Reverse, value);
			}
		}

		public bool? FillDiscontinuitiesWithSilence {
			get {
				return GetBoolValue (Selectors.FillDiscontinuitiesWithSilence);
			}
			set {
				SetBooleanValue (Selectors.FillDiscontinuitiesWithSilence, value);
			}
		}

		public bool? EmptyMedia {
			get {
				return GetBoolValue (Selectors.EmptyMedia);
			}
			set {
				SetBooleanValue (Selectors.EmptyMedia, value);
			}
		}

		public bool? PermanentEmptyMedia {
			get {
				return GetBoolValue (Selectors.PermanentEmptyMedia);
			}
			set {
				SetBooleanValue (Selectors.PermanentEmptyMedia, value);
			}
		}

		public bool? DisplayEmptyMediaImmediately {
			get {
				return GetBoolValue (Selectors.DisplayEmptyMediaImmediately);
			}
			set {
				SetBooleanValue (Selectors.DisplayEmptyMediaImmediately, value);
			}
		}

		public bool? EndsPreviousSampleDuration {
			get {
				return GetBoolValue (Selectors.EndsPreviousSampleDuration);
			}
			set {
				SetBooleanValue (Selectors.EndsPreviousSampleDuration, value);
			}
		}

		[Since (6,0)]
		public string DroppedFrameReason {
			get {
				return GetStringValue (Selectors.DroppedFrameReason);
			}
		}

		// TODO: Implement remaining selector properties
		// PostNotificationWhenConsumed
		// ResumeOutput
		// TransitionID
		// TrimDurationAtStart
		// TrimDurationAtEnd
		// SpeedMultiplier
		// SampleReferenceURL
		// SampleReferenceByteOffset
		// GradualDecoderRefresh
	}
#endif
}


text:
import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {Card, RaisedButton, TextField} from 'material-ui';
import {push} from 'react-router-redux';

// our packages
import {createClassAction} from '../../store/actions';

const mapDispatchToProps = dispatch => ({
  navToRoot: () => dispatch(push('/')),
  onCreateClick: params => dispatch(createClassAction(params)),
});

const CreateClassroom = ({navToRoot, onCreateClick}) => {
  let nameInput;
  let descriptionInput;

  const handleClick = (e) => {
    e.preventDefault();
    onCreateClick({
      name: nameInput.getValue(),
      description: descriptionInput.getValue(),
    });
    navToRoot();
  };

  return (

      <Card className="containerPaper">

{'Create new Klayas classroom'}

        <form>

              <TextField
                hintText="Classroom name"
                floatingLabelText="Classroom name"
                ref={(i) => { nameInput = i; }}
              />

              <TextField
                hintText="Describe your classroom"
                floatingLabelText="Description"
                ref={(i) => { descriptionInput = i; }}
              />

              <RaisedButton label="Create" primary onTouchTap={handleClick} fullWidth />

        </form>
      </Card>

  );
};

CreateClassroom.propTypes = {
  navToRoot: PropTypes.func,
  onCreateClick: PropTypes.func,
};

export default connect(null, mapDispatchToProps)(CreateClassroom);


text:
package org.onosproject.ovsdb.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.onosproject.net.behaviour.BridgeDescription;
import org.onosproject.net.behaviour.BridgeDescription.FailMode;
import org.onosproject.net.behaviour.ControllerInfo;

import static com.google.common.base.MoreObjects.toStringHelper;
import static org.onosproject.ovsdb.controller.OvsdbConstant.DATAPATH_ID;
import static org.onosproject.ovsdb.controller.OvsdbConstant.DISABLE_INBAND;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * The class representing an OVSDB bridge.
 * This class is immutable.
 */
public final class OvsdbBridge {

    private final String name;

    /* OpenFlow properties */
    private final Optional<FailMode> failMode;
    private final List<ControllerInfo> controllers;

    /* Adds more properties */
    private final Optional<String> datapathType;

    /* other optional configs */
    private final Map<String, String> otherConfigs;

    /**
     * Default constructor.
     *
     * @param name name of the bridge
     * @param failMode openflow controller fail mode policy
     * @param controllers list of openflow controllers
     * @param datapathType ovs datapath_type
     * @param otherConfigs other configs
     */
    private OvsdbBridge(String name, Optional<FailMode> failMode,
                       List<ControllerInfo> controllers,
                       Optional<String> datapathType,
                       Map<String, String> otherConfigs) {
        this.name = checkNotNull(name);
        this.failMode = failMode;
        this.controllers = controllers;
        this.datapathType = datapathType;
        this.otherConfigs = otherConfigs;
    }

    /**
     * Gets the bridge name of bridge.
     *
     * @return the bridge name of bridge
     */
    public String name() {
        return name;
    }

    /**
     * Returns the controllers of the bridge.
     *
     * @return list of controllers
     */
    public List<ControllerInfo> controllers() {
        return controllers;
    }

    /**
     * Returns fail mode of the bridge.
     *
     * @return fail mode
     */
    public Optional<FailMode> failMode() {
        return failMode;
    }

    /**
     * Returns OVSDB datapath Type of the bridge.
     *
     * @return datapath type
     */
    public Optional<String> datapathType() {
        return datapathType;
    }

    /**
     * Returns other configurations of the bridge.
     *
     * @return map of configurations
     */
    public Map<String, String> otherConfigs() {
        return otherConfigs;
    }

    /**
     * Gets the datapathId of bridge.
     *
     * @return datapath id; null if not used
     */
    public Optional<String> datapathId() {
        return Optional.ofNullable(otherConfigs.get(DATAPATH_ID));
    }

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

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof OvsdbBridge) {
            final OvsdbBridge otherOvsdbBridge = (OvsdbBridge) obj;
            return Objects.equals(this.name, otherOvsdbBridge.name);
        }
        return false;
    }

    @Override
    public String toString() {
        return toStringHelper(this)
                .add("bridgeName", name)
                .add("failMode", failMode)
                .add("controllers", controllers)
                .add("datapathType", datapathType)
                .add("otherConfigs", otherConfigs)
                .toString();
    }

    /**
     * Returns a new builder instance.
     *
     * @return ovsdb bridge builder
     */
    public static OvsdbBridge.Builder builder() {
        return new Builder();
    }

    /**
     * Returns OVSDB bridge object with a given bridge description.
     *
     * @param bridgeDesc bridge description
     * @return ovsdb bridge
     */
    public static OvsdbBridge.Builder builder(BridgeDescription bridgeDesc) {
        return new Builder(bridgeDesc);
    }

    /**
     * Builder of OVSDB bridge entities.
     */
    public static final class Builder {
        private String name;
        private Optional<FailMode> failMode = Optional.empty();
        private List<ControllerInfo> controllers = Lists.newArrayList();
        private Optional<String> datapathType = Optional.empty();
        private Map<String, String> otherConfigs = Maps.newHashMap();

        private Builder() {
        }

        /**
         * Constructs OVSDB bridge builder with a given bridge description.
         *
         * @param bridgeDesc bridge description
         */
        private Builder(BridgeDescription bridgeDesc) {
            if (bridgeDesc.datapathId().isPresent()) {
                otherConfigs.put(DATAPATH_ID, bridgeDesc.datapathId().get());
            }
            if (bridgeDesc.disableInBand().isPresent()) {
                otherConfigs.put(DISABLE_INBAND,
                                 bridgeDesc.disableInBand().get().toString());
            }
            if (bridgeDesc.datapathType().isPresent()) {
                this.datapathType = bridgeDesc.datapathType();
            }
            this.name = bridgeDesc.name();
            this.failMode = bridgeDesc.failMode();
            this.controllers = Lists.newArrayList(bridgeDesc.controllers());
        }

        /**
         * Builds an immutable OVSDB bridge.
         *
         * @return ovsdb bridge
         */
        public OvsdbBridge build() {
            return new OvsdbBridge(name, failMode, controllers, datapathType, otherConfigs);
        }

        /**
         * Returns OVSDB bridge builder with a given name.
         *
         * @param name name of the bridge
         * @return ovsdb bridge builder
         */
        public Builder name(String name) {
            this.name = name;
            return this;
        }

        /**
         * Returns OVSDB bridge builder with a given fail mode.
         *
         * @param failMode fail mode
         * @return ovsdb bridge builder
         */
        public Builder failMode(FailMode failMode) {
            this.failMode = Optional.ofNullable(failMode);
            return this;
        }

        /**
         * Returns OVSDB bridge builder with given controllers.
         *
         * @param controllers list of controllers
         * @return ovsdb bridge builder
         */
        public Builder controllers(List<ControllerInfo> controllers) {
            this.controllers = Lists.newArrayList(controllers);
            return this;
        }

        /**
         * Returns OVSDB bridge builder with a given controller.
         *
         * @param controller controller
         * @return ovsdb bridge builder
         */
        public Builder controller(ControllerInfo controller) {
            this.controllers = Lists.newArrayList(controller);
            return this;
        }

        /**
         * Returns OVSDB bridge builder with given configs.
         *
         * @param otherConfigs other configs
         * @return ovsdb bridge builder
         */
        public Builder otherConfigs(Map<String, String> otherConfigs) {
            this.otherConfigs = Maps.newHashMap(otherConfigs);
            return this;
        }

        /**
         * Returns OVSDB bridge builder with a given datapath ID.
         *
         * @param datapathId datapath id
         * @return ovsdb bridge builder
         */
        public Builder datapathId(String datapathId) {
            otherConfigs.put(DATAPATH_ID, datapathId);
            return this;
        }

        /**
         * Returns OVSDB bridge builder with a given datapath type.
         *
         * @param datapathType datapath Type
         * @return ovsdb bridge builder
         */
        public Builder datapathType(String datapathType) {
            this.datapathType = Optional.ofNullable(datapathType);
            return this;
        }

        /**
         * Returns OVSDB bridge builder with a given disable in-band config.
         *
         * @return ovsdb bridge builder
         */
        public Builder disableInBand() {
            otherConfigs.put(DATAPATH_ID, Boolean.TRUE.toString());
            return this;
        }
    }
}


text:
package com.example.beer.api;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import com.asarkar.grpc.test.Resources;
import com.example.BeerServiceGrpc;
import com.example.PersonToCheck;
import com.google.protobuf.InvalidProtocolBufferException;
import io.grpc.ManagedChannel;
import io.grpc.Status;
import io.grpc.StatusException;
import io.grpc.StatusRuntimeException;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.RequestBody;

import org.springframework.cloud.contract.verifier.http.HttpVerifier;
import org.springframework.cloud.contract.verifier.http.Request;
import org.springframework.cloud.contract.verifier.http.Response;

/**
 * Example of how you can use the HttpVerifier with stubbed HTTP/2 communication.
 */
public class GrpcStubHttpVerifier implements HttpVerifier {

	private final ManagedChannel channel;

	public GrpcStubHttpVerifier(ManagedChannel channel) {
		this.channel = channel;
	}

	@Override
	public Response exchange(Request request) {
		if (request.path().contains("beer.BeerService/check")) {
			try {
				com.example.Response response = BeerServiceGrpc.newBlockingStub(channel).check(PersonToCheck.parseFrom(request.body().asByteArray()));
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				response.writeTo(stream);
				return Response
						.builder()
						.body(stream.toByteArray())
						.header("Content-Type", "application/grpc")
						.statusCode(200)
						.build();
			}
			catch (IOException e) {
				throw new IllegalStateException(e);
			}
		}
		throw new UnsupportedOperationException("Request with path [" + request.path() + "] is unsupported");
	}
}


text:
module Compass::SassExtensions::Functions::Constants
  if defined?(Sass::Script::List)
    POSITIONS = /top|bottom|left|right|center/
    def is_position(position)
      Sass::Script::Bool.new(position.is_a?(Sass::Script::String) && !!(position.value =~ POSITIONS))
    end
    def is_position_list(position_list)
      Sass::Script::Bool.new(position_list.is_a?(Sass::Script::List) && position_list.value.all?{|p| is_position(p).to_bool})
    end
    # returns the opposite position of a side or corner.
    def opposite_position(position)
      position = unless position.is_a?(Sass::Script::List)
        Sass::Script::List.new([position], :space)
      else
        Sass::Script::List.new(position.value.dup, position.separator)
      end
      position.value.map! do |pos|
        if pos.is_a? Sass::Script::String
          opposite = case pos.value
          when "top" then "bottom"
          when "bottom" then "top"
          when "left" then "right"
          when "right" then "left"
          when "center" then "center"
          else
            Compass::Util.compass_warn("Cannot determine the opposite position of: #{pos}")
            pos.value
          end
          Sass::Script::String.new(opposite)
        elsif pos.is_a? Sass::Script::Number
          if pos.numerator_units == ["%"] && pos.denominator_units == []
            Sass::Script::Number.new(100-pos.value, ["%"])
          else
            Compass::Util.compass_warn("Cannot determine the opposite position of: #{pos}")
            pos
          end
        else
          Compass::Util.compass_warn("Cannot determine the opposite position of: #{pos}")
          pos
        end
      end
      if position.value.size == 1
        position.value.first
      else
        position
      end
    end

    def is_url(string)
      if string.is_a?(Sass::Script::String)
        is_url = !!(string.value =~ /^url\(.*\)$/)
        Sass::Script::Bool.new(is_url)
      else
        Sass::Script::Bool.new(false)
      end
    end
  else
    # returns the opposite position of a side or corner.
    def opposite_position(position)
      opposite = position.value.split(/ +/).map do |pos|
        case pos
        when "top" then "bottom"
        when "bottom" then "top"
        when "left" then "right"
        when "right" then "left"
        when "center" then "center"
        else
          pos
        end
      end
      Sass::Script::String.new(opposite.join(" "), position.type)
    end
  end
end


text:
using System;
using System.Collections;

using MWS.Helper;

namespace MWS.Log
{
    public static class LogFactory
    {
        private static ArrayList _logs;

        static LogFactory()
        {
            Initialize();
        }

        static void Initialize()
        {
            // internal logs
            _logs = new ArrayList();
        }

        public static void RegisterLog(LogInterface log)
        {
            if (!_logs.Contains(log))
            {
                _logs.Add(log);
            }
        }

        public static void WriteInfo(string message)
        {
            WriteInfo(message);
        }

        private static void WriteInfo(DateTime date, string message)
        {
            foreach (LogInterface log in _logs)
            {
                log.WriteInfo(date, message);
            }
        }

        public static void WriteWarning(string message)
        {
            WriteWarning(DateTime.Now, message);
        }

        private static void WriteWarning(DateTime date, string message)
        {
            foreach (LogInterface log in _logs)
            {
                log.WriteWarning(date, message);
            }
        }

        public static void WriteError(string message)
        {
            WriteError(DateTime.Now, message);
        }

        private static void WriteError(DateTime date, string message)
        {
            foreach (LogInterface log in _logs)
            {
                log.WriteError(DateTime.Now, message);
            }
        }

        public static void WriteEntry(MovilizerStatusMessage statusMessage)
        {
            switch (statusMessage.severity)
            {
                case 2: // warning=2
                    WriteWarning(statusMessage.timestamp, statusMessage.message);
                    break;
                case 3:
                case 4: // error=3, fatal=4
                    WriteError(statusMessage.timestamp, statusMessage.message);
                    break;
                default: // debug=-1, info=1
                    WriteInfo(statusMessage.timestamp, statusMessage.message);
                    break;
            }
        }

        public static void WriteEntry(MovilizerMoveletError moveletError)
        {
            WriteError(moveletError.timestamp, moveletError.message);
        }
    }
}


text:
package awt.config;

public class ApplicationConfigTest {

    public void testClasses() {

    }
}


text:
package clusterdesc

import (
	"io/ioutil"
	"path"
	"testing"

	"github.com/topicai/candy"
	"gopkg.in/yaml.v2"
)

func TestGetMasterIP(t *testing.T) {
	c := &Cluster{}

	clusterDescExample, e := ioutil.ReadFile(path.Join(candy.GoPath(), clusterDescExampleFile))
	candy.Must(e)
	candy.Must(yaml.Unmarshal([]byte(clusterDescExample), c))

}


text:
using System.Collections.Generic;
using System.Linq;
using TellagoStudios.Hermes.Client.Util;
using TellagoStudios.Hermes.Facade;

namespace TellagoStudios.Hermes.Client
{
    public class Group : ModelBase
    {
        private readonly Facade.Group @group;
        private readonly RestClient restClient;

        internal Group(Facade.Group group, RestClient restClient)
            : base((string) group.Id)
        {
            this.@group = @group;
            this.restClient = restClient;
        }

        public string Name
        {
            get { return group.Name; }
            set { group.Name = value; }
        }

        public string Description
        {
            get { return group.Description; }
            set { group.Description = value; }
        }

        public Topic CreateTopic(string name, string description = "")
        {
            var topicPost = new TopicPost {Name = name, Description = description, GroupId = (Identity)Id};
            var location = restClient.Post(group.GetLinkForRelation("Create Topic"), topicPost);
            var topicCreated = restClient.Get<Facade.Topic>(location.ToString());

            return new Topic(topicCreated, this, restClient);
        }

        public IEnumerable<Topic> GetTopics()
        {
            var topics = restClient.Get<Facade.Topic[]>(group.GetLinkForRelation("All Topics"));
            return topics.Select(tf => new Topic(tf, this, restClient)).ToList();
        }

        public void Delete()
        {
            restClient.Delete(group.GetLinkForRelation("Delete"));
        }

        public void SaveChanges()
        {
            restClient.Put(group.GetLinkForRelation("Update"),
                new GroupPut
                {
                    Description = Description,
                    Name = Name,
                    Id = (Identity) Id
                });
        }

        public Topic TryCreateTopic(string name, string description = "")
        {
            var topic = restClient.Get<Facade.Topic>(Operations.GetTopic(name, group.Id));
            return topic==null ?
                CreateTopic(name, description) :
                new Topic( topic , restClient);
        }
    }
}


text:
An HTML element's `class` attribute can be bound like any other
attribute:

```handlebars
<div class={{priority}}>
  Warning!
</div>
```

If the component's `priority` property is `"p4"`, this template will emit the following HTML:

```html
<div class="p4">
  Warning!
</div>
```

### Conditonal Values

If you want a class value based on a conditonal property, use the Handlebars `if` helper:

```handlebars
<div class={{if isUrgent 'is-urgent'}}>
  Warning!
</div>
```

If `isUrgent` is true, this emits the following HTML:

```html
<div class="is-urgent">
  Warning!
</div>
```

If `isUrgent` is false, no class name is added:

```html
<div>
  Warning!
</div>
```

You can also specify a class name to add when the property is `false`:

```handlebars
<div class={{if isEnabled 'enabled' 'disabled'}}>
  Warning!
</div>
```

In this case, if the `isEnabled` property is `true`, the `enabled`
class will be added. If the property is `false`, the class `disabled`
will be added.


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>at.ac.big.tuwien.ewa</groupId>
	<artifactId>sample-web-service</artifactId>
	<packaging>jar</packaging>
	<version>1.0.0-SNAPSHOT</version>
	<name>WE Sample Web Service</name>

	<properties>
        <commons-lang-version>2.2</commons-lang-version>
        <commons-logging-version>1.1.3</commons-logging-version>
        <jaxws-version>2.1.7</jaxws-version>
        <joda-version>2.0</joda-version>
        <logback-version>1.1.1</logback-version>
        <slf4j-version>1.7.6</slf4j-version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>

        <!-- Junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>

		<!-- LOGGING DEPENDENCIES -->
        <dependency>
            <!-- We use logback and slf4j, so we exclude commons-logging (define
                it as provided) c.f. http://www.slf4j.org/faq.html#excludingJCL -->
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.3</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
            <version>${slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jul-to-slf4j</artifactId>
            <version>${slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback-version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>${logback-version}</version>
        </dependency>

		<!-- Dependency to JAX-WS -->
		<dependency>
			<groupId>com.sun.xml.ws</groupId>
			<artifactId>jaxws-rt</artifactId>
			<version>${jaxws-version}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>

        <!-- Add JAXB Impl, since otherwise the WebFault does not work.
         cf. http://stackoverflow.com/questions/7232331/unable-to-create-jaxbcontext-creating-my-wsdl -->
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>2.2.6</version>
        </dependency>

		<!-- Joda Time -->
		<dependency>
			<groupId>joda-time</groupId>
			<artifactId>joda-time</artifactId>
			<version>${joda-version}</version>
		</dependency>

		<!-- Apache Commons -->
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>${commons-lang-version}</version>
		</dependency>

	</dependencies>
	<build>

		<finalName>arithmetic-service</finalName>

		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<archive>
						<manifest>
							<mainClass>at.ac.tuwien.big.we.webservice.ArithmeticService</mainClass>
						</manifest>
					</archive>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
				</configuration>
				<executions>
					<execution>
						<id>make-assembly</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

		</plugins>

		<resources>
			<resource>
                <filtering>false</filtering>
				<directory>src/main/java</directory>
				<includes>
					<include>**</include>
				</includes>
				<excludes>
					<exclude>**/*.java</exclude>
				</excludes>
			</resource>
		</resources>

	</build>

</project>


text:
package com.cognizant.cognizantits.datalib.or.web;

import com.cognizant.cognizantits.datalib.component.utils.FileUtils;
import com.cognizant.cognizantits.datalib.or.common.ORPageInf;
import com.cognizant.cognizantits.datalib.or.common.ORUtils;
import com.cognizant.cognizantits.datalib.or.common.ObjectGroup;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties({"root"})
public class WebORPage implements ORPageInf<WebORObject, WebOR> {

    @JacksonXmlProperty(isAttribute = true, localName = "ref")
    private String name;

    @JacksonXmlProperty(isAttribute = true)
    private String title;

    @JacksonXmlProperty(localName = "ObjectGroup")
    @JacksonXmlElementWrapper(useWrapping = false, localName = "ObjectGroup")
    private List<ObjectGroup<WebORObject>> objectGroups;

    @JsonIgnore
    private WebOR root;

    public WebORPage() {
        this.objectGroups = new ArrayList<>();
    }

    public WebORPage(String name, WebOR root) {
        this.name = name;
        this.root = root;
        this.title = "";
        this.objectGroups = new ArrayList<>();
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public List<ObjectGroup<WebORObject>> getObjectGroups() {
        return objectGroups;
    }

    @Override
    public void setObjectGroups(List<ObjectGroup<WebORObject>> objectGroups) {
        this.objectGroups = objectGroups;
        for (ObjectGroup<WebORObject> objectGroup : objectGroups) {
            objectGroup.setParent(this);
        }
    }

    @JsonIgnore
    @Override
    public void removeFromParent() {
        root.setSaved(false);
        root.getPages().remove(this);
        FileUtils.deleteFile(getRepLocation());
    }

    @JsonIgnore
    @Override
    public ObjectGroup<WebORObject> getObjectGroupByName(String groupName) {
        for (ObjectGroup<WebORObject> group : objectGroups) {
            if (group.getName().equalsIgnoreCase(groupName)) {
                return group;
            }
        }
        return null;
    }

    @JsonIgnore
    @Override
    public ObjectGroup<WebORObject> addObjectGroup() {
        String oName = "WObjectGroup";
        int i = 0;
        String objectName;
        do {
            objectName = oName + i++;
        } while (getObjectGroupByName(objectName) != null);

        return addObjectGroup(objectName);
    }

    @JsonIgnore
    @Override
    public ObjectGroup<WebORObject> addObjectGroup(String groupName) {
        if (getObjectGroupByName(groupName) == null) {
            ObjectGroup<WebORObject> group = new ObjectGroup<>(groupName, this);
            objectGroups.add(group);
            new File(group.getRepLocation()).mkdirs();
            group.addObject(groupName);
            root.setSaved(false);
            return group;
        }
        return null;
    }

    @JsonIgnore
    @Override
    public WebORObject getNewObject(String objectName, ObjectGroup<WebORObject> group) {
        return new WebORObject(objectName, group);
    }

    @JsonIgnore
    @Override
    public WebORObject addObject() {
        String oName = "WObject";
        int i = 0;
        String objectName;
        do {
            objectName = oName + i++;
        } while (getObjectGroupByName(objectName) != null);
        return addObject(objectName);
    }

    @JsonIgnore
    @Override
    public WebORObject addObject(String objectName) {
        ObjectGroup<WebORObject> group = addObjectGroup(objectName);
        if (group != null) {
            return group.getObjects().get(0);
        }
        return null;
    }

    @JsonIgnore
    @Override
    public void deleteObjectGroup(String groupName) {
        ObjectGroup<WebORObject> group = getObjectGroupByName(groupName);
        if (group != null) {
            objectGroups.remove(group);
            root.setSaved(false);
        }
    }

    @JsonIgnore
    @Override
    public TreeNode getChildAt(int i) {
        if (objectGroups.get(i).getChildCount() > 1) {
            return objectGroups.get(i);
        }
        return objectGroups.get(i).getChildAt(0);
    }

    @JsonIgnore
    @Override
    public int getChildCount() {
        return objectGroups == null ? 0
                : objectGroups.size();
    }

    @JsonIgnore
    @Override
    public WebOR getParent() {
        return root;
    }

    @JsonIgnore
    @Override
    public int getIndex(TreeNode tn) {
        return objectGroups.indexOf(tn);
    }

    @JsonIgnore
    @Override
    public boolean getAllowsChildren() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isLeaf() {
        return getChildCount() == 0;
    }

    @JsonIgnore
    @Override
    public Enumeration children() {
        return Collections.enumeration(objectGroups);
    }

    @JsonIgnore
    @Override
    public WebOR getRoot() {
        return root;
    }

    @JsonIgnore
    @Override
    public void setRoot(WebOR root) {
        this.root = root;
    }

    @Override
    public String toString() {
        return name;
    }

    @JsonIgnore
    @Override
    public TreeNode[] getPath() {
        return (TreeNode[]) ORUtils.getPath(this).getPath();
    }

    @JsonIgnore
    @Override
    public TreePath getTreePath() {
        return ORUtils.getPath(this);
    }

    @Override
    public Boolean rename(String newName) {
        if (getParent().getPageByName(newName) == null) {
            if (FileUtils.renameFile(getRepLocation(), newName)) {
                getRoot().getObjectRepository().renamePage(this, newName);
                setName(newName);
                getParent().setSaved(false);
                return true;
            }
        }
        return false;
    }

    @JsonIgnore
    @Override
    public String getRepLocation() {
        return getParent().getRepLocation() + File.separator + getName();
    }

    @JsonIgnore
    @Override
    public void sort() {
        ORUtils.sort(this);
    }
}


text:
SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"
BASEDIR=${SCRIPTPATH%/*}

# Create fresh db, load fixtures in an order that works

read -p "About to blow away DB - answer Y to go ahead, ^C to cancel> "
case $REPLY in
  Y*) ;;
  *)
   echo "Cancelling (try capital Y if you meant to go ahead)"
   exit 1
  ;;
esac

python ${BASEDIR}/manage.py syncdb --noinput
python ${BASEDIR}/manage.py migrate

python ${BASEDIR}/manage.py loaddata \
  ${BASEDIR}/fixtures/auth_user.json \
  ${BASEDIR}/fixtures/conference.json \
  ${BASEDIR}/fixtures/database_constance.json \
  ${BASEDIR}/fixtures/boxes.json \
  ${BASEDIR}/fixtures/proposals.json \
  ${BASEDIR}/fixtures/sitetree.json \
  ${BASEDIR}/fixtures/sotmjp.json \
  ${BASEDIR}/fixtures/sponsorship.json \
  ${BASEDIR}/fixtures/schedule.json \
  ${BASEDIR}/fixtures/teams.json \
  ${BASEDIR}/fixtures/restcms_page.json \

echo
echo
echo "Database initialized."
echo "Hint: setup an account with: ./manage.py createsuperuser"


text:
{{<layout}}

{{$pageTitle}} Do you experience severe slowing up (off periods of freezing)? {{/pageTitle}}

{{$head}}
	{{>includes/head}}
	{{>includes/scripts}}
{{/head}}

{{$content}}
{{>includes/buttons/standard-back-phase-banner}}

 Do you experience severe slowing up (off periods or freezing)?

			<form class="form">

					{{>includes/errors/error-message}}

					<fieldset class="inline">
						<legend class="visuallyhidden"> Do you experience severe slowing up (off periods or freezing)? </legend>

							<input id="PK3-a1" type="radio" name="PK3" value="Y"> Yes

							<input id="PK3-a2" type="radio" name="PK3" value="N"> No

					</fieldset>

				{{>includes/buttons/continue-validation}}
			</form>

		{{>includes/widgets/need-help}}

{{/content}}

{{/layout}}


text:
if (process.env.NODE_ENV !== 'production') {
	const path = require('path');
	require('dotenv').config({ path: path.join(__dirname, '.env') });
}

const path = require('path');
const express = require('express');
const http = require('http');
const app = express();
const server = http.Server(app);
const io = require('socket.io')(server);
const secure = require('ssl-express-www');

const PORT = process.env.PORT || 3000;

if (process.env.NODE_ENV === 'production') {
	app.use(secure);
	app.use(express.static(path.join(__dirname, '../', 'dist')));

	app.get('/', (req, res) => {
		res.sendFile(path.join(__dirname, '../', 'dist/index.html'));
	});
}

server.listen(PORT, () => console.log(`Listening on *:${PORT}`));

io.use((socket, next) => {
	const token = socket.handshake.query.token;
	if (isValid(token)) {
		return next();
	}
	return next(new Error('authentication error'));
});

io.on('connection', (socket) => require('./socket')(io, socket));

function isValid(token) {
	return token === process.env.TOKEN_SECRET;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<ti:app xmlns:ti="http://ti.appcelerator.org">
<id>com.scriptprojects.picbook</id>
<name>PicBook</name>
<version>2</version>
<publisher>ScriptProjects.com</publisher>
<url>http://scriptprojects.com/</url>
<description>View a slideshow of your Facebook pictures on your mobile device.</description>
<copyright>2010 by ScriptProjects.com</copyright>
<icon>default_app_logo.png</icon>
    <persistent-wifi>false</persistent-wifi>
    <prerendered-icon>false</prerendered-icon>
    <statusbar-style>default</statusbar-style>
    <statusbar-hidden>false</statusbar-hidden>
    <fullscreen>false</fullscreen>
    <navbar-hidden>false</navbar-hidden>
    <analytics>true</analytics>
<guid>e9138eec-af26-43fe-b311-b0b08fce9261</guid>
<iphone>
		<orientations device="iphone">
			<orientation>Ti.UI.PORTRAIT</orientation>
		</orientations>
		<orientations device="ipad">
			<orientation>Ti.UI.PORTRAIT</orientation>
			<orientation>Ti.UI.UPSIDE_PORTRAIT</orientation>
			<orientation>Ti.UI.LANDSCAPE_LEFT</orientation>
			<orientation>Ti.UI.LANDSCAPE_RIGHT</orientation>
		</orientations>
	</iphone>
<modules>
    <module version="0.1">com.scriptprojects.hacks</module>
</modules>
<android xmlns:android="http://schemas.android.com/apk/res/android">
		<manifest>
			<uses-permission android:name="android.permission.WAKE_LOCK" />
		</manifest>
 	</android>

</ti:app>


text:
package org.camunda.bpm.elasticsearch.util;

import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;

import java.io.IOException;
import java.util.Map;
import java.util.logging.Logger;

public class ElasticSearchHelper {

  protected static final Logger LOGGER = Logger.getLogger(ElasticSearchHelper.class.getName());

  public static void checkIndex(Client esClient, String indexName) {
    if (!checkIndexExists(esClient, indexName)) {
      if (createIndex(esClient, indexName)) {
        LOGGER.info("Index [" + indexName + "] not found. Creating new index [" + indexName + "]");
      } else {
        throw new RuntimeException("Unable to create index [" + indexName + "] in Elasticsearch.");
      }
    } else {
      LOGGER.info("Index [" + indexName + "] already exists in Elasticsearch.");
    }
  }

  public static boolean createIndex(Client esClient, String indexName) {
    return esClient.admin().indices().prepareCreate(indexName).get().isAcknowledged();
  }

  public static void checkTypeAndMapping(Client esClient, String indexName, String typeName) {
    Map<String, Object> mapping =
        JsonHelper.readJsonFromClasspathAsMap("mapping/" + typeName + ".json");
    checkTypeAndMapping(esClient, indexName, typeName, mapping);
  }

  public static void checkTypeAndMapping(Client esClient, String indexName, String typeName, Map<String, Object> mapping) {
    if (!checkTypeExists(esClient, indexName, typeName)) {
      if (mapping == null) {
        throw new RuntimeException("No mapping provided.");
      }

      if (updateMappingForType(esClient, indexName, typeName, mapping)) {
        LOGGER.info("Created mapping for [" + indexName + "]/[" + typeName + "]");
      } else {
        throw new RuntimeException("Could not define mapping for ["+ indexName +"]/["+ typeName +"]");
      }
    }
  }

  public static boolean checkIndexExists(Client esClient, String indexName) {
    return esClient.admin().indices().prepareExists(indexName).get().isExists();
  }

  public static boolean checkTypeExists(Client esClient, String index, String type) {
    return esClient.admin().indices().prepareExists(index, type).get().isExists();
  }

  public static boolean updateMappingForType(Client esClient, String indexName, String typeName, Map<String, Object> mapping) {
    return esClient.admin().indices().preparePutMapping(indexName).setType(typeName).setSource(mapping).get().isAcknowledged();
  }

  public static String convertRequestToJson(ActionRequest request) throws IOException {
    BytesStreamOutput bytesStreamOutput = new BytesStreamOutput();
    request.writeTo(bytesStreamOutput);

    XContentBuilder builder = XContentFactory.jsonBuilder(bytesStreamOutput);
    builder.prettyPrint();

//    builder.startObject();
//    builder.endObject();
    BytesArray bytesArray = builder.bytes().toBytesArray();
    return new String(bytesArray.array(), bytesArray.arrayOffset(), bytesArray.length());
  }

  public static String convertResponseToJson(ActionResponse response) throws IOException {
    BytesStreamOutput bytesStreamOutput = new BytesStreamOutput();
    response.writeTo(bytesStreamOutput);

    XContentBuilder builder = XContentFactory.jsonBuilder(bytesStreamOutput);
    builder.prettyPrint();

//    builder.startObject();
//    builder.endObject();
    return builder.bytes().toUtf8();
  }

}


text:
interface JQuery {
    sortElements(comparator:Function, getSortable?:Function):JQuery;
}