text:
package io.aeron;

import io.aeron.driver.MediaDriver;
import io.aeron.driver.ThreadingMode;
import io.aeron.logbuffer.FragmentHandler;
import io.aeron.test.MediaDriverTestWatcher;
import io.aeron.test.TestMediaDriver;
import io.aeron.test.Tests;
import org.agrona.CloseHelper;
import org.agrona.collections.MutableReference;
import org.agrona.concurrent.UnsafeBuffer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.RegisterExtension;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class TwoBufferOfferMessageTest
{
    private static final String CHANNEL = "aeron:ipc?term-length=64k";
    private static final int STREAM_ID = 1001;
    private static final int FRAGMENT_COUNT_LIMIT = 10;

    @RegisterExtension
    public final MediaDriverTestWatcher testWatcher = new MediaDriverTestWatcher();

    private final MediaDriver.Context driverContext = new MediaDriver.Context()
        .errorHandler(Tests::onError)
        .dirDeleteOnStart(true)
        .threadingMode(ThreadingMode.SHARED);

    private final TestMediaDriver driver = TestMediaDriver.launch(driverContext, testWatcher);

    private final Aeron aeron = Aeron.connect();

    @AfterEach
    public void after()
    {
        CloseHelper.closeAll(aeron, driver);
        driver.context().deleteDirectory();
    }

    @Test
    @Timeout(10)
    public void shouldTransferUnfragmentedTwoPartMessage()
    {
        final UnsafeBuffer expectedBuffer = new UnsafeBuffer(new byte[256]);
        final UnsafeBuffer bufferOne = new UnsafeBuffer(expectedBuffer, 0, 32);
        final UnsafeBuffer bufferTwo = new UnsafeBuffer(expectedBuffer, 32, expectedBuffer.capacity() - 32);

        bufferOne.setMemory(0, bufferOne.capacity(), (byte)'a');
        bufferTwo.setMemory(0, bufferTwo.capacity(), (byte)'b');
        final String expectedMessage = expectedBuffer.getStringWithoutLengthAscii(0, expectedBuffer.capacity());

        final MutableReference<String> receivedMessage = new MutableReference<>();
        final FragmentHandler fragmentHandler = (buffer, offset, length, header) ->
            receivedMessage.set(buffer.getStringWithoutLengthAscii(offset, length));

        try (Subscription subscription = aeron.addSubscription(CHANNEL, STREAM_ID))
        {
            try (Publication publication = aeron.addPublication(CHANNEL, STREAM_ID))
            {
                publishMessage(bufferOne, bufferTwo, publication);
                pollForMessage(subscription, receivedMessage, fragmentHandler);

                assertEquals(expectedMessage, receivedMessage.get());
            }

            try (Publication publication = aeron.addExclusivePublication(CHANNEL, STREAM_ID))
            {
                publishMessage(bufferOne, bufferTwo, publication);
                pollForMessage(subscription, receivedMessage, fragmentHandler);

                assertEquals(expectedMessage, receivedMessage.get());
            }
        }
    }

    @Test
    @Timeout(10)
    public void shouldTransferFragmentedTwoPartMessage()
    {
        final UnsafeBuffer expectedBuffer = new UnsafeBuffer(new byte[32 + driver.context().mtuLength()]);
        final UnsafeBuffer bufferOne = new UnsafeBuffer(expectedBuffer, 0, 32);
        final UnsafeBuffer bufferTwo = new UnsafeBuffer(expectedBuffer, 32, expectedBuffer.capacity() - 32);

        bufferOne.setMemory(0, bufferOne.capacity(), (byte)'a');
        bufferTwo.setMemory(0, bufferTwo.capacity(), (byte)'b');
        final String expectedMessage = expectedBuffer.getStringWithoutLengthAscii(0, expectedBuffer.capacity());

        final MutableReference<String> receivedMessage = new MutableReference<>();
        final FragmentHandler fragmentHandler = new FragmentAssembler((buffer, offset, length, header) ->
            receivedMessage.set(buffer.getStringWithoutLengthAscii(offset, length)));

        try (Subscription subscription = aeron.addSubscription(CHANNEL, STREAM_ID))
        {
            try (Publication publication = aeron.addPublication(CHANNEL, STREAM_ID))
            {
                publishMessage(bufferOne, bufferTwo, publication);
                pollForMessage(subscription, receivedMessage, fragmentHandler);

                assertEquals(expectedMessage, receivedMessage.get());
            }

            try (Publication publication = aeron.addExclusivePublication(CHANNEL, STREAM_ID))
            {
                publishMessage(bufferOne, bufferTwo, publication);
                pollForMessage(subscription, receivedMessage, fragmentHandler);

                assertEquals(expectedMessage, receivedMessage.get());
            }
        }
    }

    private static void publishMessage(
        final UnsafeBuffer bufferOne, final UnsafeBuffer bufferTwo, final Publication publication)
    {
        while (publication.offer(bufferOne, 0, bufferOne.capacity(), bufferTwo, 0, bufferTwo.capacity()) < 0L)
        {
            Tests.yield();
        }
    }

    private void pollForMessage(
        final Subscription subscription, final MutableReference<String> receivedMessage, final FragmentHandler handler)
    {
        receivedMessage.set(null);

        while (receivedMessage.get() == null)
        {
            final int fragments = subscription.poll(handler, FRAGMENT_COUNT_LIMIT);
            if (fragments == 0)
            {
                Tests.yield();
            }
        }
    }
}


text:
Integrates Redisson with Spring Boot library. Depends on [Spring Data Redis](https://github.com/redisson/redisson/tree/master/redisson-spring-data#spring-data-redis-integration) module.

Supports Spring Boot 1.3.x - 2.7.x

## Usage

### 1. Add `redisson-spring-boot-starter` dependency into your project:

Maven

```xml
     <dependency>
         <groupId>org.redisson</groupId>
         <artifactId>redisson-spring-boot-starter</artifactId>
         <version>3.18.0</version>
     </dependency>
```

Gradle

```groovy
     compile 'org.redisson:redisson-spring-boot-starter:3.18.0'
```

Downgrade `redisson-spring-data` module if necessary to support required Spring Boot version:

|redisson-spring-data
module name|Spring Boot
version|
|----------------------------|-------------------|
|redisson-spring-data-16     |1.3.y              |
|redisson-spring-data-17     |1.4.y              |
|redisson-spring-data-18     |1.5.y              |
|redisson-spring-data-2x     |2.x.y              |

### 2. Add settings into `application.settings` file

Using common spring boot settings:

```yaml
spring:
  redis:
    database:
    host:
    port:
    password:
    ssl:
    timeout:
    cluster:
      nodes:
    sentinel:
      master:
      nodes:
```

Using Redisson config file:

```yaml
spring:
  redis:
   redisson:
      file: classpath:redisson.yaml
```

Using Redisson settings:

```yaml
spring:
  redis:
   redisson:
      config: |
        clusterServersConfig:
          idleConnectionTimeout: 10000
          connectTimeout: 10000
          timeout: 3000
          retryAttempts: 3
          retryInterval: 1500
          failedSlaveReconnectionInterval: 3000
          failedSlaveCheckInterval: 60000
          password: null
          subscriptionsPerConnection: 5
          clientName: null
          loadBalancer: !<org.redisson.connection.balancer.RoundRobinLoadBalancer> {}
          subscriptionConnectionMinimumIdleSize: 1
          subscriptionConnectionPoolSize: 50
          slaveConnectionMinimumIdleSize: 24
          slaveConnectionPoolSize: 64
          masterConnectionMinimumIdleSize: 24
          masterConnectionPoolSize: 64
          readMode: "SLAVE"
          subscriptionMode: "SLAVE"
          nodeAddresses:
          - "redis://127.0.0.1:7004"
          - "redis://127.0.0.1:7001"
          - "redis://127.0.0.1:7000"
          scanInterval: 1000
          pingConnectionInterval: 0
          keepAlive: false
          tcpNoDelay: false
        threads: 16
        nettyThreads: 32
        codec: !<org.redisson.codec.MarshallingCodec> {}
        transportMode: "NIO"

```

### 3. Available Spring Beans:

- `RedissonClient`
- `RedissonRxClient`
- `RedissonReactiveClient`
- `RedisTemplate`
- `ReactiveRedisTemplate`

Try __[Redisson PRO](https://redisson.pro)__ with **ultra-fast performance** and **support by SLA**.

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * Vault Class File Definition
 *
 * @author polux <polux@poluxfr.org>
 *
 * @package MyGED
 * @subpackage Vault
 */

namespace MyGED\Vault;

use MyGED\Exceptions as AppExceptions;
use MyGED\Core\Database as AppDb;
use MyGED\Application\Application as App;

use MyGED\Vault\Vault;
use MyGED\Application\Application;

/**
 * Vaul Class Definition
 *
 * Class managing storing solution.
 */
class Vault
{
    /**
     * Vault Root Path
     *
     * @var string
     * @access protected
     * @static
     */
    protected static $_sVaultPath = null;

    /**
     * Vault TMP Path
     *
     * @var string
     * @access protected
     * @static
     */
    protected static $_sVaultTMPPath = '/tmp';

    /**
     * Vault OCR Path
     *
     * @var string
     * @access protected
     * @static
     */
    protected static $_sVaultOCRPath = '';

    /**
     * Vault DB filepath
     *
     * @var \PDO
     * @access protected
     * @static
     */
    protected static $_sVaultDBFilepath = null;

     /**
     * Vault DB Pdo Object
     *
     * @var \PDO
     * @access protected
     * @static
     */
    protected static $_oPdoVaultDB = null;

    /**
     * Define Vault Root Path Property
     *
     * @param type $pStrVaultPath
     *
     * @static
     */
    private static function setVaultPath($pStrVaultPath)
    {
        self::$_sVaultPath = $pStrVaultPath;
    }

    /**
     * Define Vault OCR Path Property
     *
     * @param type $pStrVaultPath
     *
     * @static
     */
    public static function setVaultOCRDirectory($pStrVaultOCRPath)
    {
        self::$_sVaultOCRPath = $pStrVaultOCRPath;
    }

    /**
     * Load Vault Directory
     *
     * @param string  $pStrVaultPath    Path to manage.
     * @param boolean $pBoolReset       Force reset of vault (db)
     *
     * @throws \MyGED\Core\Exceptions\GenericException
     */
    public static function loadVault($pStrVaultPath, $pBoolReset=false)
    {
        self::setVaultPath($pStrVaultPath);

        // Check Filesystem !
        if (!VaultFs::isValidVault($pStrVaultPath)) {
            if (!$pBoolReset) {
                $lArrOptions = array('msg'=> sprintf('Vault is not valid (path: %s)', $pStrVaultPath));
                throw new AppExceptions\GenericException('LOAD_VAULT_CHECKFS', $lArrOptions);
            } else {
                VaultFs::repairVaultDirectoriesAndFiles();
            }
        }

        // Check Database !
        if (!file_exists(self::getDatabaseFilePath())) {
            if (!$pBoolReset) {
                $lArrOptions = array('msg'=> sprintf('VaultDb is not valid (path: %s)', self::getDatabaseFilePath()));
                throw new AppExceptions\GenericException('LOAD_VAULT_CHECKDB', $lArrOptions);
            } else {
                self::setVaultPath($pStrVaultPath);
                VaultFs::repairVaultDirectoriesAndFiles();
            }
        }

        self::setVaultPath($pStrVaultPath);
        self::$_sVaultDBFilepath = self::getDatabaseFilePath();
    }//end loadVault()

    /**
     * Generate Unique id
     *
     * @static
     * @return string
     */
    public static function generateUniqueID($pStrPrefix='doc-')
    {
        return uniqid($pStrPrefix);
    }

    /**
     * Returns File Content from her Uid
     *
     * @param type $pStrUniqueID Unique id of file
     *
     * @return mixed Content of the file.
     */
    public static function getFileContentByID($pStrUniqueID)
    {
        $lStrFilePath = VaultDb::getFilePath($pStrUniqueID);
        return VaultFs::getFileContentByFilepath($lStrFilePath);
    }

    /**
     *
     * @param type $pStrUniqueID
     */
    public static function getFilePathByID($pStrUniqueID)
    {
        return VaultDb::getFilePath($pStrUniqueID);
    }

     /**
     *
     * @param type $pStrUniqueID
     */
    public static function getFileOriginalNameByID($pStrUniqueID)
    {
        return VaultDb::getFileOriginalName($pStrUniqueID);
    }

    public static function getDatabaseFilePath()
    {
        return Application::getAppParam('VAULT_DB');
    }

    public static function getTemplateVaultDBFilePath()
    {
        return App\App::getAppParam('TEMPLATES_ROOT').'/vault_template.db';
    }

    /**
     * Returns complete path of  Vault temporary Directory
     *
     * @return string   Complete filepath of  Vault temporary Directory
     */
    public static function getTemporaryVaultDirectory()
    {
        return self::$_sVaultTMPPath;
    }

    /**
     * Returns complete path of Vault OCR Directory
     *
     * @return string   Complete filepath of  Vault OCR Directory
     */
    public static function getVaultOCRDirectory()
    {
        return self::$_sVaultOCRPath;
    }

    public static function getVaultRootDir()
    {
        return self::$_sVaultPath;
    }

    /**
     * Store a content into Vault
     *
     * @param bytes   $pMixedContent          Content to store
     * @param string  $pStrOriginalFilename   Source filename
     * @param string  $pStrFileTypeMime       Mime Type of source file
     *
     * @throws GenericException In case of technical error during storage
     *
     * @return string   id of file created
     */
    public static function storeFromContent($pMixedContent, $pStrOriginalFilename='', $pStrFileTypeMime='')
    {
        $lStrUniqueIdDoc = self::generateUniqueID('fic-');

        try {
            $lStrExtensionFile = substr($pStrOriginalFilename, stripos($pStrOriginalFilename, '.')+1);
            $lStrFilePath = VaultFs::storeFileContent($lStrUniqueIdDoc, $pMixedContent, $lStrExtensionFile);
            VaultDb::insertNewFile($lStrUniqueIdDoc, basename($pStrOriginalFilename), $lStrFilePath, $pStrFileTypeMime);
        } catch (\Exception $ex) {
            $lArrOptions = array('msg'=> sprintf('Error saving a file into the Vault (filepath to store: %s) | Error : %s', $lStrFilePath, $ex->getMessage()));
            throw new AppExceptions\GenericException('LOAD_VAULT_CHECKDB', $lArrOptions);
        }
        return $lStrUniqueIdDoc;
    }

    /**
     * Store a file from existing file
     *
     * @param type $pStrFilePath Path of file to store.
     *
     * @return string Id Unique Doc
     */
    public static function storeFromFilepath($pStrFilePath)
    {
        $lStrUniqueIdDoc = self::generateUniqueID('fic-');

        try {
            $lStrFilePath = VaultFs::storeFromFilepath($lStrUniqueIdDoc, $pStrFilePath);
            VaultDb::insertNewFile($lStrUniqueIdDoc, basename($pStrFilePath), $lStrFilePath);
        } catch (\Exception $ex) {
            $lArrOptions = array('msg'=> sprintf('Error saving a file into the Vault (filepath to store: %s) | Error : %s', $pStrFilePath, $ex->getMessage()));
            throw new AppExceptions\GenericException('LOAD_VAULT_CHECKDB', $lArrOptions);
        }
        return $lStrUniqueIdDoc;
    }

    /**
     * Store a file from existing file with Filename update
     *
     * @param string  $pStrFilePath           Path of file to store.
     * @param string  $pStrOriginalFilename   Original Filename to store.
     *
     * @return string Id Unique Doc
     */
    public static function storeFromFilepathWithFilename($pStrFilePath, $pStrOriginalFilename)
    {
        $lStrUniqueIdDoc = self::generateUniqueID('fic-');
        $lStrFilePathTmp = VaultFs::copyFiletoVaultTmpDir($pStrFilePath, $pStrOriginalFilename);
        try {
            $lStrFilePath = VaultFs::storeFromFilepath($lStrUniqueIdDoc, $lStrFilePathTmp);
            VaultDb::insertNewFile($lStrUniqueIdDoc, $pStrOriginalFilename, $lStrFilePath);
        } catch (\Exception $ex) {
            $lArrOptions = array('msg'=> sprintf('Error saving a file into the Vault (filepath to store: %s) | Error : %s', $pStrFilePath, $ex->getMessage()));
            throw new AppExceptions\GenericException('LOAD_VAULT_CHECKDB', $lArrOptions);
        }
        return $lStrUniqueIdDoc;
    }

    /**
     * Returns Vault PDO Database Object
     *
     * @static
     * @access protected
     * @return \PDO
     */
    public static function getPDOVaultDBObject()
    {
        if (is_null(self::$_oPdoVaultDB) || !(self::$_oPdoVaultDB instanceof \PDO)) {
            self::$_oPdoVaultDB = AppDb\DatabaseTools::getSQLitePDODbObj(self::getDatabaseFilePath());
        }
        return self::$_oPdoVaultDB;
    }
}


text:
package net.dongliu.vcdiff.exception;

/**
 * vcdiff encode exception.
 *
 * @author dongliu
 */
public class VcdiffEncodeException extends Exception {

    public VcdiffEncodeException(String string) {
        super(string);
    }

}


text:
UrlDownloader::UrlDownloader(QJSValue downloader, int index, QObject *parent)
	: QObject(parent), m_downloader(std::move(downloader)), m_index(index)
{
	m_name = m_downloader.property("name").toString();

	const QStringList regexes = jsToStringList(m_downloader.property("handlers").property(m_index).property("regexes"));
	m_regexes.reserve(regexes.count());
	for (const QString &regex : regexes) {
		m_regexes.append(QRegularExpression(regex));
	}
}

const QString &UrlDownloader::name() const
{
	return m_name;
}

bool UrlDownloader::canDownload(const QUrl &url) const
{
	const QString str = url.toString();
	return std::any_of(m_regexes.constBegin(), m_regexes.constEnd(), [&str](const QRegularExpression &rx) {
		return rx.match(str).hasMatch();
	});
}

UrlDownloaderUrl UrlDownloader::url(const QUrl &url) const
{
	UrlDownloaderUrl ret;

	QJSValue urlFunction = m_downloader.property("handlers").property(m_index).property("url");
	if (urlFunction.isUndefined()) {
		ret.url = url.toString();
		return ret;
	}

	const QJSValue &result = urlFunction.call(QList<QJSValue> { url.toString() });

	// Script errors and exceptions
	if (result.isError()) {
		const QString err = QStringLiteral("Uncaught exception at line %1: %2").arg(result.property("lineNumber").toInt()).arg(result.toString());
		ret.error = err;
		log(err, Logger::Error);
		return ret;
	}

	// String return for basic URL
	if (!result.isObject()) {
		ret.url = result.toString();
		return ret;
	}

	// Error objects
	if (result.hasProperty("error")) {
		ret.error = result.property("error").toString();
		return ret;
	}

	// URL + headers object
	ret.url = result.property("url").toString();
	if (result.hasProperty("headers")) {
		const QJSValue &headers = result.property("headers");
		QJSValueIterator headersIt(headers);
		while (headersIt.hasNext()) {
			headersIt.next();
			ret.headers[headersIt.name()] = headersIt.value().toString();
		}
	}

	return ret;
}

UrlDownloaderResult UrlDownloader::parse(const QString &source, int statusCode) const
{
	UrlDownloaderResult ret;

	QJSValue parseFunction = m_downloader.property("handlers").property(m_index).property("parse");
	const QJSValue &result = parseFunction.call(QList<QJSValue> { source, statusCode });

	// Script errors and exceptions
	if (result.isError()) {
		const QString err = QStringLiteral("Uncaught exception at line %1: %2").arg(result.property("lineNumber").toInt()).arg(result.toString());
		ret.error = err;
		log(err, Logger::Error);
		return ret;
	}

	// Error objects
	if (result.hasProperty("error")) {
		ret.error = result.property("error").toString();
		return ret;
	}

	// Tokens
	if (result.hasProperty("tokens")) {
		const QJSValue &tokens = result.property("tokens");
		QJSValueIterator tokensIt(tokens);
		while (tokensIt.hasNext()) {
			tokensIt.next();
			ret.tokens[tokensIt.name()] = tokensIt.value().toVariant();
		}
	}

	// Files
	if (result.hasProperty("files")) {
		const QJSValue &files = result.property("files");
		const quint32 length = files.property("length").toUInt();
		for (quint32 i = 0; i < length; ++i) {
			const QJSValue &file = files.property(i);

			UrlDownloaderFile rFile;
			getProperty(file, "url", rFile.url);
			getProperty(file, "width", rFile.width);
			getProperty(file, "height", rFile.height);
			getProperty(file, "filesize", rFile.filesize);
			getProperty(file, "ext", rFile.ext);

			ret.files.append(rFile);
		}
	}

	return ret;
}


text:
//
// Samples.Controls.SearchPersist.cs
//
// Author:
//   Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using Novell.Directory.Ldap;
using Novell.Directory.Ldap.Controls;

namespace Samples.Controls
{
	class SearchPersist
	{
		const double TIME_OUT_IN_MINUTES = 0.5;
		static DateTime timeOut;

		static void Main(string[] args)
		{

			if ( args.Length != 5)
			{
				Console.WriteLine("Usage:   mono SearchPersist <host name> <ldap port>  <login dn>" + " <password> <search base>" );
				Console.WriteLine("Example: mono SearchPersist Acme.com 389"  + " \"cn=admin,o=Acme\"" + " secret \"ou=sales,o=Acme\"");
				return;
			}

			int ldapVersion  = LdapConnection.Ldap_V3;
			String ldapHost = args[0];
			int ldapPort = Convert.ToInt32(args[1]);;
			String loginDN = args[2];
			String password = args[3];
			String searchBase = args[4];
			LdapSearchQueue queue = null;
			LdapSearchConstraints constraints;
			LdapPersistSearchControl psCtrl;
			LdapConnection lc = new LdapConnection();
			constraints =  new LdapSearchConstraints();

			try
			{
				// connect to the server
				lc.Connect( ldapHost, ldapPort );
				// authenticate to the server
				lc.Bind(ldapVersion, loginDN, password);

				//Create the persistent search control
				psCtrl = new LdapPersistSearchControl(
					LdapPersistSearchControl.ANY, // any change
					true,                         //only get changes
					true,                         //return entry change controls
					true);                        //control is critcal

				// add the persistent search control to the search constraints
				constraints.setControls( psCtrl );

				// perform the search with no attributes returned
				String[] noAttrs = {LdapConnection.NO_ATTRS};
				queue = lc.Search(
					searchBase,                // container to search
					LdapConnection.SCOPE_SUB,  // search container's subtree
					"(objectClass=*)",         // search filter, all objects
					noAttrs,                   // don't return attributes
					false,                     // return attrs and values, ignored
					null,                      // use default search queue
					constraints);              // use default search constraints
			}
			catch( LdapException e )
			{
				Console.WriteLine( "Error: " + e.ToString() );
				try { lc.Disconnect(); }
				catch(LdapException e2) {  }
				Environment.Exit(1);
			}
			catch(Exception e)
			{
				Console.WriteLine( "Error: " + e.Message );
				return;
			}

			Console.WriteLine("Monitoring the events for {0} minutes..", TIME_OUT_IN_MINUTES );
			Console.WriteLine();

			//Set the timeout value
			timeOut= DateTime.Now.AddMinutes(TIME_OUT_IN_MINUTES);

			try
			{
				//Monitor till the timeout happens
				while (DateTime.Now.CompareTo(timeOut) < 0)
				{
					if (!checkForAChange(queue))
						break;
					System.Threading.Thread.Sleep(10);
				}
			}
			catch (System.IO.IOException e)
			{
				System.Console.Out.WriteLine(e.Message);
			}
			catch (System.Threading.ThreadInterruptedException e)
			{
			}

			//Disconnect from the server before exiting
			try
			{
				lc.Abandon(queue); //abandon the search
				lc.Disconnect();
			}
			catch (LdapException e)
			{
				Console.Out.WriteLine();
				Console.Out.WriteLine("Error: " + e.ToString());
			}

			Environment.Exit(0);
		}

		/// <summary> Check the queue for a response. If a response has been received,
		/// print the response information.
		/// </summary>

		static private bool checkForAChange(LdapSearchQueue queue)
		{
			LdapMessage message;
			bool result = true;
			try
			{
				//check if a response has been received so we don't block
				//when calling getResponse()
				if (queue.isResponseReceived())
				{
					message = queue.getResponse();
					if (message != null)
					{
						// is the response a search result reference?
						if (message is LdapSearchResultReference)
						{
							String[] urls = ((LdapSearchResultReference) message).Referrals;
							Console.Out.WriteLine("\nSearch result references:");
							for (int i = 0; i < urls.Length; i++)
								Console.Out.WriteLine(urls[i]);
						}
							// is the response a search result?
						else if (message is LdapSearchResult)
						{
							LdapControl[] controls = message.Controls;
							for (int i = 0; i < controls.Length; i++)
							{
								if (controls[i] is LdapEntryChangeControl)
								{
									LdapEntryChangeControl ecCtrl = (LdapEntryChangeControl) controls[i];

									int changeType = ecCtrl.ChangeType;
										Console.Out.WriteLine("\n\nchange type: " + getChangeTypeString(changeType));
									if (changeType == LdapPersistSearchControl.MODDN)
										Console.Out.WriteLine("Prev. DN: " + ecCtrl.PreviousDN);
									if (ecCtrl.HasChangeNumber)
										Console.Out.WriteLine("Change Number: " + ecCtrl.ChangeNumber);

									LdapEntry entry = ((LdapSearchResult) message).Entry;

									Console.Out.WriteLine("entry: " + entry.DN);
								}
							}
						}
							// the message is a search response
						else
						{
							LdapResponse response = (LdapResponse) message;
							int resultCode = response.ResultCode;
							if (resultCode == LdapException.SUCCESS)
							{
								Console.Out.WriteLine("\nUnexpected success response.");
								result = false;
							}
							else if (resultCode == LdapException.REFERRAL)
							{
								String[] urls = ((LdapResponse) message).Referrals;
								Console.Out.WriteLine("\n\nReferrals:");
								for (int i = 0; i < urls.Length; i++)
									Console.Out.WriteLine(urls[i]);
							}
							else
							{
								Console.Out.WriteLine("Persistent search failed.");
								throw new LdapException(response.ErrorMessage, resultCode, response.MatchedDN);
							}
						}
					}
				}
			}
			catch (LdapException e)
			{
				Console.Out.WriteLine("Error: " + e.ToString());
				result = false;
			}

			return result;
		}

		/// <summary> Return a string indicating the type of change represented by the
		/// changeType parameter.
		/// </summary>
		private static String getChangeTypeString(int changeType)
		{
			String changeTypeString;

			switch (changeType)
			{

				case LdapPersistSearchControl.ADD:
					changeTypeString = "ADD";
					break;

				case LdapPersistSearchControl.MODIFY:
					changeTypeString = "MODIFY";
					break;

				case LdapPersistSearchControl.MODDN:
					changeTypeString = "MODDN";
					break;

				case LdapPersistSearchControl.DELETE:
					changeTypeString = "DELETE";
					break;

				default:
					changeTypeString = "Unknown change type: " + changeType.ToString();
					break;

			}

			return changeTypeString;
		}
	} //end class SearchPersist
}


text:
package hk.samwong.roomservice.servlet.gdriveapi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

import org.junit.Test;

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;

public class DriveAPITest {

	@Test
	public void test() {
		String CLIENT_ID = "956519301435.apps.googleusercontent.com";
		String CLIENT_SECRET = "KgfDPDAImauK1160XaN0YXOY";
		String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";

		HttpTransport httpTransport = new NetHttpTransport();
		JsonFactory jsonFactory = new JacksonFactory();

		GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
				Arrays.asList(DriveScopes.DRIVE)).setAccessType("online").setApprovalPrompt("auto").build();

		String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
		System.out.println("Please open the following URL in your browser then type the authorization code:");
		System.out.println("  " + url);
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String code;
		try {
			code = br.readLine();

			GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
			GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

			// Create a new authorized API client
			Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build();

			// Insert a file
			File body = new File();
			body.setTitle("My document");
			body.setDescription("A test document");
			body.setMimeType("text/plain");

			java.io.File fileContent = new java.io.File("/tmp/drive");
			FileContent mediaContent = new FileContent("text/plain", fileContent);

			File file = service.files().insert(body, mediaContent).execute();
			System.out.println("File ID: " + file.getId());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}


text:
var name		= "Student of Artifactology";
var collection_type	= 0;
var is_secret		= 0;
var desc		= "Reassembled three different artifacts";
var status_text		= "The memories of the ancients buzz through you as you handle artifacts. Having carefully reassembled three, hopefully it hasn't given you a headache. It has, however, given you a badge. YAY!";
var last_published	= 1351302421;
var is_shareworthy	= 1;
var url		= "student-of-artifactology";
var category		= "feats";
var url_swf		= "\/c2.glitch.bz\/achievements\/2012-10-26\/student_of_artifactology_1351300716.swf";
var url_img_180		= "\/c2.glitch.bz\/achievements\/2012-10-26\/student_of_artifactology_1351300716_180.png";
var url_img_60		= "\/c2.glitch.bz\/achievements\/2012-10-26\/student_of_artifactology_1351300716_60.png";
var url_img_40		= "\/c2.glitch.bz\/achievements\/2012-10-26\/student_of_artifactology_1351300716_40.png";
function on_apply(pc){

}
var conditions = {
	852 : {
		type	: "group_count",
		group	: "artifacts_made",
		value	: "3"
	},
};
function onComplete(pc){ // generated from rewards
	var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0;
	multiplier += pc.imagination_get_achievement_modifier();
	if (/completist/i.exec(this.name)) {
		 var level = pc.stats_get_level();
		 if (level > 4) {
				multiplier *= (pc.stats_get_level()/4);
		}
	}
	pc.stats_add_xp(round_to_5(1750 * multiplier), true);
	pc.stats_add_favor_points("all", round_to_5(87 * multiplier));
	if(pc.buffs_has('gift_of_gab')) {
		pc.buffs_remove('gift_of_gab');
	}
	else if(pc.buffs_has('silvertongue')) {
		pc.buffs_remove('silvertongue');
	}
}
var rewards	= {
	"xp"	: 1750,
	"favor"	: {
		"giant"		: "all",
		"points"	: 87
	}
};

// generated ok (NO DATE)


text:
package com.ehensin.pt;

import java.io.Serializable;

public class ExeResult implements Serializable{
    /**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private boolean isSuccess;
    private Object result;
    private String resultDesc;

	public ExeResult(boolean isSuccess, Object result, String resultDesc) {
		super();
		this.isSuccess = isSuccess;
		this.result = result;
		this.resultDesc = resultDesc;
	}
	public boolean isSuccess() {
		return isSuccess;
	}
	public void setSuccess(boolean isSuccess) {
		this.isSuccess = isSuccess;
	}
	public Object getResult() {
		return result;
	}
	public void setResult(Object result) {
		this.result = result;
	}
	public String getResultDesc() {
		return resultDesc;
	}
	public void setResultDesc(String resultDesc) {
		this.resultDesc = resultDesc;
	}

}


text:
.. _styleguide04:

****************
Including a file
****************

A complete file should be included with the following construct. It is recommended it be included with
it's own .rst file describing the file included. This is an example of an xml file is included.

.. toctree::

  xmlexample.rst


text:
SB Semesterbyar Hem

A web-based interface for managing the booking system of a holliday business.

Made with MySQL in mind and using PHP PDO.

### Notes, code issues, toDo
Working after the ORM principles, but limited, and mainly for easy language portability. Failing... the DB should instead have standard language for relations, probalby english. Language compatability should be restricted to UI strings, nowhere in code and naming.

Todo:
* Make the HTML5 element week storable in DB, need method to substr() the value and calc with it.

### License

This software is free software and carries a MIT license.

Copyright (c) 2015 Kai Weeks


text:
package consulo.csharp.lang.psi.impl.light;

import javax.annotation.Nonnull;

import org.jetbrains.annotations.NonNls;

import javax.annotation.Nullable;
import consulo.annotation.access.RequiredReadAction;
import consulo.dotnet.psi.DotNetExpression;
import consulo.dotnet.psi.DotNetModifier;
import consulo.dotnet.psi.DotNetModifierList;
import consulo.dotnet.psi.DotNetType;
import consulo.dotnet.psi.DotNetVariable;
import consulo.dotnet.resolve.DotNetTypeRef;
import com.intellij.psi.PsiElement;
import com.intellij.util.IncorrectOperationException;

/**
 * @author VISTALL
 * @since 15.01.14
 */
public abstract class CSharpLightVariable<S extends DotNetVariable> extends CSharpLightNamedElement<S> implements DotNetVariable
{
	protected CSharpLightVariable(S original)
	{
		super(original);
	}

	@RequiredReadAction
	@Override
	public boolean isConstant()
	{
		return myOriginal.isConstant();
	}

	@RequiredReadAction
	@Nullable
	@Override
	public PsiElement getConstantKeywordElement()
	{
		return myOriginal.getConstantKeywordElement();
	}

	@RequiredReadAction
	@Nonnull
	@Override
	public DotNetTypeRef toTypeRef(boolean resolveFromInitializer)
	{
		return myOriginal.toTypeRef(true);
	}

	@RequiredReadAction
	@Nullable
	@Override
	public DotNetType getType()
	{
		return myOriginal.getType();
	}

	@RequiredReadAction
	@Nullable
	@Override
	public DotNetExpression getInitializer()
	{
		return myOriginal.getInitializer();
	}

	@RequiredReadAction
	@Override
	public boolean hasModifier(@Nonnull DotNetModifier modifier)
	{
		return myOriginal.hasModifier(modifier);
	}

	@RequiredReadAction
	@Nullable
	@Override
	public DotNetModifierList getModifierList()
	{
		return myOriginal.getModifierList();
	}

	@Nullable
	@Override
	public PsiElement getNameIdentifier()
	{
		return myOriginal.getNameIdentifier();
	}

	@Override
	public PsiElement setName(@NonNls @Nonnull String s) throws IncorrectOperationException
	{
		return myOriginal.setName(s);
	}
}


text:
using namespace Rcpp;

#include "utilities.h" // R_INFO, profiling mode, etc. must include first
#include "ANN_util.h" // matrixToANNpointArray
#include "R_kNN.h" // main header
#include "R_kdtree.h" // R Interface to ANN KD trees
// #include <DT/KNN/dt_knn.h> // Dual Tree KNN implementation

using namespace Rcpp;

// returns knn + dist
List kNN_int(const NumericMatrix& x, int k,
             int type, int bucketSize, int splitRule, double approx,
             NumericMatrix& r_x = emptyMatrix) {

  // Copy data over to ANN point array
  bool qr_same = true;
  ANNpointArray queryPts = matrixToANNpointArray(x);
  ANNpointArray refPts;
  if (r_x.size() <= 1){
    r_x = x;
    refPts = queryPts;
  } else {
    qr_same = false;
    refPts = matrixToANNpointArray(r_x);
  }

  // Query data dimensions
  int q_n = x.nrow(), q_d = x.ncol();
  int r_n = r_x.nrow(), r_d = r_x.ncol();
  if (q_d != r_d){ Rcpp::stop("Query and reference sets must have the same dimension."); }

  // Create the ANN kd tree
  ANNkd_tree* kdTree = new ANNkd_tree(refPts, r_n, r_d, bucketSize, (ANNsplitRule) splitRule);

  // Reserve the output
  NumericMatrix dist(q_n, k);
  IntegerMatrix id(q_n, k);

  // Note: the search also returns the point itself (as the first hit)!
  // So we have to look for k+1 points.
  ANNdistArray dists = new ANNdist[k+1];
  ANNidxArray nnIdx = new ANNidx[k+1];

  for (int i=0; i < q_n; i++) {
    if (!(i % 100)) Rcpp::checkUserInterrupt();

    ANNpoint queryPt = queryPts[i];
    kdTree->annkSearch(queryPt, k+1, nnIdx, dists, approx);

    // remove self match
    IntegerVector ids = IntegerVector(nnIdx, nnIdx+k+1);
    LogicalVector take = ids != i;
    ids = ids[take];
    id(i, _) = ids + 1;

    NumericVector ndists = NumericVector(dists, dists+k+1);
    dist(i, _) = sqrt(ndists[take]);
  }

  // cleanup
  delete kdTree;
  delete [] dists;
  delete [] nnIdx;
  annDeallocPts(queryPts);
  if (!qr_same) annDeallocPts(refPts);
  annClose();

  // prepare results
  List ret;
  ret["dist"] = dist;
  ret["id"] = id;
  ret["k"] = k;
  return ret;
}

// R-facing API for the KNN-focused dual tree traversal
// TODO: approx unused right now
// List dt_kNN_int(const NumericMatrix& q_x, const int k, int bucketSize, int splitRule, SEXP metric_ptr, // The user-specified metric to use
//                 NumericMatrix r_x = NumericMatrix())
//   {
//
//   // Construct the dual tree KNN instance
//   Metric& metric = getMetric(metric_ptr);
//   List config = List::create(_["bucketSize"] = bucketSize, _["splitRule"] = splitRule);
//   DualTreeKNN dt_knn = DualTreeKNN(q_x, metric, r_x, config);
//
//   // Note: the search also returns the point itself (as the first hit)!
//   // So we have to look for k+1 points.
//   List res = dt_knn.KNN(k+1);
//
//   // Return results
//   return(res);
// }

// Performance profiling
// void perf_test(){
//   List res;
// #ifdef PROFILING
//   annResetStats(r_x.nrow());
//
//   // Regular kdtree search
//   List ann_kdtree = kdtree(r_x, bucketSize); // create regular kdtree with the same bucket size
//   BEGIN_PROFILE()
//     List res1 = kd_knn(q_x, (SEXP) ann_kdtree["kdtree_ptr"], k, false);
//   REPORT_TIME("Regular KNN search")
//
//     // Print statistics
//     Rcout << "Regular KDtree search performance: " << std::endl;
//   annPrintStats((ANNbool) false);
//
//   // Dual tree equivalent
//   Rcout << "DualTree search performance: " << std::endl;
//   annResetStats(r_x.nrow());
//   annResetCounts();	// reset stats for a set of queries
//   BEGIN_PROFILE()
// }


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.dashboard;

import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;

/**
 * Register this extension to provide run configuration types available in Run Dashboard/Services by default.
 */
public interface RunDashboardDefaultTypesProvider {
  @NotNull
  Collection<String> getDefaultTypeIds(@NotNull Project project);
}


text:
using System.Collections.Generic;
using System.Net.Http.Headers;

using Xunit;

namespace System.Net.Http.Tests
{
    public class RangeItemHeaderValueTest
    {
        [Fact]
        public void Ctor_BothValuesNull_Throw()
        {
            Assert.Throws<ArgumentException>(() => { new RangeItemHeaderValue(null, null); });
        }

        [Fact]
        public void Ctor_FromValueNegative_Throw()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => { new RangeItemHeaderValue(-1, null); });
        }

        [Fact]
        public void Ctor_FromGreaterThanToValue_Throw()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => { new RangeItemHeaderValue(2, 1); });
        }

        [Fact]
        public void Ctor_ToValueNegative_Throw()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => { new RangeItemHeaderValue(null, -1); });
        }

        [Fact]
        public void Ctor_ValidFormat_SuccessfullyCreated()
        {
            RangeItemHeaderValue rangeItem = new RangeItemHeaderValue(1, 2);
            Assert.Equal(1, rangeItem.From);
            Assert.Equal(2, rangeItem.To);
        }

        [Fact]
        public void ToString_UseDifferentRangeItems_AllSerializedCorrectly()
        {
            // Make sure ToString() doesn't add any separators.
            RangeItemHeaderValue rangeItem = new RangeItemHeaderValue(1000000000, 2000000000);
            Assert.Equal("1000000000-2000000000", rangeItem.ToString());

            rangeItem = new RangeItemHeaderValue(5, null);
            Assert.Equal("5-", rangeItem.ToString());

            rangeItem = new RangeItemHeaderValue(null, 10);
            Assert.Equal("-10", rangeItem.ToString());
        }

        [Fact]
        public void GetHashCode_UseSameAndDifferentRangeItems_SameOrDifferentHashCodes()
        {
            RangeItemHeaderValue rangeItem1 = new RangeItemHeaderValue(1, 2);
            RangeItemHeaderValue rangeItem2 = new RangeItemHeaderValue(1, null);
            RangeItemHeaderValue rangeItem3 = new RangeItemHeaderValue(null, 2);
            RangeItemHeaderValue rangeItem4 = new RangeItemHeaderValue(2, 2);
            RangeItemHeaderValue rangeItem5 = new RangeItemHeaderValue(1, 2);

            Assert.NotEqual(rangeItem1.GetHashCode(), rangeItem2.GetHashCode());
            Assert.NotEqual(rangeItem1.GetHashCode(), rangeItem3.GetHashCode());
            Assert.NotEqual(rangeItem1.GetHashCode(), rangeItem4.GetHashCode());
            Assert.Equal(rangeItem1.GetHashCode(), rangeItem5.GetHashCode());
        }

        [Fact]
        public void Equals_UseSameAndDifferentRanges_EqualOrNotEqualNoExceptions()
        {
            RangeItemHeaderValue rangeItem1 = new RangeItemHeaderValue(1, 2);
            RangeItemHeaderValue rangeItem2 = new RangeItemHeaderValue(1, null);
            RangeItemHeaderValue rangeItem3 = new RangeItemHeaderValue(null, 2);
            RangeItemHeaderValue rangeItem4 = new RangeItemHeaderValue(2, 2);
            RangeItemHeaderValue rangeItem5 = new RangeItemHeaderValue(1, 2);

            Assert.False(rangeItem1.Equals(rangeItem2), "1-2 vs. 1-.");
            Assert.False(rangeItem2.Equals(rangeItem1), "1- vs. 1-2.");
            Assert.False(rangeItem1.Equals(null), "1-2 vs. null.");
            Assert.False(rangeItem1.Equals(rangeItem3), "1-2 vs. -2.");
            Assert.False(rangeItem3.Equals(rangeItem1), "-2 vs. 1-2.");
            Assert.False(rangeItem1.Equals(rangeItem4), "1-2 vs. 2-2.");
            Assert.True(rangeItem1.Equals(rangeItem5), "1-2 vs. 1-2.");
        }

        [Fact]
        public void Clone_Call_CloneFieldsMatchSourceFields()
        {
            RangeItemHeaderValue source = new RangeItemHeaderValue(1, 2);
            RangeItemHeaderValue clone = (RangeItemHeaderValue)((ICloneable)source).Clone();
            Assert.Equal(source.From, clone.From);
            Assert.Equal(source.To, clone.To);

            source = new RangeItemHeaderValue(1, null);
            clone = (RangeItemHeaderValue)((ICloneable)source).Clone();
            Assert.Equal(source.From, clone.From);
            Assert.Equal(source.To, clone.To);

            source = new RangeItemHeaderValue(null, 2);
            clone = (RangeItemHeaderValue)((ICloneable)source).Clone();
            Assert.Equal(source.From, clone.From);
            Assert.Equal(source.To, clone.To);
        }

        [Fact]
        public void GetRangeItemLength_DifferentValidScenarios_AllReturnNonZero()
        {
            CheckValidGetRangeItemLength("1-2", 0, 3, 1, 2);
            CheckValidGetRangeItemLength("0-0", 0, 3, 0, 0);
            CheckValidGetRangeItemLength(" 1-", 1, 2, 1, null);
            CheckValidGetRangeItemLength(" -2", 1, 2, null, 2);

            // Note that the parser will only parse '1-' as a valid range and ignore '-2'. It is the callers
            // responsibility to determine if this is indeed a valid range
            CheckValidGetRangeItemLength(" 1--2", 1, 2, 1, null);

            CheckValidGetRangeItemLength(" 684684 - 123456789012345 !", 1, 25, 684684, 123456789012345);

            // The separator doesn't matter. It only parses until the first non-whitespace
            CheckValidGetRangeItemLength(" 1 - 2 ,", 1, 6, 1, 2);
        }

        [Fact]
        public void GetRangeItemLength_DifferentInvalidScenarios_AllReturnZero()
        {
            CheckInvalidGetRangeItemLength(" 1-2", 0); // no leading spaces.
            CheckInvalidGetRangeItemLength("2-1", 0);
            CheckInvalidGetRangeItemLength("-", 0);
            CheckInvalidGetRangeItemLength("1", 0);
            CheckInvalidGetRangeItemLength(null, 0);
            CheckInvalidGetRangeItemLength(string.Empty, 0);
            CheckInvalidGetRangeItemLength("12345678901234567890123-", 0); // >>Int64.MaxValue
            CheckInvalidGetRangeItemLength("-12345678901234567890123", 0); // >>Int64.MaxValue
            CheckInvalidGetRangeItemLength("9999999999999999999-", 0); // 19-digit numbers outside the Int64 range.
            CheckInvalidGetRangeItemLength("-9999999999999999999", 0); // 19-digit numbers outside the Int64 range.
        }

        [Fact]
        public void GetRangeItemListLength_DifferentValidScenarios_AllReturnNonZero()
        {
            CheckValidGetRangeItemListLength("x,,1-2, 3 -  , , -6 , ,,", 1, 23,
                new Tuple<long?, long?>(1, 2), new Tuple<long?, long?>(3, null), new Tuple<long?, long?>(null, 6));
            CheckValidGetRangeItemListLength("1-2,", 0, 4, new Tuple<long?, long?>(1, 2));
            CheckValidGetRangeItemListLength("1-", 0, 2, new Tuple<long?, long?>(1, null));
        }

        [Fact]
        public void GetRangeItemListLength_DifferentInvalidScenarios_AllReturnZero()
        {
            CheckInvalidGetRangeItemListLength(null, 0);
            CheckInvalidGetRangeItemListLength(string.Empty, 0);
            CheckInvalidGetRangeItemListLength("1-2", 3);
            CheckInvalidGetRangeItemListLength(",,", 0);
            CheckInvalidGetRangeItemListLength("1", 0);
            CheckInvalidGetRangeItemListLength("1-2,3", 0);
            CheckInvalidGetRangeItemListLength("1--2", 0);
            CheckInvalidGetRangeItemListLength("1,-2", 0);
            CheckInvalidGetRangeItemListLength("-", 0);
            CheckInvalidGetRangeItemListLength("--", 0);
        }

        #region Helper methods

        private static void AssertFormatException(string tag)
        {
            Assert.Throws<FormatException>(() => { new EntityTagHeaderValue(tag); });
        }

        private static void CheckValidGetRangeItemLength(string input, int startIndex, int expectedLength,
            long? expectedFrom, long? expectedTo)
        {
            RangeItemHeaderValue result = null;
            Assert.Equal(expectedLength, RangeItemHeaderValue.GetRangeItemLength(input, startIndex, out result));
            Assert.Equal(expectedFrom, result.From);
            Assert.Equal(expectedTo, result.To);
        }

        private static void CheckInvalidGetRangeItemLength(string input, int startIndex)
        {
            RangeItemHeaderValue result = null;
            Assert.Equal(0, RangeItemHeaderValue.GetRangeItemLength(input, startIndex, out result));
            Assert.Null(result);
        }

        private static void CheckValidGetRangeItemListLength(string input, int startIndex, int expectedLength,
            params Tuple<long?, long?>[] expectedRanges)
        {
            List<RangeItemHeaderValue> ranges = new List<RangeItemHeaderValue>();
            Assert.Equal(expectedLength, RangeItemHeaderValue.GetRangeItemListLength(input, startIndex, ranges));

            Assert.Equal<int>(expectedRanges.Length, ranges.Count);

            for (int i = 0; i < expectedRanges.Length; i++)
            {
                Assert.Equal(expectedRanges[i].Item1, ranges[i].From);
                Assert.Equal(expectedRanges[i].Item2, ranges[i].To);
            }
        }

        private static void CheckInvalidGetRangeItemListLength(string input, int startIndex)
        {
            List<RangeItemHeaderValue> ranges = new List<RangeItemHeaderValue>();
            Assert.Equal(0, RangeItemHeaderValue.GetRangeItemListLength(input, startIndex, ranges));
        }
        #endregion
    }
}


text:
#pragma once
#include <aws/appconfig/AppConfig_EXPORTS.h>
#include <aws/appconfig/AppConfigRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Http
{
    class URI;
} //namespace Http
namespace AppConfig
{
namespace Model
{

  /**
   */
  class AWS_APPCONFIG_API ListDeploymentsRequest : public AppConfigRequest
  {
  public:
    ListDeploymentsRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "ListDeployments"; }

    Aws::String SerializePayload() const override;

    void AddQueryStringParameters(Aws::Http::URI& uri) const override;

    /**
     *
The application ID.

     */
    inline const Aws::String& GetApplicationId() const{ return m_applicationId; }

    /**
     *
The application ID.

     */
    inline bool ApplicationIdHasBeenSet() const { return m_applicationIdHasBeenSet; }

    /**
     *
The application ID.

     */
    inline void SetApplicationId(const Aws::String& value) { m_applicationIdHasBeenSet = true; m_applicationId = value; }

    /**
     *
The application ID.

     */
    inline void SetApplicationId(Aws::String&& value) { m_applicationIdHasBeenSet = true; m_applicationId = std::move(value); }

    /**
     *
The application ID.

     */
    inline void SetApplicationId(const char* value) { m_applicationIdHasBeenSet = true; m_applicationId.assign(value); }

    /**
     *
The application ID.

     */
    inline ListDeploymentsRequest& WithApplicationId(const Aws::String& value) { SetApplicationId(value); return *this;}

    /**
     *
The application ID.

     */
    inline ListDeploymentsRequest& WithApplicationId(Aws::String&& value) { SetApplicationId(std::move(value)); return *this;}

    /**
     *
The application ID.

     */
    inline ListDeploymentsRequest& WithApplicationId(const char* value) { SetApplicationId(value); return *this;}

    /**
     *
The environment ID.

     */
    inline const Aws::String& GetEnvironmentId() const{ return m_environmentId; }

    /**
     *
The environment ID.

     */
    inline bool EnvironmentIdHasBeenSet() const { return m_environmentIdHasBeenSet; }

    /**
     *
The environment ID.

     */
    inline void SetEnvironmentId(const Aws::String& value) { m_environmentIdHasBeenSet = true; m_environmentId = value; }

    /**
     *
The environment ID.

     */
    inline void SetEnvironmentId(Aws::String&& value) { m_environmentIdHasBeenSet = true; m_environmentId = std::move(value); }

    /**
     *
The environment ID.

     */
    inline void SetEnvironmentId(const char* value) { m_environmentIdHasBeenSet = true; m_environmentId.assign(value); }

    /**
     *
The environment ID.

     */
    inline ListDeploymentsRequest& WithEnvironmentId(const Aws::String& value) { SetEnvironmentId(value); return *this;}

    /**
     *
The environment ID.

     */
    inline ListDeploymentsRequest& WithEnvironmentId(Aws::String&& value) { SetEnvironmentId(std::move(value)); return *this;}

    /**
     *
The environment ID.

     */
    inline ListDeploymentsRequest& WithEnvironmentId(const char* value) { SetEnvironmentId(value); return *this;}

    /**
     *
The maximum number of items that may be returned for this call. If there are
     * items that have not yet been returned, the response will include a non-null
     * NextToken that you can provide in a subsequent call to get the next
     * set of results.

     */
    inline int GetMaxResults() const{ return m_maxResults; }

    /**
     *
The maximum number of items that may be returned for this call. If there are
     * items that have not yet been returned, the response will include a non-null
     * NextToken that you can provide in a subsequent call to get the next
     * set of results.

     */
    inline bool MaxResultsHasBeenSet() const { return m_maxResultsHasBeenSet; }

    /**
     *
The maximum number of items that may be returned for this call. If there are
     * items that have not yet been returned, the response will include a non-null
     * NextToken that you can provide in a subsequent call to get the next
     * set of results.

     */
    inline void SetMaxResults(int value) { m_maxResultsHasBeenSet = true; m_maxResults = value; }

    /**
     *
The maximum number of items that may be returned for this call. If there are
     * items that have not yet been returned, the response will include a non-null
     * NextToken that you can provide in a subsequent call to get the next
     * set of results.

     */
    inline ListDeploymentsRequest& WithMaxResults(int value) { SetMaxResults(value); return *this;}

    /**
     *
The token returned by a prior call to this operation indicating the next set
     * of results to be returned. If not specified, the operation will return the first
     * set of results.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
The token returned by a prior call to this operation indicating the next set
     * of results to be returned. If not specified, the operation will return the first
     * set of results.

     */
    inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; }

    /**
     *
The token returned by a prior call to this operation indicating the next set
     * of results to be returned. If not specified, the operation will return the first
     * set of results.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }

    /**
     *
The token returned by a prior call to this operation indicating the next set
     * of results to be returned. If not specified, the operation will return the first
     * set of results.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }

    /**
     *
The token returned by a prior call to this operation indicating the next set
     * of results to be returned. If not specified, the operation will return the first
     * set of results.

     */
    inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }

    /**
     *
The token returned by a prior call to this operation indicating the next set
     * of results to be returned. If not specified, the operation will return the first
     * set of results.

     */
    inline ListDeploymentsRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
The token returned by a prior call to this operation indicating the next set
     * of results to be returned. If not specified, the operation will return the first
     * set of results.

     */
    inline ListDeploymentsRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
The token returned by a prior call to this operation indicating the next set
     * of results to be returned. If not specified, the operation will return the first
     * set of results.

     */
    inline ListDeploymentsRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    Aws::String m_applicationId;
    bool m_applicationIdHasBeenSet = false;

    Aws::String m_environmentId;
    bool m_environmentIdHasBeenSet = false;

    int m_maxResults;
    bool m_maxResultsHasBeenSet = false;

    Aws::String m_nextToken;
    bool m_nextTokenHasBeenSet = false;
  };

} // namespace Model
} // namespace AppConfig
} // namespace Aws


text:
var a = document.createElement('audio'),
	supportsVorbis = !!(a.canPlayType && a.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, '')),
	supportsAAC = !!(a.canPlayType && a.canPlayType('audio/mp4; codecs="mp4a.40.2"').replace(/no/, ''));

exports.vorbis = supportsVorbis;
exports.AAC = supportsAAC;


text:
using System;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;

using MdDumper.Visualization;

namespace MdDumper
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length == 0 || new[] {"/?", "-?", "-h", "--help"}.Any(x => string.Equals(args[0], x, StringComparison.OrdinalIgnoreCase)))
            {
                PrintUsage();
                return;
            }

            foreach (var fileName in args)
            {
                Console.WriteLine(fileName);
                Console.WriteLine(new string('*', 80));

                try
                {
                    using (var stream = File.OpenRead(fileName))
                    using (var peFile = new PEReader(stream))
                    {
                        var metadataReader = peFile.GetMetadataReader();
                        var visualizer = new MetadataVisualizer(metadataReader, Console.Out);
                        visualizer.Visualize();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

        private static void PrintUsage()
        {
            Console.WriteLine("This tool dumps the contents of all tables in a set of PE files.");
            Console.WriteLine("usage: mddumper <file>...");
        }
    }
}


text:
/*************************************************************************/
/*                                                                       */
/*                Centre for Speech Technology Research                  */
/*                     University of Edinburgh, UK                       */
/*                       Copyright (c) 1996,1997                         */
/*                        All Rights Reserved.                           */
/*                                                                       */
/*  Permission is hereby granted, free of charge, to use and distribute  */
/*  this software and its documentation without restriction, including   */
/*  without limitation the rights to use, copy, modify, merge, publish,  */
/*  distribute, sublicense, and/or sell copies of this work, and to      */
/*  permit persons to whom this work is furnished to do so, subject to   */
/*  the following conditions:                                            */
/*   1. The code must retain the above copyright notice, this list of    */
/*      conditions and the following disclaimer.                         */
/*   2. Any modifications must be clearly marked as such.                */
/*   3. Original authors' names are not deleted.                         */
/*   4. The authors' names are not used to endorse or promote products   */
/*      derived from this software without specific prior written        */
/*      permission.                                                      */
/*                                                                       */
/*  THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK        */
/*  DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING      */
/*  ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT   */
/*  SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE     */
/*  FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES    */
/*  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN   */
/*  AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,          */
/*  ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF       */
/*  THIS SOFTWARE.                                                       */
/*                                                                       */
/*************************************************************************/
/*             Author :  Alan W Black (Steve Isard and Alistair Conkie)  */
/*             Date   :  July 1996                                       */
/*-----------------------------------------------------------------------*/
/*                                                                       */
/* Interface to Donovan (Isard) LPC diphone code                         */
/*                                                                       */
/* Uses the FreeSpeech version of the code.  Those .c files are          */
/* with both systems and hopefully will continue to be so.  Only the     */
/* necessary parts of FreeSpeech are included (the waveform synthesizer) */
/* The rest is plugged in from this file                                 */
/*                                                                       */
/* Note the FreeSpeech code is GNU Copyright not like the above          */
/*                                                                       */
/*=======================================================================*/
#include <iostream>
#include <fstream>
#include "festival.h"
#include "donovan.h"

static CONFIG *make_config(void);
static void delete_config(CONFIG *config);
static SPN *make_spn(EST_Utterance &u);
static void delete_spn(SPN *ps);
static ACOUSTIC *make_as(SPN *ps);
static void delete_as(ACOUSTIC *ss);

static CONFIG *don_config=0;
static short *outbuff = 0;
static int outpos = 0;
static int outmax = 0;

static void don_make_silence(int duration);

LISP FT_Donovan_Load_Diphones(LISP params)
{
    if (don_config != 0)
	delete_config(don_config);
    don_config = make_config();

    don_config->index_file=wstrdup(get_param_str("index_file",params,"index"));
    don_config->diphone_file =
	wstrdup(get_param_str("diphone_file",params,"diphs"));

    if (load_speech(don_config) != 0)  // load in the diphones
	festival_error();

    return NIL;
}

static void delete_config(CONFIG *config)
{
    (void) config;
}

static CONFIG *make_config(void)
{
    // Allocate a new config structure
    CONFIG *config = walloc(CONFIG,1);
    config->input_file = 0;
    config->output_file = 0;
    config->index_file = 0;
    config->diphone_file = 0;
    config->hash_file = 0;
    config->format = 0;
    config->ifd = 0;
    config->ofd = 0;
    config->xfd = 0;
    config->dfd = 0;

    return config;
}

LISP FT_Donovan_Synthesize_Utt(LISP utt)
{
    EST_Utterance *u = get_c_utt(utt);
    EST_Item *item = 0;
    SPN *ps;
    ACOUSTIC *as;

    if (nindex == 0)
    {
	cerr << "Festival: no donovan diphones loaded\n";
	festival_error();
    }

    don_random_seed = 1;  // so resynthesizing an utterance is always the same

    /* Build structure */
    ps = make_spn(*u);   // get info from utterance structure

    /* This doesn't work if there are less than two phones so */
    /* deal with those cases explicitly                       */
    if (ps->p_sz < 1)
	outpos = 0;
    else if (ps->p_sz < 2)
	don_make_silence(ps->duration[0]);
    else
    {
	as = make_as(ps);

	/* do the actual synthesis */
	phonstoframes(ps,as);
	durations(ps,as);
	calc_pitch(ps,as);
	makewave(don_config,as);

	delete_as(as);
    }
    delete_spn(ps);

    // Add wave as stream into utterance
    EST_Wave *w = new EST_Wave;
    w->resize(outpos,1);
    for (int i=0; i<w->length(); i++)
	w->a_no_check(i) = outbuff[i];
    w->set_sample_rate(SR);

    item = u->create_relation("Wave")->append();
    item->set_val("wave",est_val(w));

    return utt;
}

static void don_make_silence(int duration)
{
    // Make silence for size of the first (and only) phone
    // duation is in sample points
    int i;
    short *buff = walloc(short,duration);
    for (i=0; i < duration; i++)
	buff[i] = 0;
    audio_play(buff,sizeof(short),duration,NULL);
    wfree(buff);
}

static SPN *make_spn(EST_Utterance &u)
{
    //  Build initial structure for donovan code
    SPN *ps = walloc(SPN,1);
    EST_Relation *seg = u.relation("Segment");
    EST_Relation *targ = u.relation("Target");
    EST_Item *s;
    LISP cps;
    const char *ph_name;
    EST_Item *rt;
    int i,j;
    float pos,seg_start,seg_dur;

    ps->p_sz = seg->length();
    ps->p_max = ps->p_sz+1;
    ps->t_sz = num_leaves(targ->head());
    ps->t_max = ps->t_sz+1;
    ps->phons = walloc(char *,ps->p_max);
    ps->duration = walloc(int,ps->p_max);
    ps->cum_dur = walloc(int,ps->p_max);
    ps->pb = walloc(int,ps->p_max);
    ps->scale = walloc(float,ps->p_max);
    ps->diphs = walloc(char *,ps->p_max);
    for (i=0; i<ps->p_sz; i++)
	ps->diphs[i] = walloc(char,8);

    ps->pc_targs = walloc(int,ps->t_max);
    ps->targ_phon = walloc(int,ps->t_max);
    ps->targ_freq = walloc(int,ps->t_max);
    ps->abs_targ = walloc(int,ps->t_max);

    for (j=i=0,s=seg->first(); s != 0; s=s->next(),i++)
    {
	if (((cps=ft_get_param("PhoneSet")) == NIL) ||
	    ((streq(get_c_string(cps),"holmes"))))
	    ph_name = s->name();
	else
	    ph_name = map_phone(s->name(),get_c_string(cps),"holmes");
	ps->phons[i] = wstrdup(ph_name);
	seg_start = ffeature(s,"segment_start");
	seg_dur = ffeature(s,"segment_duration");
	ps->duration[i] = (int)(seg_dur * 10000);  /* in frames */
	if (i>0)
	    ps->cum_dur[i] = ps->cum_dur[i-1];
	else
	    ps->cum_dur[i] = 0;
	ps->cum_dur[i] += ps->duration[i];
	for (rt = daughter1(s,"Target");
	     rt != 0;
	     rt = rt->next(),j++)
	{
	    ps->targ_phon[j] = i;
	    ps->targ_freq[j] = rt->I("f0");
	    pos = ((rt->F("pos") - seg_start) / seg_dur) * 99.9;
	    ps->pc_targs[j] = (int)pos;
	}
    }

    // makewave thinks its writing to a file but its actually writting
    // to an incore buffer.  We allocate it here and make it bigger if
    // necessary
    if (outbuff != NULL)
	wfree(outbuff);
    if (i == 0)
	outmax = 10;
    else
	outmax = (int)(ps->cum_dur[i-1]*1.1);
    outbuff = walloc(short,outmax);
    outpos = 0;

    return ps;

}

static void delete_spn(SPN *ps)
{
    // claim back the space from ps
    int i;

    if (ps == NULL)
	return;

    for (i=0; i<ps->p_sz; i++)
    {
	wfree(ps->diphs[i]);
	wfree(ps->phons[i]);
    }
    wfree(ps->phons);
    wfree(ps->duration);
    wfree(ps->cum_dur);
    wfree(ps->pb);
    wfree(ps->scale);
    wfree(ps->diphs);

    wfree(ps->pc_targs);
    wfree(ps->targ_phon);
    wfree(ps->targ_freq);
    wfree(ps->abs_targ);

    wfree(ps);

    return;
}

static ACOUSTIC *make_as(SPN *ps)
{
    ACOUSTIC *as = walloc(ACOUSTIC,1);
    int nframes = ps->cum_dur[ps->p_sz-1];
    int npp = nframes * 2;

    as->p_sz = 0;
    as->f_sz = 0;
    as->p_max = npp;
    as->f_max = nframes;

    as->mcebuf = walloc(FRAME*,nframes);
    as->duration = walloc(short,nframes);
    as->pitch = walloc(short,npp);

    return as;
}

static void delete_as(ACOUSTIC *as)
{

    if (as == NULL)
	return;
    wfree(as->mcebuf);
    wfree(as->duration);
    wfree(as->pitch);
    wfree(as);

    return;
}

void as_realloc(int nframes, int npp, ACOUSTIC *as)
{
    // I don't think this will ever be called in Festival
    (void)nframes;
    (void)npp;
    (void)as;

    cerr << "Donovan diphones: as_realloc called unexpectedly\n";
    festival_error();

}

void audio_play(short *start,int sz,int number,CONFIG *config)
{
    // The lower level system thinks its calling an original function
    // but here we intercept the output and put in a EST_Wave class
    // This function will be called a number of times, but we know
    // (roughly) what the maximum size will be, but just in case
    // we make it bigger if necessary
    (void)config;

    if (outpos+number > outmax)
    {
	int noutmax = (int)((float)(outpos+number)*1.1);
	short *noutbuf = walloc(short,noutmax);
	memmove(noutbuf,outbuff,sizeof(short)*outpos);
	wfree(outbuff);
	outbuff = noutbuf;
	outmax = noutmax;
    }

    memmove(&outbuff[outpos],start,number*sz);
    outpos += number;
}

void festival_donovan_init(void)
{

    // Donovan (Isard) LPC diphone set

    proclaim_module("donovan");

    init_subr_1("Donovan_Init",FT_Donovan_Load_Diphones,
    "(Donovan_Init PARAMS)\n\
  Initialize the Donovan LPC diphone database.  PARAMS are an assoc list\n\
  of parameter name and value.  The two parameters are index_file (value is\n\
  a pathname for \"diphlocs.txt\") and diphone_file (value is a pathname\n\
  for \"lpcdiphs.bin\").  [see LPC diphone synthesizer]");
    festival_def_utt_module("Donovan_Synthesize",FT_Donovan_Synthesize_Utt,
    "(Donovan_Synthesize UTT)\n\
  Synthesize a waveform using the Donovan LPC diphone synthesizer.\n\
  This is called from Synthesize when the Synth_Method Parameter has the\n\
  value Donovan. [see LPC diphone synthesizer]");

}


text:
<?php if( ! empty($page)) :?>

	<?php

		$id = $page['id_page'];
		$title = ($page['title'] != '') ? $page['title'] : $page['name'];
		$status = (!$page['online']) ? 'offline' : 'online' ;
	?>

		<li class="sortme" data-id="<?php echo $id; ?>">

			<a class="icon unlink right" data-id="<?php echo $id; ?>">

			<a style="overflow:hidden;height:16px;display:block;" class="pl5 pr10 page page<?php echo $id; ?> <?php echo $status ;?>" title="<?php echo lang('ionize_label_edit'); ?>" data-id="<?php echo $id; ?>"><?php echo $title; ?>

<?php else :?>

		<?php echo lang('ionize_drop_maintenance_page_here'); ?>

<?php endif ;?>


text:
from msrest.serialization import Model

class ApplicationGatewayWebApplicationFirewallConfiguration(Model):
    """Application gateway web application firewall configuration.

    All required parameters must be populated in order to send to Azure.

    :param enabled: Required. Whether the web application firewall is enabled
     or not.
    :type enabled: bool
    :param firewall_mode: Required. Web application firewall mode. Possible
     values include: 'Detection', 'Prevention'
    :type firewall_mode: str or
     ~azure.mgmt.network.v2017_03_01.models.ApplicationGatewayFirewallMode
    :param rule_set_type: Required. The type of the web application firewall
     rule set. Possible values are: 'OWASP'.
    :type rule_set_type: str
    :param rule_set_version: Required. The version of the rule set type.
    :type rule_set_version: str
    :param disabled_rule_groups: The disabled rule groups.
    :type disabled_rule_groups:
     list[~azure.mgmt.network.v2017_03_01.models.ApplicationGatewayFirewallDisabledRuleGroup]
    """

    _validation = {
        'enabled': {'required': True},
        'firewall_mode': {'required': True},
        'rule_set_type': {'required': True},
        'rule_set_version': {'required': True},
    }

    _attribute_map = {
        'enabled': {'key': 'enabled', 'type': 'bool'},
        'firewall_mode': {'key': 'firewallMode', 'type': 'str'},
        'rule_set_type': {'key': 'ruleSetType', 'type': 'str'},
        'rule_set_version': {'key': 'ruleSetVersion', 'type': 'str'},
        'disabled_rule_groups': {'key': 'disabledRuleGroups', 'type': '[ApplicationGatewayFirewallDisabledRuleGroup]'},
    }

    def __init__(self, **kwargs):
        super(ApplicationGatewayWebApplicationFirewallConfiguration, self).__init__(**kwargs)
        self.enabled = kwargs.get('enabled', None)
        self.firewall_mode = kwargs.get('firewall_mode', None)
        self.rule_set_type = kwargs.get('rule_set_type', None)
        self.rule_set_version = kwargs.get('rule_set_version', None)
        self.disabled_rule_groups = kwargs.get('disabled_rule_groups', None)


text:
namespace eclipse {

using vec_str = std::vector<std::string>;

class FileLeader: public Node {
  public:
    FileLeader(network::ClientHandler*);
    ~FileLeader();

    //! @brief Insert file metadata and compute block metadata.
    unique_ptr<messages::Message> file_insert(messages::FileInfo*);

    //! Confirm that all the blocks has been uploaded.
    bool file_insert_confirm(messages::FileInfo*);

    //! Return a description of the blocks containing the file.
    std::shared_ptr<messages::Message> file_request(messages::FileRequest*);

    bool file_delete(messages::FileDel*);

    //! Fill the param with the list of files.
    bool list(messages::FileList*);

    bool file_exist(std::string);

    //! Update the file with the new size and blocks.
    bool file_update(messages::FileUpdate*);

    void metadata_save(messages::MetaData*);

    //! Remove everything and create tables.
    bool format();

  protected:
    void replicate_metadata();
    Directory directory;
    Local_io local_io;
    std::unique_ptr<Histogram> boundaries;
    std::map<std::string, std::shared_ptr<messages::FileDescription>> current_file_arrangements;
    int network_size;

    void find_best_arrangement(messages::FileDescription* file_desc);
};

}


text:
function caml_hexstring_of_float() {
  // https://github.com/ocsigen/js_of_ocaml/issues/403
  // Should be available when js_of_ocaml 2.8 is released
  throw new Error('caml_hexstring_of_float: not implemented in JS');
}


text:
'use strict';

const fs = require('fs');
const path = require('path');
const http = require('http');
const mm = require('egg-mock');
const fixtures = path.join(__dirname, 'fixtures');
const eggPath = path.join(__dirname, '..');

exports.app = (name, options) => {
  options = formatOptions(name, options);
  const app = mm.app(options);
  return app;
};

/**
 * start app with cluster mode
 *
 * @param {String} name - cluster name.
 * @param {Object} [options] - optional
 * @return {App} app - Application object.
 */
exports.cluster = (name, options) => {
  options = formatOptions(name, options);
  return mm.cluster(options);
};

let localServer;

exports.startLocalServer = () => {
  return new Promise((resolve, reject) => {
    if (localServer) {
      return resolve('http://127.0.0.1:' + localServer.address().port);
    }
    localServer = http.createServer((req, res) => {
      req.resume();
      req.on('end', () => {
        res.statusCode = 200;
        if (req.url === '/get_headers') {
          res.setHeader('Content-Type', 'json');
          res.end(JSON.stringify(req.headers));
        } else {
          res.end(`${req.method} ${req.url}`);
        }
      });
    });

    localServer.listen(0, err => {
      if (err) return reject(err);
      return resolve('http://127.0.0.1:' + localServer.address().port);
    });
  });
};
process.once('exit', () => localServer && localServer.close());

exports.getFilepath = name => {
  return path.join(fixtures, name);
};

exports.getJSON = name => {
  return JSON.parse(fs.readFileSync(exports.getFilepath(name)));
};

function formatOptions(name, options) {
  let baseDir;
  if (typeof name === 'string') {
    baseDir = name;
  } else {
    // name is options
    options = name;
  }
  return Object.assign({}, {
    baseDir,
    customEgg: eggPath,
    cache: false,
  }, options);
}


text:
Hangman
=======
![Logo](https://raw.githubusercontent.com/brpandey/elixir-hangman/master/priv/images/hangman.jpg)

> Definition of Hangman
>
> Hangman is a paper and pencil guessing game for two or more players.
> One player thinks of a word, phrase or sentence and the other tries
> to guess it by suggesting letters or numbers,
> within a certain number of guesses.
>
–  [Wikipedia](https://en.wikipedia.org/wiki/Hangman_(game))

Plays really fun hangman word games. What did you expect? :)

Plays interactive games allowing the user to choose letters
or allows the computer to guess instead.  Supports parallel play using
CPU cores concurrently. Only when the set of secrets is 40 or greater
is this speedup tangible. The max incorrect guesses is 5, 6 incorrect guesses
we lose the game.

## Noteworthy

* Comics: [9 Ways of Hangman](http://i.imgur.com/m3dh9ny.jpg)

* Game play design: [README DIAGRAMS](https://github.com/brpandey/elixir-hangman/blob/master/README%20DIAGRAMS.pdf)

* Feature highlights: [FEATURES](https://github.com/brpandey/elixir-hangman/blob/master/FEATURES.md)

## Usage

* Hangman runs both interactive human games with manually specified
secrets e.g. --secrets or runs games with randomly generated secrets
e.g. --random.  Interactivity is denoted by the player type `-t`, with
values of either human or robot.

* The random `-r` secret generation option allows you to play without
knowing the secret hangman word(s) beforehand as the system randomly
selects the secret(s) to play against.

* Robot games are auto-guessed based on simple strategy heuristics.

* Player game archival can be captured through logging, e.g. --log option
The display and log options are exclusive to the command line client.
The human guessing wait timeout `-w` option allows values between 0 secs and 20 secs
to choose a letter. The parallel `-p` option allows games to be played on
all the cores of your system

Command Line options:

```elixir
    --name (player id) --type ("human" or "robot")
    --random (num random secrets, max 1000)
    [--secret (hangman word(s)) --baseline]
    [--log --display --wait (e.g. 15 secs)] [--parallel]

    or aliases:

    -n (player id) -t ("human" or "robot") -r (num random secrets, max 1000)
    [-s (hangman word(s)) -b] [-l -d -w] [-p]
```

## Install & Run

   [Install Elixir](http://elixir-lang.org/install.html)

### Step 1 - Git clone
```
    $  git clone --depth 10 https://github.com/brpandey/hangman.git
```

### Step 2 - Build executable
```
    $  cd hangman
    $  mix compile
    $  mix escript.build
```

### Step 3 - Run game
```
    $  ./hangman_game -n toad -t robot -r 3 -d
```

or alternatively you can run the release version for the web mode

```
    $  mix deps.get
    $  MIX_ENV=prod mix compile --no-debug-info
    $  MIX_ENV=prod mix release

    $  rel/hangman_game/bin/hangman_game start or use iex -S mix
```

## Examples

### Game Play - 1

Command Line - Robot type with secret specified with display feed

```elixir
    ./hangman_game -n mario -t robot -s spectacle -d

    mario_feed --> Game 1 has started
    mario_feed Game 1, secret length --> 9
    mario_feed Game 1, letter --> e
    mario_feed Game 1, Round 1, status --> --E-----E; score=1; status=KEEP_GUESSING

    mario_feed Game 1, letter --> a
    mario_feed Game 1, Round 2, status --> --E--A--E; score=2; status=KEEP_GUESSING

    mario_feed Game 1, letter --> l
    mario_feed Game 1, Round 3, status --> --E--A-LE; score=3; status=KEEP_GUESSING

    mario_feed Game 1, letter --> n
    mario_feed Game 1, Round 4, status --> --E--A-LE; score=4; status=KEEP_GUESSING

    mario_feed Game 1, letter --> c
    mario_feed Game 1, Round 5, status --> --EC-ACLE; score=5; status=KEEP_GUESSING

    mario_feed Game 1, word --> spectacle
    mario_feed Game 1, Round 6, status --> SPECTACLE; score=5; status=GAME_WON

    mario_feed Game Over!! -->
    Game Over! Average Score: 5.0, Games: 1, Scores:  (SPECTACLE: 5)
```

### Game Play - 2

Command Line - Human type with 2 random words requested

```elixir
    ./hangman_game -n luigi -t human -r 2

    Player luigi, Round 1, ----------; score=0; status=KEEP_GUESSING.
    5 weighted letter choices :  e*:15606 i:13788 s:13226 r:11925 a:11763 (* ...)
    [Please input letter choice]

    Player luigi, Round 2, ----------; score=1; status=KEEP_GUESSING.
    5 weighted letter choices :  i*:3852 a:3276 o:3157 n:2993 s:2968 (* robot...)
    [Please input letter choice]

    Player luigi, Round 3, ------I---; score=2; status=KEEP_GUESSING.
    5 weighted letter choices :  s*:309 o:255 a:246 t:214 n:207 (* robot choice)
    [Please input letter choice]

    Player luigi, Round 4, ------I--S; score=3; status=KEEP_GUESSING.
    5 weighted letter choices :  n:106 o*:104 a:98 t:70 l:57 (* robot choice)
    [Please input letter choice]

    Player luigi, Round 5, ------I-NS; score=4; status=KEEP_GUESSING.
    5 weighted letter choices :  a*:39 o:38 t:36 l:21 c:15 (* robot choice)
    [Please input letter choice]

    Possible hangman words left 3 words: ["barbarians", "dalmatians", "mammalians"]

    Player luigi, Round 6, -A--A-IANS; score=5; status=KEEP_GUESSING.
    5 weighted letter choices :  l:2 m:2 b*:1 d:1 r:1 (* robot choice)
    [Please input letter choice]

    Player luigi, Round 7, -A--A-IANS; score=6; status=KEEP_GUESSING.
    Last word left: barbarians

    BARBARIANS; score=6; status=GAME_WON

    Player luigi, Round 1, ------; score=0; status=KEEP_GUESSING.
    5 weighted letter choices :  e*:9356 s:6981 a:6599 r:6097 i:5518 (* robot..)
    [Please input letter choice]

    Player luigi, Round 2, -E--E-; score=1; status=KEEP_GUESSING.
    5 weighted letter choices :  r*:273 d:266 s:199 t:152 l:146 (* robot choice)
    [Please input letter choice]

    Player luigi, Round 3, -E--ER; score=2; status=KEEP_GUESSING.
    5 weighted letter choices :  t*:50 l:41 d:32 n:30 a:29 (* robot choice)
    [Please input letter choice]

    Player luigi, Round 4, -E--ER; score=3; status=KEEP_GUESSING.
    5 weighted letter choices :  l*:32 d:28 a:22 n:19 i:15 (* robot choice)
    [Please input letter choice]

    Player luigi, Round 5, -E--ER; score=4; status=KEEP_GUESSING.
    5 weighted letter choices :  d:18 n*:17 a:12 i:11 s:10 (* robot choice)
    [Please input letter choice]

    Possible hangman words left, 7 words: ["deafer", "decker", "defier",
    "deicer", "denier", "denser", "dewier"]

    Player luigi, Round 6, DE--ER; score=5; status=KEEP_GUESSING.
    5 weighted letter choices :  i:4 c*:2 f:2 n:2 a:1 (* robot choice)
    [Please input letter choice]

    Possible hangman words left, 3 words: ["defier", "denier", "dewier"]

    Player luigi, Round 7, DE-IER; score=6; status=KEEP_GUESSING.
    3 weighted letter choices :  f*:1 n:1 w:1 (* robot choice)
    [Please input letter choice]

    Game Over! Average Score: 6.5, Games: 2, Scores:  (BARBARIANS: 6) (DEFIER: 7)
```

### Game Play - 3

Command Line - Parallel option with 100 secrets

Open another terminal window and type `top` and press `1` to see all cores or `htop` which will automatically show the cores
After the below command has been issued, check the the cpu utilization of the cores while this runs!

```elixir
$ ./hangman_game -n yoshi -p -r 100
   "Game Over! Average Score: 6.91, Games: 100, Scores: (BARRELS: 5) (BETIDES: 6)
   (BRANDERS: 8) (BRILLIANTLY: 3) (BUCKISH: 10) (BUCKSHEES: 2) (CAGILY: 10)
   (CHAFFIEST: 9) (CHARBROILER: 5) (CIRCULATABLE: 4) (CLOBBERED: 9) (COENURI: 5)
   (CONCURRENT: 6) (CONSULTANTS: 7) (COWEDLY: 8) (CURBER: 25) (CYANOGENS: 7)
   (DANDRIFFS: 8) (DARKENS: 10) (DEFLECTABLE: 4) (DICLINY: 7) (DOBIES: 8)
   (DOWNPLAYS: 7) (DOZENS: 8) (ECOTYPES: 7) (ELECTROMETERS: 2) (ELEGIZING: 5)
   (ENTASIS: 5) (ERYTHORBATE: 3) (EXTEMPORIZER: 9) (EXTENSIONALITY: 5)
   (FLAGPOLE: 6) (FRAGMENTATES: 3) (GASTRONOMY: 6) (GEMLIKE: 7) (GENUINENESSES: 2)
   (HETEROCLITE: 3) (IMPRESSION: 3) (INNOCUOUSLY: 4) (JACKFISH: 8) (LAYABOUT: 8)
   (LEPIDOPTERISTS: 2) (LINGERER: 8) (LOVINGNESSES: 6) (LUMINOUSNESSES: 5)
   (MAILABILITIES: 5) (MARABOUTS: 7) (MICROANALYST: 4) (MISPENNED: 6)
   (MISYOKING: 8) (MULTIENGINES: 3) (NEOPHILIAS: 6) (NILGAIS: 5) (NONSALABLE: 4)
   (ORDEAL: 5) (OSCILLATES: 5) (OVERHUNTED: 7) (PACHYSANDRA: 3) (PARIS: 25)
   (PHILIPPICS: 4) (PLACARDING: 6) (PREDELIVERIES: 3) (PYLORUS: 25) (PYRRHICS: 8)
   (RACED: 6) (REEFS: 8) (RELUCTANT: 6) (REPERCUSSION: 4) (RHIZOMES: 5)
   (ROOMETTE: 5) (ROUBLES: 10) (SAFROL: 9) (SHIVER: 10) (SNOWMOBILIST: 5)
   (SOCIALIZED: 5) (SOVEREIGNS: 4) (SPRINGBOARD: 4) (STEDFAST: 5) (STRAIGHTEN: 6)
   (SUBCENTERS: 5) (SUBSHELLS: 7) (SWIMMINGLY: 6) (SYMMETRIZATIONS: 4)
   (SYMPHONIST: 7) (TENSIOMETER: 3) (TIGHTENER: 3) (TUTUS: 25) (UNBRILLIANT: 4)
   (UNHARNESSED: 3) (UNINTERRUPTEDLY: 2) (VERBALISM: 7) (WEATHERBOARDED: 4)
   (WIDGEON: 8) (WINES: 25) (WINIER: 25) (WONDERMENTS: 6) (WOODHENS: 9) (XENIAS: 8)
   (ZIGGURAT: 6) (ZIRCONIUM: 5)"
```

### Game Play - 4

Web Example - Single Game

```elixir
    $ iex -S mix
    Erlang/OTP 19 [erts-8.0] [source] [64-bit] [smp:2:2] [async-threads:10] ...

    iex>
    HTTPoison.get("http://127.0.0.1:3737/hangman?name=princess&secret=librarian")
    {:ok,
     %HTTPoison.Response{body: "(H) ---------; score=1; status=KEEP_GUESSING
    (H) ----A--A-; score=2; status=KEEP_GUESSING
    (H) -I--A-IA-; score=3; status=KEEP_GUESSING
    (H) -IB-A-IA-; score=4; status=KEEP_GUESSING
    (H) LIBRARIAN; score=4; status=GAME_WON
    (H) Game Over! Average Score: 4.0, Games: 1, Scores:  (LIBRARIAN: 4) ",
      headers: [{"server", "Cowboy"}, {"date", "Wed, 30 Nov 2016 03:01:34 GMT"},
       {"content-length", "289"},
       {"cache-control", "max-age=0, private, must-revalidate"},
       {"content-type", "text/plain; charset=utf-8"}], status_code: 200}}

```

### Game Play - 5

Word not in dictionary - Fault-Tolerance of Player Worker Crash

```elixir
    $ ./hangman_game -n bowser -s "apache azerbaijan enthralled"

    APACHE; score=4; status=GAME_WON

    18:49:15.448 [error] GenServer {:n, :l, {:player_worker, "bowser"}} terminating
    ** (HangmanError) Word not in dictionary
        (hangman_game) lib/hangman/letter_strategy.ex:85:
        (hangman_game) lib/hangman/action_robot.ex:36:
        (hangman_game) lib/hangman/player_fsm.ex:74:
        (hangman_game) lib/hangman/player_worker.ex:122:
    Last message: :proceed
    State: %Hangman.Player.FSM{data: Action.Robot<[display: false]
    [id: "bowser", pid: #PID<0.261.0>, game_pid: #PID<0.260.0>, round_data:
    [game_num: 1, round_num: 5, guess: "overflight", guess_result: :incorrect_word,
    round_code: :guessing,
    round_status: "--ER--I---; score=5; status=KEEP_GUESSING",
    pattern: "--ER--I---", context: {:guessing, :incorrect_word, "overflight"}]]>,
    state: :setup}

    Game Over! Average Score: 4.5, Games: 2, Scores:
    (APACHE: 4) (AZERBAIJAN: 0) (ENTHRALLED: 5)
```

## Appendices

### Notes

* Unit and Integration tests are here
>   https://github.com/brpandey/elixir-hangman/tree/master/test/hangman
>
> Finished in 74.9 seconds
> 1 property, 165 tests, 0 failures

* Optional -- configure `config/config.exs` to see inner game play details.
Specifically change :info to :debug and then run `mix compile` and then `mix escript.build`

```elixir

    config :logger, :console,
-->   level: :info,
      format: "\n$time $metadata[$level] $levelpad$message\n",
      metadata: [:module]
```

* The web and cli modes are able to play parallel games using all CPU cores. To tangibly
  see the speedup of parallelization use 40 secrets or more.  For cli mode, simply use the
  random option to specify a value like 60 secrets with the parallel option.  e.g. -n luigi -p -r 60
  By default web mode plays in parallel

* The hangman game handles word not in dictionary cases.  The current procedure is the Player.Worker crashes and is restarted to resume where it left off.

* The dictionary ingestion is handled through multiple GenStage Flows.  Lastly it is written to an ets dump file for near instantaneous load.

* If a "mix test" is run, the free version of Quick Check from quvic should be installed to avoid errors

* The hangman file directory structure is flat in lib/hangman.  There should technically be
directories under lib/hangman following the dotted modules names but for portfolio
simplicity purposes all are in the top level directory.

* In the doc directory are generated html docs with Github integration: [Sample](https://github.com/brpandey/elixir-hangman/blob/master/CounterSnapshot.pdf)

* Running 100 hangman games in parallel takes about roughly 10 secs on a dual-core

* Hangman configuration is tunable (perhaps you want to compare different pool size, max_demand size combinations) -->

```elixir

    config :hangman_game,
      max_wrong_guesses: 5, # Max incorrect hangman guess chances
      port: 3737,
      min_secret_length: 3,
      max_secret_length: 28,
      max_guess_wait: 20000, # 20 secs to choose for letter under human cli
      default_guess_wait: 5000, # 5 secs to choose for letter under human cli
      min_random_word_length: 5,
      max_random_word_length: 15,
      max_random_words: 1000, # Max randoms secrets to play against
      words_container_size: 500, # Number of words to group by when processing dict
      random_words_per_container: 20, # Given words container choose 20 randoms
      shard_flow_max_demand: 2, # Maximum amount of events that must be in flow
      reduction_pool_size: 10, # 10 reduction workers
      shard_size_words: 10 # 10 words per shard
```

### Wishlist

* One game server being able to handle multiple concurrent different player games

* Multiple players on a single game. Players being able to communicate with each other
  e.g. using a lookup registry to find other players and being able to play in tandem

* A new type cyborg which alternates between human and robot playing

* A stumper word process which plays the games before hand with all the words and identifies
the word stumpers for use in real game play

* New strategy algorithms which try to learn player's guessing style - aka machine learning.
As well as difficulty level setting: e.g. easy, medium, or hard

* Truly distributed hangman running on multiple nodes and machines to avoid a single point of failure

## Thank You

Enjoy playing!

**Bibek Pandey**


text:
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using CommonSerializer.Newtonsoft.Json;
using Kts.Remoting.Benchmarks;
using Kts.Remoting.Shared;
using vtortola.WebSockets;
using Xunit;
using Xunit.Abstractions;

namespace Kts.Remoting.Tests
{
	public class SystemWebSocketsToVtortolaCircle
	{
		private readonly ITestOutputHelper _testOutputHelper;

		public SystemWebSocketsToVtortolaCircle(ITestOutputHelper testOutputHelper)
		{
			_testOutputHelper = testOutputHelper;
		}

		public interface IMyService
		{
			Task<int> Add(int a, int b);
		}

		public class MyService : IMyService
		{
			public Task<int> Add(int a, int b)
			{
				return Task.FromResult(a + b);
			}
		}

		[Fact]
		public void BasicRoundTrip()
		{
			var serializer = new JsonCommonSerializer();

			var port = new Random().Next(6000, 60000);

			var options = new WebSocketListenerOptions();
			options.SubProtocols = new[] { "SignalR" };
			var listener = new WebSocketListener(new IPEndPoint(IPAddress.Loopback, port), options);
			var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(listener);
			listener.Standards.RegisterStandard(rfc6455);
			var serverTransport = listener.GenerateTransportSource();
			var serverRouter = new DefaultMessageRouter(serverTransport, serializer);
			serverRouter.AddService<IMyService>(new MyService());
			listener.Start();

			var client = new ClientWebSocket();
			client.Options.AddSubProtocol("SignalR");
			var clientTransport = client.GenerateTransportSource();
			var clientRouter = new DefaultMessageRouter(clientTransport, serializer);
			var proxy = clientRouter.AddInterface<IMyService>();
			client.ConnectAsync(new Uri("ws://localhost:" + port + "/"), CancellationToken.None).Wait();

			var result = proxy.Add(3, 4).Result;
			Assert.Equal(7, result);

			clientRouter.Dispose();
			clientTransport.Dispose();
			client.Dispose();

			serverRouter.Dispose();
			serverTransport.Dispose();
			listener.Dispose();
		}

		[Fact]
		public void Benchmark()
		{
			var serializer = new JsonCommonSerializer();

			var port = new Random().Next(30000, 60000);

			var options = new WebSocketListenerOptions();
			options.SubProtocols = new[] { "SignalR" };
			var listener = new WebSocketListener(new IPEndPoint(IPAddress.Loopback, port), options);
			var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(listener);
			listener.Standards.RegisterStandard(rfc6455);
			var serverTransport = listener.GenerateTransportSource();
			var serverRouter = new DefaultMessageRouter(serverTransport, serializer);
			serverRouter.AddService<ISumService>(new SumService());
			listener.Start();

			var client = new ClientWebSocket();
			client.Options.AddSubProtocol("SignalR");
			var clientTransport = client.GenerateTransportSource();
			var clientRouter = new DefaultMessageRouter(clientTransport, serializer);
			var proxy = clientRouter.AddInterface<ISumService>();
			client.ConnectAsync(new Uri("ws://localhost:" + port + "/"), CancellationToken.None).Wait();

			const int randCnt = 100;
			var rand = new Random(42);
			var randoms = new int[randCnt];
			for (int i = 0; i < randCnt; i++) randoms[i] = rand.Next(10000000, 20000000);

			var sw = new Stopwatch();
			long timeFromClient = 0, timeToClient = 0;
			const int cnt = 1000;
			for (int j = 0; j < cnt; j++)
			{
				sw.Start();
				var sum = proxy.Sum(randoms).Result;
				sw.Stop();
				Assert.Equal(randoms.Sum(), sum);
				for (int i = 0; i < randCnt; i++) randoms[i] = rand.Next(10000000, 20000000);
				var times = proxy.TimeDiff(Stopwatch.GetTimestamp()).Result;
				timeFromClient += times.Item1;
				timeToClient += Stopwatch.GetTimestamp() - times.Item2;
			}

			_testOutputHelper.WriteLine("Completed {0} sum passes in {1}ms", cnt, sw.ElapsedMilliseconds);
			_testOutputHelper.WriteLine("Client to server latency: {0}us", timeFromClient / cnt / 10);
			_testOutputHelper.WriteLine("Server to client latency: {0}us", timeToClient / cnt / 10);

			sw.Reset();
			var tree = new SumServiceTree();
			SumServiceTree.FillTree(tree, rand, 2);
			_testOutputHelper.WriteLine("Starting large message transfer.");
			sw.Start();
			var result = proxy.Increment(tree).Result;
			sw.Stop();
			Assert.Equal(tree.Leaf + 1, result.Leaf);
			_testOutputHelper.WriteLine("Completed large transfer in {0}ms", sw.Elapsed.TotalMilliseconds);

			clientRouter.Dispose();
			clientTransport.Dispose();
			client.Dispose();

			serverRouter.Dispose();
			serverTransport.Dispose();
			listener.Dispose();
		}
	}
}


text:
turing-stuff
============

Random stuff done in turing. Everything is licensed under MIT. If you are to use any part of the code contained within the files in this repository, you must copy and paste the following comment snippet before the header.

```csharp


text:
package minecraft

import (
	"context"

	"github.com/kleister/kleister-api/pkg/model"
	"github.com/opentracing/opentracing-go"
)

// TracingRequestID returns the request ID as string for tracing
type TracingRequestID func(context.Context) string

type tracingService struct {
	service   Service
	requestID TracingRequestID
}

// NewTracingService wraps the Service and provides tracing for its methods.
func NewTracingService(s Service, requestID TracingRequestID) Service {
	return &tracingService{
		service:   s,
		requestID: requestID,
	}
}

func (s *tracingService) List(ctx context.Context) ([]*model.Minecraft, error) {
	span, ctx := opentracing.StartSpanFromContext(ctx, "minecraft.Service.List")
	span.SetTag("request", s.requestID(ctx))
	defer span.Finish()

	return s.service.List(ctx)
}

func (s *tracingService) Update(ctx context.Context) error {
	span, ctx := opentracing.StartSpanFromContext(ctx, "minecraft.Service.Update")
	span.SetTag("request", s.requestID(ctx))
	defer span.Finish()

	return s.service.Update(ctx)
}


text:
@interface TNDRAdCardCellInformationView : UIView
{
}

- (id)initWithFrame:(struct CGRect)arg1;
- (void)layoutAdNameLabel;
- (void)layoutArtworkView;
- (void)resetView;
- (void)setup;
- (void)setupAdNameLabel;
- (void)setupArtworkView;

@end


text:
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
 * Runtime type representation; master is type.go
 *
 * The *Types here correspond 1-1 to type.go's *Type's, but are
 * prefixed with an extra header of 2 pointers, corresponding to the
 * interface{} structure, which itself is called type Type again on
 * the Go side.
 */

typedef struct CommonType CommonType;
typedef struct UncommonType UncommonType;
typedef struct InterfaceType InterfaceType;
typedef struct Method Method;
typedef struct IMethod IMethod;
typedef struct SliceType SliceType;
typedef struct FuncType FuncType;

// Needs to be in sync with typekind.h/CommonSize
struct CommonType
{
	uintptr size;
	uint32 hash;
	uint8 _unused;
	uint8 align;
	uint8 fieldAlign;
	uint8 kind;
	Alg *alg;
	void *gc;
	String *string;
	UncommonType *x;
	Type *ptrto;
};

struct Method
{
	String *name;
	String *pkgPath;
	Type	*mtyp;
	Type *typ;
	void (*ifn)(void);
	void (*tfn)(void);
};

struct UncommonType
{
	String *name;
	String *pkgPath;
	Slice mhdr;
	Method m[];
};

struct Type
{
	void *type;	// interface{} value
	void *ptr;
	CommonType;
};

struct IMethod
{
	String *name;
	String *pkgPath;
	Type *type;
};

struct InterfaceType
{
	Type;
	Slice mhdr;
	IMethod m[];
};

struct MapType
{
	Type;
	Type *key;
	Type *elem;
};

struct ChanType
{
	Type;
	Type *elem;
	uintptr dir;
};

struct SliceType
{
	Type;
	Type *elem;
};

struct FuncType
{
	Type;
	bool dotdotdot;
	Slice in;
	Slice out;
};


text:
class Api::V1::SessionsController < Devise::SessionsController
  before_filter :authenticate_api_key!
  before_filter :update_sanitized_params, if: :devise_controller?

  skip_before_filter :verify_authenticity_token,
                     :if => Proc.new { |c| c.request.format == 'application/json' }

  respond_to :json

  def create
    warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure")
    current_user.ensure_authentication_token
    render :status => 200,
           :json => { :success => true,
                      :info => "Logged in",
                      :data => { :auth_token => current_user.authentication_token,
                                 :csrf_param => request_forgery_protection_token,
                                 :csrf_token => form_authenticity_token,
                                 :id => current_user.id,
                                 :first_name => current_user.first_name,
                                 :last_name => current_user.last_name} }
  end

  def destroy
    Rails.logger.debug("api session distroy")
    warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure")
    current_user.update_column(:authentication_token, nil)
    render :status => 200,
           :json => { :success => true,
                      :info => "Logged out",
                      :data => {} }
  end

  def failure
    render :status => 401,
           :json => { :success => false,
                      :info => "Login Failed",
                      :data => {} }
  end

  private

  def update_sanitized_params
    devise_parameter_sanitizer.for(:sign_in) {|u| u.permit(:username, :email, :password, :password_confirmation)}
  end

  def authenticate_api_key!
    Rails.logger.debug("authenticate_api_key")
    authenticate_or_request_with_http_token do |token, options|
      ApiKey.exists?(access_token: token)
    end
  end

end