text:
This package provides a Garmin API Client for the PHP League's [OAuth 1.0 Client](https://github.com/thephpleague/oauth1-client).

## Installation

```
composer require techgyani/garmin-wellness
```

## Usage

Usage is the same as The League's OAuth client, using `techgyani\OAuth1\Client\Server\Garmin` as the provider.

```php
$server = new techgyani\OAuth1\Client\Server\Garmin([
    'identifier'   => 'your-client-id',
    'secret'       => 'your-client-secret',
    'callback_uri' => 'http://callback.url/callback',
]);
```

Please refer to the Garmin wellness API for the available endpoints.

Below are the steps to test examples :
```
1. Copy examples in your web-server root if needed.
2. Define consumerKey, consumerSecret and callback_uri enviornment variables or alternatively set them directly in all php files in example. Below is the .htaccess code to demonstrate how you may do it.

setEnv consumerKey sddsadas
setEnv consumerSecret fdsfdsfsd
setEnv callback_uri http://localhost/garmin-wellness/vendor/techgyani/garmin-wellness/examples/garmin_callback.php

3. Now run examples/index.php in your browser. It should redirect you to the garmin server, where you need to login and authorize the application.
4. Once authorization is done user will be redirected to examples/garmin_api_test.php. There you must see activity summary output if everything is okay.
5. You can change parameter values in examples/garmin_api_test.php because it is picking up user token from the session.
```


text:
class Cask::Artifact::CaskroomOnly < Cask::Artifact::Pkg
  def self.artifact_dsl_key
    :caskroom_only
  end

  def install
    # do nothing
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace oscarpalmer\Yogurt;

/**
 * Flavour, the template object.
 */
class Flavour
{
    /**
     * @var array Data to render.
     */
    protected $data;

    /**
     * @var string Filename for template.
     */
    protected $filename;

    /**
     * @var Yogurt Our Yogurt.
     */
    protected $yogurt;

    /**
     * Create a new Flavour with Yogurt and flavour name.
     *
     * @param Yogurt $yogurt Yogurt for settings and parsing.
     * @param string $name   Flavour (template) name.
     */
    public function __construct(Yogurt $yogurt, $name)
    {
        $this->yogurt = $yogurt;

        $this->setFilename($name);
    }

    /**
     * Set a new or change an existing data item magically.
     *
     * @param mixed $key   Key for item.
     * @param mixed $value Value for item.
     */
    public function __set($key, $value)
    {
        $this->data[$key] = $value;
    }

    /**
     * Return rendered template on direct access of Flavour object.
     */
    public function __toString()
    {
        return $this->taste();
    }

    /** Public functions. */

    /**
     * Add data to flavour.
     *
     * @param  array|object $data Data to add.
     * @return array        All the data.
     */
    public function data($data = null)
    {
        if (is_null($data) === false) {
            if (is_array($data) === false && is_object($data) === false) {
                throw new \InvalidArgumentException("Data must be either an array or an object.");
            }

            foreach ((object) $data as $key => $value) {
                $this->{$key} = $value;
            }
        }

        return $this->data;
    }

    /**
     * Array to object and then object to associative array.
     *
     * @return array|object Array or object of data.
     */
    public function getDataObject()
    {
        $data = $this->data;
        $data = static::itemToObject($data);
        $data = get_object_vars($data);

        return $data;
    }

    /**
     * Get current filename.
     *
     * @return string Filename.
     */
    public function getFilename()
    {
        return $this->filename;
    }

    /**
     * Set the filename.
     *
     * @param  string  $name Filename to set.
     * @return Flavour Flavour object for optional chaining.
     */
    public function setFilename($name)
    {
        if (is_string($name)) {
            $settings = $this->yogurt->getSettings();
            $filename = $settings["directory"] . "/$name";

            if (!preg_match("/\.{$settings['extension']}\z/", $filename)) {
                $filename .= ".{$settings['extension']}";
            }

            if (is_file($filename)) {
                $this->filename = $filename;

                return $this;
            }

            throw new \LogicException("The template \"{$filename}\" does not exist.");
        }

        throw new \InvalidArgumentException(
            "Filename must be a string, \"" .
            gettype($name) .
            "\" given."
        );
    }

    /**
     * Render the template.
     *
     * @param  array|object $data More data to add.
     * @return string       The rendered template.
     */
    public function taste($data = null)
    {
        $data = $this->data($data);
        $data = $this->getDataObject();

        $template = $this->yogurt->getDairy()->parse($this->filename);

        ob_start();

        extract($data);
        unset($data);

        set_error_handler("static::errorHandler");
        eval("?>{$template}");
        restore_error_handler();

        return ob_get_clean();
    }

    /** Static functions. */

    /**
     * Handle errors for the eval-function. Passes on the error if it's not a local error.
     *
     * @param  int     $number    Error level.
     * @param  string  $string    Error message.
     * @param  string  $file      Error file.
     * @param  int     $line      Error line.
     * @param  array   $variables Error variables.
     * @return boolean True if handled.
     */
    public static function errorHandler($number, $string, $file, $line, $variables)
    {
        if (strpos($file, __FILE__) !== 0) {
            return false;
        }

        $prefix = "

";
        $suffix = " on line {$line} in your template.

";

        echo($prefix . $string . $suffix);

        return true;
    }

    /**
     * Convert an item (array or object) to object.
     *
     * @param  array  $item item to convert.
     * @return object Converted item.
     */
    public static function itemToObject($item)
    {
        if (is_null($item)) {
            $item = new \stdClass;
        }

        return json_decode(json_encode($item), false);
    }
}


text:
package de.htw.vs.chat.command;

import de.htw.vs.chat.impl.ChatServer;
import de.htw.vs.shell.ConsoleUtil;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Objects;

@Component
public class ServerCommand implements CommandMarker {

	@CliCommand(value = "chat server", help = "Starts the chat server for the exercise 5.1")
	public void startServer() {
		ChatServer server = null;
		try {
			server = new ChatServer();
			server.start();
			System.out.println("Type \"exit\" to stop the server");
			boolean exit = false;
			do {
				String input = null;
				while ((input = ConsoleUtil.readline("")) != null) {
					exit = "exit".equalsIgnoreCase(input);
				}
			} while (server.isRunning && !exit);

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (server != null) {
				try {
					server.stop();
				} catch (Exception e) {}
			}
 		}
	}
}


text:
class DeveloperTESearcher < TimeEntrySearcher
  inject :current_user

  protected

  def scope
    TimeEntry.joins(:related_task).where(related_tasks: { user_id: current_user })
  end
end


text:
import sys
import os
import json
import time
from nlp_tools import tokenize_words, build_prob_language_model, generate_text_using_trigrams
from files_io import load_text, serialize, deserialize

if __name__ == '__main__':
    args = sys.argv[1:]
    N_WORDS = args[0]
    FILES_FOLDER = 'files'
    TMP_FOLDER = os.path.join(FILES_FOLDER, 'tmp')
    if not os.path.exists(TMP_FOLDER):
        os.makedirs(TMP_FOLDER)

    #print("loading text..")
    T0 = time.time()
    source_text_filename = 'eng_wiki.txt'
    source_text_path = os.path.join(FILES_FOLDER, source_text_filename)
    en_text = load_text(source_text_path)
    T1 = time.time()
    #print("\tdone in {0:.2f} sec".format(T1-T0))

    tmp_folder_content = os.listdir(TMP_FOLDER)
    # If temp folder doesn't yet contain serialized token list, tokenize text and serialize tokens
    if len(tmp_folder_content) == 0:
        #print("tokenizing words..")
        tokens = tokenize_words(en_text)
        tokenized_words_filename = 'tokenized_' + source_text_filename
        tokenized_words_path = os.path.join(TMP_FOLDER, tokenized_words_filename)
        serialize(tokens, tokenized_words_path)

    # Otherwise, deserialize tokens list. Much faster, as no need to wait tokenization time
    else:
        #print("temporary file found. Deserializing words..")
        tokenized_words_filename = tmp_folder_content[0]
        tokenized_words_path = os.path.join(TMP_FOLDER, tokenized_words_filename)
        tokens = deserialize(tokenized_words_path)

    T2 = time.time()
    #print("\tdone in {0:.2f} sec".format(T2-T1))

    #print("building probabilistic language model..")
    language_model = build_prob_language_model(tokens)
    T3 = time.time()
    #print("\tdone in {0:.2f} sec".format(T3-T2))

    #print("generating output text..")
    final_text = generate_text_using_trigrams(language_model, N_WORDS)
    T4 = time.time()
    #print("\tdone in {0:.2f} sec".format(T4-T3))

    #print("\ntotal execution time: {0:.2f} sec".format(T4-T0))
    response = {'error': 'false', 'data': final_text}
    print(json.dumps(response))


text:
package engine

import (
	"testing"

	"github.com/influxdb/influxdb/common"
	"github.com/influxdb/influxdb/parser"
	. "launchpad.net/gocheck"
)

type FilteringSuite struct{}

var _ = Suite(&FilteringSuite{})

// Hook up gocheck into the gotest runner.
func Test(t *testing.T) {
	TestingT(t)
}

func (self *FilteringSuite) TestInOperatorFiltering(c *C) {
	queryStr := "select * from t where column_one in (100, 85);"
	query, err := parser.ParseSelectQuery(queryStr)
	c.Assert(err, IsNil)

	series, err := common.StringToSeriesArray(`
[
 {
   "points": [
     {"values": [{"int64_value": 100},{"int64_value": 5 }], "timestamp": 1381346631, "sequence_number": 1},
     {"values": [{"int64_value": 85},{"int64_value": 6 }], "timestamp": 1381346631, "sequence_number": 1},
     {"values": [{"int64_value": 90 },{"int64_value": 15}], "timestamp": 1381346632, "sequence_number": 1}
   ],
   "name": "t",
   "fields": ["column_one", "column_two"]
 }
]
`)
	c.Assert(err, IsNil)
	result, err := Filter(query, series[0])
	c.Assert(err, IsNil)
	c.Assert(result, NotNil)
	c.Assert(result.Points, HasLen, 2)
	c.Assert(*result.Points[0].Values[0].Int64Value, Equals, int64(100))
	c.Assert(*result.Points[0].Values[1].Int64Value, Equals, int64(5))
	c.Assert(*result.Points[1].Values[0].Int64Value, Equals, int64(85))
	c.Assert(*result.Points[1].Values[1].Int64Value, Equals, int64(6))
}

func (self *FilteringSuite) TestFilteringWithGroupBy(c *C) {
	queryStr := "select sum(column_one) from t group by column_two where column_one = 85;"
	query, err := parser.ParseSelectQuery(queryStr)
	c.Assert(err, IsNil)

	series, err := common.StringToSeriesArray(`
[
 {
   "points": [
     {"values": [{"int64_value": 100},{"int64_value": 5 }], "timestamp": 1381346631, "sequence_number": 1},
     {"values": [{"int64_value": 85},{"int64_value": 6 }], "timestamp": 1381346631, "sequence_number": 1},
     {"values": [{"int64_value": 90 },{"int64_value": 15}], "timestamp": 1381346632, "sequence_number": 1}
   ],
   "name": "t",
   "fields": ["column_one", "column_two"]
 }
]
`)
	c.Assert(err, IsNil)
	result, err := Filter(query, series[0])
	c.Assert(err, IsNil)
	c.Assert(result, NotNil)
	c.Assert(result.Points, HasLen, 1)
	c.Assert(result.Fields, HasLen, 2)
}

func (self *FilteringSuite) TestEqualityFiltering(c *C) {
	queryStr := "select * from t where column_one = 100 and column_two <> 6;"
	query, err := parser.ParseSelectQuery(queryStr)
	c.Assert(err, IsNil)

	series, err := common.StringToSeriesArray(`
[
 {
   "points": [
     {"values": [{"int64_value": 100},{"int64_value": 5 }], "timestamp": 1381346631, "sequence_number": 1},
     {"values": [{"int64_value": 100},{"int64_value": 6 }], "timestamp": 1381346631, "sequence_number": 1},
     {"values": [{"int64_value": 90 },{"int64_value": 15}], "timestamp": 1381346632, "sequence_number": 1}
   ],
   "name": "t",
   "fields": ["column_one", "column_two"]
 }
]
`)
	c.Assert(err, IsNil)
	result, err := Filter(query, series[0])
	c.Assert(err, IsNil)
	c.Assert(result, NotNil)
	c.Assert(result.Points, HasLen, 1)
	c.Assert(*result.Points[0].Values[0].Int64Value, Equals, int64(100))
	c.Assert(*result.Points[0].Values[1].Int64Value, Equals, int64(5))
}

func (self *FilteringSuite) TestFilteringNonExistentColumn(c *C) {
	queryStr := "select * from t where column_one = 100 and column_two <> 6"
	query, err := parser.ParseSelectQuery(queryStr)
	c.Assert(err, IsNil)

	series, err := common.StringToSeriesArray(`
[
 {
   "points": [
     {"values": [{"int64_value": 100}], "timestamp": 1381346631, "sequence_number": 1},
     {"values": [{"int64_value": 90 }], "timestamp": 1381346632, "sequence_number": 1}
   ],
   "name": "t",
   "fields": ["column_one"]
 }
]
`)
	c.Assert(err, IsNil)
	_, err = Filter(query, series[0])
	c.Assert(err, NotNil)
}

func (self *FilteringSuite) TestFilteringWithJoin(c *C) {
	queryStr := "select * from t as bar inner join t as foo where bar.column_one = 100 and foo.column_two <> 6;"
	query, err := parser.ParseSelectQuery(queryStr)
	c.Assert(err, IsNil)
	series, err := common.StringToSeriesArray(`
[
 {
   "points": [
     {"values": [{"int64_value": 100},{"int64_value": 5 }], "timestamp": 1381346631, "sequence_number": 1},
     {"values": [{"int64_value": 100},{"int64_value": 6 }], "timestamp": 1381346631, "sequence_number": 1},
     {"values": [{"int64_value": 90 },{"int64_value": 15}], "timestamp": 1381346632, "sequence_number": 1}
   ],
   "name": "foo_join_bar",
   "fields": ["bar.column_one", "foo.column_two"]
 }
]
`)
	c.Assert(err, IsNil)
	result, err := Filter(query, series[0])
	c.Assert(err, IsNil)
	c.Assert(result, NotNil)
	// no filtering should happen for join queries
	c.Assert(result.Points, HasLen, 1)
}

func (self *FilteringSuite) TestReturnAllColumnsIfAskedForWildcard(c *C) {
	queryStr := "select * from t where column_one = 100 and column_two <> 6;"
	query, err := parser.ParseSelectQuery(queryStr)
	c.Assert(err, IsNil)
	series, err := common.StringToSeriesArray(`
[
 {
   "points": [
     {"values": [{"int64_value": 100},{"int64_value": 5 }], "timestamp": 1381346631, "sequence_number": 1},
     {"values": [{"int64_value": 100},{"int64_value": 6 }], "timestamp": 1381346631, "sequence_number": 1},
     {"values": [{"int64_value": 90 },{"int64_value": 15}], "timestamp": 1381346632, "sequence_number": 1}
   ],
   "name": "t",
   "fields": ["column_one", "column_two"]
 }
]
`)
	c.Assert(err, IsNil)
	result, err := Filter(query, series[0])
	c.Assert(err, IsNil)
	c.Assert(result, NotNil)
	c.Assert(result.Points, HasLen, 1)
	c.Assert(result.Fields, HasLen, 2)
	c.Assert(result.Points[0].Values, HasLen, 2)
}

func (self *FilteringSuite) TestReturnRequestedColumnsOnly(c *C) {
	queryStr := "select column_two from t where column_one = 100 and column_two <> 6;"
	query, err := parser.ParseSelectQuery(queryStr)
	c.Assert(err, IsNil)
	series, err := common.StringToSeriesArray(`
[
 {
   "points": [
     {"values": [{"int64_value": 100},{"int64_value": 5 }], "timestamp": 1381346631, "sequence_number": 1},
     {"values": [{"int64_value": 100},{"int64_value": 6 }], "timestamp": 1381346631, "sequence_number": 1},
     {"values": [{"int64_value": 90 },{"int64_value": 15}], "timestamp": 1381346632, "sequence_number": 1}
   ],
   "name": "t",
   "fields": ["column_one", "column_two"]
 }
]
`)
	c.Assert(err, IsNil)
	result, err := Filter(query, series[0])
	c.Assert(err, IsNil)
	c.Assert(result, NotNil)
	c.Assert(result.Points, HasLen, 1)
	c.Assert(result.Fields, HasLen, 1)
	c.Assert(result.Points[0].Values, HasLen, 1)
	c.Assert(*result.Points[0].Values[0].Int64Value, Equals, int64(5))
}

func (self *FilteringSuite) TestRegexFiltering(c *C) {
	queryStr := "select * from t where column_one =~ /.*foo.*/ and time > now() - 1d;"
	query, err := parser.ParseSelectQuery(queryStr)
	c.Assert(err, IsNil)
	series, err := common.StringToSeriesArray(`
[
 {
   "points": [
     {"values": [{"string_value": "100"}], "timestamp": 1381346631, "sequence_number": 1},
     {"values": [{"string_value": "foobar"}], "timestamp": 1381346631, "sequence_number": 1}
   ],
   "name": "t",
   "fields": ["column_one"]
 }
]
`)
	c.Assert(err, IsNil)
	result, err := Filter(query, series[0])
	c.Assert(err, IsNil)
	c.Assert(result, NotNil)
	c.Assert(result.Points, HasLen, 1)
	c.Assert(*result.Points[0].Values[0].StringValue, Equals, "foobar")
}

func (self *FilteringSuite) TestNotRegexFiltering(c *C) {
	queryStr := "select * from t where column_one !~ /.*foo.*/ and time > now() - 1d;"
	query, err := parser.ParseSelectQuery(queryStr)
	c.Assert(err, IsNil)
	series, err := common.StringToSeriesArray(`
[
 {
   "points": [
     {"values": [{"string_value": "100"}], "timestamp": 1381346631, "sequence_number": 1},
     {"values": [{"string_value": "foobar"}], "timestamp": 1381346631, "sequence_number": 1}
   ],
   "name": "t",
   "fields": ["column_one"]
 }
]
`)
	c.Assert(err, IsNil)
	result, err := Filter(query, series[0])
	c.Assert(err, IsNil)
	c.Assert(result, NotNil)
	c.Assert(result.Points, HasLen, 1)
	c.Assert(*result.Points[0].Values[0].StringValue, Equals, "100")
}

func (self *FilteringSuite) TestInequalityFiltering(c *C) {
	queryStr := "select * from t where column_one >= 100 and column_two > 6 and time > now() - 1d;"
	query, err := parser.ParseSelectQuery(queryStr)
	c.Assert(err, IsNil)
	series, err := common.StringToSeriesArray(`
[
 {
   "points": [
     {"values": [{"int64_value": 100},{"int64_value": 7 }], "timestamp": 1381346631, "sequence_number": 1},
     {"values": [{"int64_value": 100},{"int64_value": 6 }], "timestamp": 1381346631, "sequence_number": 1},
     {"values": [{"int64_value": 90 },{"int64_value": 15}], "timestamp": 1381346632, "sequence_number": 1}
   ],
   "name": "t",
   "fields": ["column_one", "column_two"]
 }
]
`)
	c.Assert(err, IsNil)
	result, err := Filter(query, series[0])
	c.Assert(err, IsNil)
	c.Assert(result, NotNil)
	c.Assert(result.Points, HasLen, 1)
	c.Assert(*result.Points[0].Values[0].Int64Value, Equals, int64(100))
	c.Assert(*result.Points[0].Values[1].Int64Value, Equals, int64(7))
}


text:
.opacity.csstransforms .modernizr-multi-supports {
  test: ok;
}

.opacity.csstransforms .modernizr-multi-supports .modernizr-multi-supports2 {
  test: ok;
}

.opacity.csstransforms .modernizr-multi-supports, .opacity.csstransforms .modernizr-multi-supports2 {
  test: ok;
}


text:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;

using Microsoft.Win32.SafeHandles;

using static Interop.Crypt32;

namespace Internal.Cryptography.Pal.Windows
{
    internal sealed partial class DecryptorPalWindows : DecryptorPal
    {
        public sealed override ContentInfo TryDecrypt(RecipientInfo recipientInfo, X509Certificate2 cert, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore, out Exception exception)
        {
            Debug.Assert(recipientInfo != null);
            Debug.Assert(cert != null);
            Debug.Assert(originatorCerts != null);
            Debug.Assert(extraStore != null);

            CryptKeySpec keySpec;
            exception = TryGetKeySpecForCertificate(cert, out keySpec);
            if (exception != null)
                return null;

            // Desktop compat: We pass false for "silent" here (thus allowing crypto providers to display UI.)
            using (SafeProvOrNCryptKeyHandle hKey = TryGetCertificatePrivateKey(cert, false, out exception))
            {
                if (hKey == null)
                    return null;

                RecipientInfoType type = recipientInfo.Type;
                switch (type)
                {
                    case RecipientInfoType.KeyTransport:
                        exception = TryDecryptTrans((KeyTransRecipientInfo)recipientInfo, hKey, keySpec);
                        break;

                    case RecipientInfoType.KeyAgreement:
                        exception = TryDecryptAgree((KeyAgreeRecipientInfo)recipientInfo, hKey, keySpec, originatorCerts, extraStore);
                        break;

                    default:
                        // Since only the framework can construct RecipientInfo's, we're at fault if we get here. So it's okay to assert and throw rather than
                        // returning to the caller.
                        Debug.Fail($"Unexpected RecipientInfoType: {type}");
                        throw new NotSupportedException();
                }

                if (exception != null)
                    return null;

                // If we got here, we successfully decrypted. Return the decrypted content.
                return _hCryptMsg.GetContentInfo();
            }
        }

        private static Exception TryGetKeySpecForCertificate(X509Certificate2 cert, out CryptKeySpec keySpec)
        {
            using (SafeCertContextHandle hCertContext = cert.CreateCertContextHandle())
            {
                int cbSize = 0;
                if (!Interop.Crypt32.CertGetCertificateContextProperty(hCertContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, null, ref cbSize))
                {
                    ErrorCode errorCode = (ErrorCode)(Marshal.GetLastWin32Error());
                    keySpec = default(CryptKeySpec);
                    return errorCode.ToCryptographicException();
                }

                byte[] pData = new byte[cbSize];
                unsafe
                {
                    fixed (byte* pvData = pData)
                    {
                        if (!Interop.Crypt32.CertGetCertificateContextProperty(hCertContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, pData, ref cbSize))
                        {
                            ErrorCode errorCode = (ErrorCode)(Marshal.GetLastWin32Error());
                            keySpec = default(CryptKeySpec);
                            return errorCode.ToCryptographicException();
                        }

                        CRYPT_KEY_PROV_INFO* pCryptKeyProvInfo = (CRYPT_KEY_PROV_INFO*)pvData;
                        keySpec = pCryptKeyProvInfo->dwKeySpec;
                        return null;
                    }
                }
            }
        }

        private static SafeProvOrNCryptKeyHandle TryGetCertificatePrivateKey(X509Certificate2 cert, bool silent, out Exception exception)
        {
            CryptAcquireCertificatePrivateKeyFlags flags =
                CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_USE_PROV_INFO_FLAG
                | CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_COMPARE_KEY_FLAG
                // Note: Using CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG rather than CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG because wrapping an NCrypt wrapper over CAPI keys unconditionally
                // causes some legacy features (such as RC4 support) to break.
                | CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG;
            if (silent)
            {
                flags |= CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_SILENT_FLAG;
            }

            bool mustFree;
            using (SafeCertContextHandle hCertContext = cert.CreateCertContextHandle())
            {
                IntPtr hKey;
                CryptKeySpec keySpec;
                if (!Interop.Crypt32.CryptAcquireCertificatePrivateKey(hCertContext, flags, IntPtr.Zero, out hKey, out keySpec, out mustFree))
                {
                    exception = Marshal.GetHRForLastWin32Error().ToCryptographicException();
                    return null;
                }

                // We need to know whether we got back a CRYPTPROV or NCrypt handle. Unfortunately, NCryptIsKeyHandle() is a prohibited api on UWP.
                // Fortunately, CryptAcquireCertificatePrivateKey() is documented to tell us which one we got through the keySpec value.
                bool isNCrypt;
                switch (keySpec)
                {
                    case CryptKeySpec.AT_KEYEXCHANGE:
                    case CryptKeySpec.AT_SIGNATURE:
                        isNCrypt = false;
                        break;

                    case CryptKeySpec.CERT_NCRYPT_KEY_SPEC:
                        isNCrypt = true;
                        break;

                    default:
                        // As of this writing, we've exhausted all the known values of keySpec. We have no idea what kind of key handle we got so
                        // play it safe and fail fast.
                        throw new NotSupportedException(SR.Format(SR.Cryptography_Cms_UnknownKeySpec, keySpec));
                }

                SafeProvOrNCryptKeyHandleUwp hProvOrNCryptKey = new SafeProvOrNCryptKeyHandleUwp(hKey, ownsHandle: mustFree, isNcrypt: isNCrypt);
                exception = null;
                return hProvOrNCryptKey;
            }
        }

        private Exception TryDecryptTrans(KeyTransRecipientInfo recipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec)
        {
            KeyTransRecipientInfoPalWindows pal = (KeyTransRecipientInfoPalWindows)(recipientInfo.Pal);

            CMSG_CTRL_DECRYPT_PARA decryptPara;
            decryptPara.cbSize = Marshal.SizeOf<CMSG_CTRL_DECRYPT_PARA>();
            decryptPara.hKey = hKey;
            decryptPara.dwKeySpec = keySpec;
            decryptPara.dwRecipientIndex = pal.Index;

            bool success = Interop.Crypt32.CryptMsgControl(_hCryptMsg, 0, MsgControlType.CMSG_CTRL_DECRYPT, ref decryptPara);
            if (!success)
                return Marshal.GetHRForLastWin32Error().ToCryptographicException();

            return null;
        }

        private Exception TryDecryptAgree(KeyAgreeRecipientInfo keyAgreeRecipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore)
        {
            unsafe
            {
                KeyAgreeRecipientInfoPalWindows pal = (KeyAgreeRecipientInfoPalWindows)(keyAgreeRecipientInfo.Pal);
                return pal.WithCmsgCmsRecipientInfo<Exception>(
                    delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* pKeyAgreeRecipientInfo)
                    {
                        CMSG_CTRL_KEY_AGREE_DECRYPT_PARA decryptPara = default(CMSG_CTRL_KEY_AGREE_DECRYPT_PARA);
                        decryptPara.cbSize = Marshal.SizeOf<CMSG_CTRL_KEY_AGREE_DECRYPT_PARA>();
                        decryptPara.hProv = hKey;
                        decryptPara.dwKeySpec = keySpec;
                        decryptPara.pKeyAgree = pKeyAgreeRecipientInfo;
                        decryptPara.dwRecipientIndex = pal.Index;
                        decryptPara.dwRecipientEncryptedKeyIndex = pal.SubIndex;
                        CMsgKeyAgreeOriginatorChoice originatorChoice = pKeyAgreeRecipientInfo->dwOriginatorChoice;
                        switch (originatorChoice)
                        {
                            case CMsgKeyAgreeOriginatorChoice.CMSG_KEY_AGREE_ORIGINATOR_CERT:
                                {
                                    X509Certificate2Collection candidateCerts = new X509Certificate2Collection();
                                    candidateCerts.AddRange(Helpers.GetStoreCertificates(StoreName.AddressBook, StoreLocation.CurrentUser, openExistingOnly: true));
                                    candidateCerts.AddRange(Helpers.GetStoreCertificates(StoreName.AddressBook, StoreLocation.LocalMachine, openExistingOnly: true));
                                    candidateCerts.AddRange(originatorCerts);
                                    candidateCerts.AddRange(extraStore);
                                    SubjectIdentifier originatorId = pKeyAgreeRecipientInfo->OriginatorCertId.ToSubjectIdentifier();
                                    X509Certificate2 originatorCert = candidateCerts.TryFindMatchingCertificate(originatorId);
                                    if (originatorCert == null)
                                        return ErrorCode.CRYPT_E_NOT_FOUND.ToCryptographicException();
                                    using (SafeCertContextHandle hCertContext = originatorCert.CreateCertContextHandle())
                                    {
                                        CERT_CONTEXT* pOriginatorCertContext = hCertContext.DangerousGetCertContext();
                                        decryptPara.OriginatorPublicKey = pOriginatorCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey;

                                        // Do not factor this call out of the switch statement as leaving this "using" block will free up
                                        // native memory that decryptPara points to.
                                        return TryExecuteDecryptAgree(ref decryptPara);
                                    }
                                }

                            case CMsgKeyAgreeOriginatorChoice.CMSG_KEY_AGREE_ORIGINATOR_PUBLIC_KEY:
                                {
                                    decryptPara.OriginatorPublicKey = pKeyAgreeRecipientInfo->OriginatorPublicKeyInfo.PublicKey;
                                    return TryExecuteDecryptAgree(ref decryptPara);
                                }

                            default:
                                return new CryptographicException(SR.Format(SR.Cryptography_Cms_Invalid_Originator_Identifier_Choice, originatorChoice));
                        }
                    });
            }
        }

        private Exception TryExecuteDecryptAgree(ref CMSG_CTRL_KEY_AGREE_DECRYPT_PARA decryptPara)
        {
            if (!Interop.Crypt32.CryptMsgControl(_hCryptMsg, 0, MsgControlType.CMSG_CTRL_KEY_AGREE_DECRYPT, ref decryptPara))
            {
                ErrorCode errorCode = (ErrorCode)(Marshal.GetHRForLastWin32Error());
                return errorCode.ToCryptographicException();
            }
            return null;
        }
    }
}


text:
package rapture.server.web.servlet.rest;

import java.util.ArrayList;
import java.util.List;

public class RestCollectionResponse {
    public String getPath() {
        return path;
    }
    public void setPath(String path) {
        this.path = path;
    }
    public List<RestFolder> getFolders() {
        return folders;
    }
    public void setFolders(List<RestFolder> folders) {
        this.folders = folders;
    }
    public List<RestFile> getFiles() {
        return files;
    }
    public void setFiles(List<RestFile> files) {
        this.files = files;
    }
    private String path;
    private List<RestFolder> folders = new ArrayList<RestFolder>();
    private List<RestFile> files = new ArrayList<RestFile>();
}


text:
import React from 'react';
import styles from './RepoCard.css';

import Card from '../shared/Card/Card';

export default class RepoCard extends React.Component {
    hightlight() {
        this.props.highlight(this.props.repo, this.props.color);
    }
    render() {
        let repo = this.props.repo;
        let homepageShortcut = repo.homepage ? repo.homepage.slice(repo.homepage.lastIndexOf('/') + 1) : undefined;
        return (
            <Card>

 this.hightlight()}
                    onMouseLeave={() => this.props.highlight(null)}
                    style={{ borderColor: this.props.color, borderTopWidth: 3, borderTopStyle: 'solid' }}>

                        {repo.owner.login}/
                        {repo.name}

                        {homepageShortcut}

                    <svg className={styles.RepoCard__Delete} viewBox="0 0 40 40" onClick={() => this.props.delete({ id: repo.id, name: repo.name, author: repo.owner.login })}>
                        <path className={styles.RepoCard__DeleteIcon} d="M 10,10 L 30,30 M 30,10 L 10,30" />
                    </svg>

            </Card>
        )
    }
}


text:
extern lzma_ret lzma_stream_decoder_init(
		lzma_next_coder *next, const lzma_allocator *allocator,
		uint64_t memlimit, uint32_t flags);

#endif


text:
package org.infinispan.api.batch;

import org.infinispan.Cache;
import org.infinispan.test.AbstractInfinispanTest;

import java.util.concurrent.atomic.AtomicReference;

public abstract class AbstractBatchTest extends AbstractInfinispanTest {
   protected String getOnDifferentThread(final Cache<String, String> cache, final String key) throws InterruptedException {
      final AtomicReference<String> ref = new AtomicReference<String>();
      Thread t = new Thread() {
         public void run() {
            cache.startBatch();
            ref.set(cache.get(key));
            cache.endBatch(true);
         }
      };

      t.start();
      t.join();
      return ref.get();
   }
}


text:
<?php

declare(strict_types=1);

namespace Vpn\Portal\Http\Exception;

use Exception;

class HttpException extends Exception
{
    private int $statusCode;

    /** @var array<string,string> */
    private array $responseHeaders;

    /**
     * @param array<string,string> $responseHeaders
     */
    public function __construct(string $message, int $statusCode, array $responseHeaders = [])
    {
        parent::__construct($message);
        $this->statusCode = $statusCode;
        $this->responseHeaders = $responseHeaders;
    }

    public function statusCode(): int
    {
        return $this->statusCode;
    }

    /**
     * @return array<string,string>
     */
    public function responseHeaders(): array
    {
        return $this->responseHeaders;
    }
}


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

namespace ClipSynth
{
    public class ClipSynthSoundtrack
    {
        public String Path;
        public bool Checked;
        public int Offset;
    }
}


text:
var http = require('q-io/http');

var config = require('../../config/config'),
    Assessment = require('./assessment.model'),
    HttpError = require('../error/HttpError'),
    ensureAuthenticated = require('../auth/auth.middleware').ensureAuthenticated;

module.exports = function (app) {

    app.route('/assessment')
        .get(ensureAuthenticated, function (request, response) {
            Assessment.find({creator: request.user._id})
                .execQ()
                .then(function sendResponse(assessments) {
                    response.status(200).json(assessments);
                })
                .catch(HttpError.handle(response));
        })
        .post(ensureAuthenticated, function (request, response) {
            console.log(request.user, request.body);
            var assess = new Assessment(request.body);
            assess.creator = request.user._id;
            assess
                .saveQ()
                .then(function sendResponse(assess) {
                    response.status(200).json(assess);
                })
                .catch(HttpError.handle(response));
        })
        .put(ensureAuthenticated, function (request, response) {
            var id = request.body._id;
            delete request.body._id;
            Assessment
                .findOneAndUpdateQ({_id: id}, request.body)
                .then(function sendResponse(assessment) {
                    if (!assessment) {
                        HttpError.throw(400, "The assessment you're looking at doesn't exist.");
                    }
                    var data = {
                        _id: assessment._id,
                        title: assessment.title
                    };
                    response.json(data);
                })
                .fail(HttpError.handle(response));
        });

    app.route('/assessment/:id')
        .get(ensureAuthenticated, function (request, response) {
            Assessment
                .findOne({_id: request.params.id})
                .populate('providedCompilationUnits compilationUnitsToSubmit tests guides')
                .execQ()
                .then(function sendResponse(assessment) {
                    if (!assessment) {
                        HttpError.throw(400, "The assessment you're looking at doesn't exist.");
                    }
                    response.status(200).json(assessment);
                }).catch(HttpError.handle(response));
        })
        .put(ensureAuthenticated, function (request, response) {
            delete request.body._id;
            Assessment
                .findOneAndUpdateQ({_id: request.params.id}, request.body)
                .then(function sendResponse(assessment) {
                    if (!assessment) {
                        HttpError.throw(400, "The assessment you're looking at doesn't exist.");
                    }
                    response.json(assessment);
                })
                .fail(HttpError.handle(response));
        })
        .delete(ensureAuthenticated, function (request, response) {
            Assessment
                .remove({_id: request.params.id}).execQ()
                .then(function sendResponse(nb) {
                    if (nb === 0) {
                        HttpError.throw(400, "The assessment you're looking at doesn't exist.");
                    }
                    response.status(200).json({
                        message: 'assessment successfully removed'
                    });
                })
                .fail(HttpError.handle(response));
        });

    //change the index of a guide in an assessment's array of guide
    app.route(ensureAuthenticated, '/assessment/:id/guide/move/:from/to/:to')
        .put(function (request, response) {
            Assessment
                .findOne({_id: request.params.id})
                .execQ()
                .then(function (assessment) {
                    return assessment.moveGuide(request.params.from, request.params.to);
                })
                .then(function () {
                    response.status(200).json({
                        message: 'success'
                    });
                })
                .catch(HttpError.handle(response));
        });

    app.post('/assessment/:id/submission', function (request, response) {
        Assessment
            .findOne({_id: request.params.id})
            .populate('compilationUnitsToSubmit')
            .populate('providedCompilationUnits')
            .populate('tests')
            .execQ()
            .then(function (assessment) {
                var submittedCompilationUnits = request.body.submittedCompilationUnits;
                var options = {
                    url: config.codeAssesserJavaUrl,
                    method: 'POST',
                    body: [
                        JSON.stringify({
                            assessment: assessment,
                            submittedCompilationUnits: submittedCompilationUnits
                        })
                    ]
                };
                return http.request(http.normalizeRequest(options))
                    .then(function (submissionResponse) {
                        return submissionResponse.body.read().then(function (body) {
                            response
                                .status(submissionResponse.status)
                                .json(JSON.parse(body));
                        });
                    });
            })
            .catch(HttpError.handle(response));
    });
};


text:
SERVER_NAME="phpmyadmin.`hostname -d`"
WWW_ROOT="/srv/www/${SERVER_NAME}"
REQUIRE_AUTH=True
USERNAME='phpmyadmin'
PASSWORD=`tr -cd "[:alnum:]" < /dev/urandom | head -c 10` # 10 char random password
SSL=False

## Constants
LOGFILE='install.log'

echo "### Beginning Install ###"

( # Start log capture

## Start
yum -y install php-mbstring php-mcrypt # install php modules that might be missing
mkdir -p ${WWW_ROOT}

# Configure Nginx vhost
cat > /etc/nginx/conf.d/${SERVER_NAME}-phpmyadmin.conf << EOF
    # phpMyAdmin Nginx Config for ${SERVER_NAME}

    server {
        listen  80;
        server_name_in_redirect off;
        server_name ${SERVER_NAME};
        root    ${WWW_ROOT};
        index   index.php index.html index.htm;
$(
if [ $SSL == True ]; then
cat << EOFA

        # SSL
        listen 443 default ssl;

        # SSL BEAST mitigation
        ssl_ciphers HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers on;

        ssl_certificate /etc/pki/tls/certs/${SERVER_NAME}.crt;
        ssl_certificate_key /etc/pki/tls/private/${SERVER_NAME}.key;

EOFA
fi
)

        if (\$server_port = 443) { set \$https on; }
        if (\$server_port = 80) { set \$https off; }

$(
if [ $REQUIRE_AUTH == True ]; then
cat << EOFA

        # Require Auth
        auth_basic            "Restricted";
        auth_basic_user_file  /etc/nginx/htpasswd;

EOFA
fi
)
        # Output compression
        gzip on;
        gzip_disable "msie6";
        gzip_http_version 1.0;
        gzip_vary on;
        gzip_comp_level 5;
        gzip_proxied any;
        gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
        gzip_buffers 16 8k;

        # Max file upload
        client_max_body_size 32M;

        location / {
            # if the requested file exists, return it immediately
            if (-f \$request_filename) {
                break;
            }
        }

        # Pass PHP scripts on to PHP-FASTCGI
        location ~ \.php$ {
            include /etc/nginx/fastcgi_params;
            fastcgi_pass  127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
            fastcgi_read_timeout 300; # increase timeout incase our mysql is on different servers
            fastcgi_param HTTPS \$https;
        }

        # Don't serve .htaccess, .svn or .git
        location ~ \.(htaccess|svn|git) {
            deny  all;
        }
    }
EOF

# Install phpMyAdmin
wget -q http://sourceforge.net/projects/phpmyadmin/files/latest/download -O /tmp/phpmyadmin-latest.tar.bz2 && \
tar -xjf /tmp/phpmyadmin-latest.tar.bz2 -C ${WWW_ROOT} && rm -f /tmp/phpmyadmin-latest.tar.bz2

if [ $REQUIRE_AUTH == True ]; then
    htpasswd -b -c /etc/nginx/htpasswd ${USERNAME} ${PASSWORD}
    echo "Username / Password is ${USERNAME} / $PASSWORD" 1>&2
fi

# Start / Restart
service spawn-fcgi restart
service nginx restart

) 2>&1 1>> ${LOGFILE} | tee -a ${LOGFILE} # stderr to console, stdout&stderr to logfile

echo "### Install Complete ###"


text:
<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\Debug\Debug;

umask(0000);

$loader = require __DIR__.'/../app/autoload.php';
Debug::enable();

// $loader = new ApcClassLoader('evercode', $loader);
// $loader->register(true);

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();

$request = Request::createFromGlobals();
$response = $kernel->handle($request);

$response->send();
$kernel->terminate($request, $response);


text:
namespace SimpleMvc.Framework.Contracts
{
    public interface IRenderable
    {
        string Render();
    }
}


text:
import pprint

class Result:
    pass
class Success(Result):
    def __init__(self, value, tail):
        self.value = value
        self.tail = tail
    def copy(self):
        return Success(self.value, self.tail)
    def __str__(self):
        return "Success: %s, '%s'" % (self.value, self.tail)
    __repr__ = __str__

class Failure(Result):
    def __init__(self, msg):
        self.msg = msg
    def copy(self):
        return Failure(self.msg)
    def __str__(self):
        return 'Failure: ' + self.msg
    __repr__ = __str__

class Trampoline:
    def __init__(self):
        self.stack = []
        self.remove = self.stack.pop
        # A map of a stream position to a map mapping parser instances
        # to sets of continuations.
        self.backlinks = {}
        # A map of a stream position to sets of parsers.
        self.done = {}
        # A map of a stream position to a map mapping parser instances
        # to sets of successes.
        self.popped = {}
        # A map of Results to sets of functions.
        self.saved = {}

    def __str__(self):
        return '\n'.join(['Trampoline', 'Stack', pprint.pformat(self.stack), 'Backlinks', pprint.pformat(self.backlinks), 'Done', pprint.pformat(self.done), 'Popped', pprint.pformat(self.popped), 'Saved', pprint.pformat(self.saved)])

    def run(self):
        while self.stack:
            # print(self)
            # print([type(r) for s in self.popped for p in self.popped[s] for r in self.popped[s][p]])
            parser, stream = self.remove()
            def trampoline_continuation(res, stream=stream, parser=parser):
                # print('Trampoline:', res)
                if stream not in self.popped:
                    self.popped[stream] = {}
                if parser not in self.popped[stream]:
                    self.popped[stream][parser] = set()
                if isinstance(res, Success):
                    self.popped[stream][parser].add(res)
                    # print('Trampoline success: ', res, pprint.pformat(self.backlinks), pprint.pformat(self.saved), sep='\n')
                # else:
                #     return None
                if res not in self.saved:
                    self.saved[res] = set()
                for f in self.backlinks[stream][parser]:
                    if f not in self.saved[res]:
                        self.saved[res].add(f)
                        f(res)
            # print(inspect.getclosurevars(trampoline_continuation))
            parser.chain(self, stream, trampoline_continuation)

    def add(self, p, stream, f):
        if stream not in self.backlinks:
            self.backlinks[stream] = {}
        if p not in self.backlinks[stream]:
            self.backlinks[stream][p] = set()
        if f not in self.backlinks[stream][p]:
            self.backlinks[stream][p].add(f)
        if stream in self.popped and p in self.popped[stream]:
            for res in self.popped[stream][p].copy():
                f(res)
        else:
            if stream not in self.done:
                self.done[stream] = set()
            if p not in self.done[stream]:
                self.stack.append((p, stream))
                self.done[stream].add(p)

# The concept of terminal and nonterminal parsers is closely related
# to the concept of static and dynamic parsers I've discussed in my
# prototype.

# I follow Spiewak in using t for Trampoline class variables and f for
# continuations.  apply is a method that takes a stream and returns a
# Result, as in recursive-descent parser combinators.  While working
# out the basic parser combinators I used __call__ instead of apply
# because apply was a built-in function in Python 2 (deprecated since
# 2.3), but with two central methods I decided to follow Spiewak's
# convention.  The other method is chain.  Scala allows you to declare
# functions with multiple lists of parameters, like:

# def chain(t: Trampoline, in: Stream[Char])(f: Result[A] => Unit)

# If you call a Scala function with fewer than the full number of
# parameters, Scala will automatically return a function that takes
# the remaining parameters (currying).  Chain takes a Trampoline, a
# stream, and a function/continuation taking a Result and returning
# the Unit algebraic type and returns the Unit algebraic type (this is
# equivalent to None in Python or void in Java), or, it takes a
# Trampoline and a stream and returns a function/continuation that
# takes a function taking a Result and returning the Unit algebraic
# type.  The only ways to simulate this currying in Python are with
# functools.partial and closures, though neither are quite the same
# thing.

# I need to close over the continuations that Spiewak implements as
# anonymous pattern-matching methods using currying.  The syntax for
# this in Scala is an example of how bizarre Scala is: you can call a
# function using parentheses as normal, but there's also a special
# notation called infix notation that allows eliding of parentheses
# when calling higher-order functions.  (This is a *convention* not a
# hard rule, which makes it possible to write even more confusing
# code, but the general complications of infix notation are beyond
# this short note.)  In the Scala code, the partial version of chain
# returns a function that then acts on an anonymous pattern-matching
# function.

# I've figured out a couple of different approaches, all bad.

# Use lambdas as anonymous functions as in Scala.  The main trick with
# this is that I have to use ternary if-else or nested and-or (see
# https://www.inkling.com/read/learning-python-mark-lutz-4th/chapter-19/anonymous-functions-lambda)
# to handle the selection logic, one of,

# b if a else c

# ((a and b) or c)

# instead of,

# if a:
#     b
# else:
#     c

# Use nested named closures with conditional logic in chain.  The
# amount of function creation and calls will make this very slow,
# though probably not much slower than the lambda method.

# Use named single-dispatch methods and pass in the continuation
# received by chain.  This avoids some of the horrible slowness by
# setting up the single-dispatch logic in __init__, but requires
# changing the signature of the continuations from what it is in
# Scala.

# Use nested named single-dispatch closures in chain.  The main
# problem with this is the amount of logic that has to be stuffed into
# the chain method: the continuations have to be created, registered
# as single-dispatch functions, closed, and then passed along.  This
# is horribly slow and completely unsuitable for the real
# implementation.

# For the real implementation, it's not clear to me which of
# single-dispatch methods, simple conditionals (like I used for the
# basic combinators), or dictionaries are the fatest way to branch
# based on whether a function receives Success or Failure, where
# pattern matching is used in Scala.  This will require profiling.

# There's an important difference between how Python handles closures
# and Scala (apparently) handles its anonymous methods: each time a
# function/method creating a closure is called, it creates a new
# function object that is not considered equal to previous instances
# of that closure, while in Scala, testing for equality/containment on
# the anonymous methods works correctly.  The way I found to
# circumvent this is that each closure object contains a .__code__
# attribute that is unique across all instances, so I always have to
# do equality/containment testing on that.  This would not be fast
# enough for a real implementation.

# The other problem with Python's closures in this particular design
# is that they're late-binding, which means that for instance if the
# same chain method is called with one closure and then called with
# another before the first closure is executed, the first closure will
# never be executed.  While the easiest way to fix this is to use
# default arguments, this is a hack.  Instead, I use a function
# factory where necessary.

# Important note from Spiewak: "The point is that apply can be relied
# upon to perform initialization operations for a specific parse.
# Since GLL initialization is the same for any non-terminal parser,
# these operations can be implemented safely in the superclass." (14)

class Parser:
    def apply(self, stream):
        # returns a list of Results
        raise NotImplementedError
    def chain(self, t, stream, f):
        # returns None
        raise NotImplementedError
    # No binary ~ operator in Python so I overloaded + instead
    def __add__(self, other):
        raise NotImplementedError
    def __radd__(self, other):
        raise NotImplementedError
    def __or__(self, other):
        return DisjunctiveParser(self, other)
    def __ror__(self, other):
        return DisjunctiveParser(other, self)
    # No ^^ operator in Python so I overloaded ^ instead
    # def __xor__(self, f):
    #     return Parser(self, f)

class NonTerminalParser(Parser):
    def apply(self, stream):
        t = Trampoline()
        successes = set()
        failures = set()
        def nonterminal_continuation(res):
            if isinstance(res, Success):
                # Disabled for now.
                # if res.tail:
                #     failures.add(Failure('Unexpected trailing characters: "{}"'.format(str(res.tail))))
                # else:
                successes.add(res)
            else:
                failures.add(res)
        self.chain(t, stream, nonterminal_continuation)
        t.run()
        if successes:
            return list(successes)
        else:
            return list(failures)

    def __add__(self, other):
        return NonTerminalSequentialParser(self, other)
    def __radd__(self, other):
        return NonTerminalSequentialParser(other, self)

# Non-terminal version
class NonTerminalSequentialParser(NonTerminalParser):
    def __init__(self, left, right):
        self.left = left
        self.right = right

    def chain(self, t, stream, f):
        def continuation1(res1):
            if isinstance(res1, Success):
                def continuation2(res2):
                    if isinstance(res2, Success):
                        # print('Sequence:', res1, res2)
                        return f(Success((res1.value, res2.value), res2.tail))
                    else:
                        return f(res2)
                return self.right.chain(t, res1.tail, continuation2)
            else:
                return f(res1)
        self.left.chain(t, stream, continuation1)

class DisjunctiveParser(NonTerminalParser):
    def __init__(self, left, right):
        self.left = left
        self.right = right
        # Walk the parser tree to gather alternates
        def gather(seen):
            seen.add(self)
            def process(p):
                nonlocal seen
                if isinstance(p, DisjunctiveParser):
                    if p not in seen:
                        seen |= set(p.alternates)
                        return seen
                    else:
                        return set()
                else:
                    seen.add(p)
                    return seen
            return process(self.left) | process(self.right)
        self.alternates = list(gather(set()))

    def chain(self, t, stream, f):
        results = set()
        def disjunctive_continuation(res):
            # print('Disjunction:', res)
            if res not in results:
                f(res)
                results.add(res)
        for p in self.alternates:
            t.add(p, stream, disjunctive_continuation)

class TerminalParser(Parser):
    def chain(self, t, stream, f):
        f(self.apply(stream))

    def __add__(self, other):
        if isinstance(other, TerminalParser):
            return TerminalSequentialParser(self, other)
        else:
            return NonTerminalSequentialParser(self, other)
    def __radd__(self, other):
        # I can't use the lazy evaluation trick I used in the basic
        # combinators here because I don't know what kind of parser
        # the other parser will be at instantiation time.
        if isinstance(other, TerminalParser):
            return TerminalSequentialParser(other, self)
        else:
            return NonTerminalSequentialParser(other, self)

class TerminalSequentialParser(TerminalParser):
    def __init__(self, left, right):
        self.left = left
        self.right = right

    # Spiewak defines this method inside the method for the overloaded
    # sequence operator in TerminalParser in Scala, but there's no
    # easy way to bind methods to instances in Python so I defined it
    # this way instead.  There may be a more elegant way to do this.
    # @tracecalls.TraceCalls(show_ret=True)
    def apply(self, stream):
        # logging.debug(apply_log.format(type(self).__name__, stream))
        result1 = self.left.apply(stream)
        if isinstance(result1, Success):
            result2 = self.right.apply(result1.tail)
            if isinstance(result2, Success):
                return Success((result1.value, result2.value), result2.tail)
            else:
                return result2.copy()
        else:
            return result1.copy()

class LiteralParser(TerminalParser):
    def __init__(self, value):
        self.value = value

    def apply(self, stream):
        length = len(self.value)
        if (length > len(stream)):
            return Failure('Unexpected end of stream (expected "{}")'.format(self.value))
        else:
            # Spiewak uses a different approach here but this will be
            # faster in Python
            if stream.startswith(self.value):
                return Success(self.value, stream[length:])
            else:
                return Failure('Expected "{}" got "{}"'.format(self.value, stream[:length]))

if __name__ == '__main__':
    # The implementation in Spiewak's paper doesn't seem to be
    # complete because the only parser that will ever return
    # "Unexpected trailing characters" is a non-terminal parser.
    import cProfile
    import platform
    import six
    import sys
    import time
    import timeit

    CPYTHON = True if platform.python_implementation() == 'CPython' else False
    if six.PY3 and CPYTHON:
        import tracemalloc
        tracemalloc.start()

    def tracefunc(frame, event, arg, indent=[0]):
        if event == "call":
            if frame.f_code.co_filename == 'gll_spiewak_combinators.py':
                indent[0] += 2
                name = frame.f_code.co_name
                print("-" * indent[0] + "> call", frame.f_code.co_filename, name)
                if not (name == '__str__' or name == '__init__' or name == '<lambda>'):
                    pprint.pprint(frame.f_locals)
        elif event == "return":
            if frame.f_code.co_filename == 'continuation_gll_combinators.py':
                print("<" + "-" * indent[0], "exit", frame.f_code.co_name)
                indent[0] -= 2
        return tracefunc

    # The implementation in Spiewak's paper doesn't seem to be
    # complete because the only parser that will ever return
    # "Unexpected trailing characters" is a non-terminal parser.
    strings = LiteralParser('ab')
    print('Literal success,', strings.apply('ababab'))
    print('Literal failure,', strings.apply('bcbcbc'))
    terminal = LiteralParser('a') + LiteralParser('b')
    print('Terminal success,', terminal.apply('ababab'))
    terminal = TerminalSequentialParser(LiteralParser('a'), LiteralParser('b'))
    print('Terminal success,', terminal.apply('ababab'))

    alternation = LiteralParser('ab') | LiteralParser('bc')
    print('Disjunction success,', alternation.apply('bcbcbc'))
    alternation = DisjunctiveParser(LiteralParser('ab'), LiteralParser('bc'))
    print('Disjunction success,', alternation.apply('bcbcbc'))

    sequence = LiteralParser('a') + (LiteralParser('b') | LiteralParser('c'))
    print('Sequence alternation success,', sequence.apply('abc'))
    print('Sequence alternation success,', sequence.apply('acb'))
    print('Sequence alternation failure,', sequence.apply('cba'))
    sequence = NonTerminalSequentialParser(LiteralParser('a'), DisjunctiveParser(LiteralParser('b'), LiteralParser('c')))
    print('Sequence alternation success,', sequence.apply('abc'))
    print('Sequence alternation success,', sequence.apply('acb'))
    print('Sequence alternation failure,', sequence.apply('cba'))

    # sys.settrace(tracefunc)

    # Ugly hack to work around the lack of forward reference support
    # in this prototype
    ambiguous = DisjunctiveParser(0, 0)
    ambiguous.alternates = [ambiguous + ambiguous + ambiguous, ambiguous + ambiguous, LiteralParser('a')]
    print('Highly ambiguous,', ambiguous.apply('aaa'))

    print('Highly ambiguous')
    def time_ambiguous(max_length):
        for i in range(2, max_length):
            print(i, timeit.timeit('ambiguous.apply("' + i * 'a' + '")', 'gc.enable(); from __main__ import ambiguous', number=1000), 'seconds')

    cProfile.run('''
time_ambiguous(9)
''')

    # alpha = Regex('([a-zA-Z])')
    # hex_char = Regex('([a-fA-F0-9])')

    # alpha_or_hex = alpha | hex_char
    # print('Alpha success,', alpha_or_hex.apply('xyz'))
    # print('Alpha and hex success,', alpha_or_hex.apply('ABC'))
    # print('Hex success,', alpha_or_hex.apply('123'))

    # a = LiteralParser('a')
    # l = Lazy('a')
    # print('Lazy,', l.apply('a'))
    # print('Lazy,', l.apply('a'))

    # word = Regex('([a-zA-Z]+)')
    # sentence = ((word + LiteralParser('.')) >> (lambda t: t[0])) | ((word + Regex(r'[\s,]') + Lazy('sentence')) >> (lambda t: t[0][0] + t[1]))
    # print('Sentence success,', sentence.apply('The quick brown fox jumps over the lazy dog.'))

#     dictionary = [w.strip().replace("'", '') for w in open('/usr/share/dict/words', 'r').read().splitlines() if w.strip().isalpha()]
#     sample = ' '.join(dictionary[:10000]) + '.'

#     start = time.clock()
#     sentence.apply(sample)
#     end = time.clock()
#     print('Dictionary, %.4f seconds' % (end - start,))

    if six.PY3 and CPYTHON:
        snapshot = tracemalloc.take_snapshot()
        top_stats = snapshot.statistics('lineno')

        print("[ Top 10 ]")
        for stat in top_stats[:10]:
            print(stat)


text:
package prometheus

import (
	"github.com/prometheus/procfs"
)

func canCollectProcess() bool {
	_, err := procfs.NewDefaultFS()
	return err == nil
}

func (c *processCollector) processCollect(ch chan<- Metric) {
	pid, err := c.pidFn()
	if err != nil {
		c.reportError(ch, nil, err)
		return
	}

	p, err := procfs.NewProc(pid)
	if err != nil {
		c.reportError(ch, nil, err)
		return
	}

	if stat, err := p.Stat(); err == nil {
		ch <- MustNewConstMetric(c.cpuTotal, CounterValue, stat.CPUTime())
		ch <- MustNewConstMetric(c.vsize, GaugeValue, float64(stat.VirtualMemory()))
		ch <- MustNewConstMetric(c.rss, GaugeValue, float64(stat.ResidentMemory()))
		if startTime, err := stat.StartTime(); err == nil {
			ch <- MustNewConstMetric(c.startTime, GaugeValue, startTime)
		} else {
			c.reportError(ch, c.startTime, err)
		}
	} else {
		c.reportError(ch, nil, err)
	}

	if fds, err := p.FileDescriptorsLen(); err == nil {
		ch <- MustNewConstMetric(c.openFDs, GaugeValue, float64(fds))
	} else {
		c.reportError(ch, c.openFDs, err)
	}

	if limits, err := p.Limits(); err == nil {
		ch <- MustNewConstMetric(c.maxFDs, GaugeValue, float64(limits.OpenFiles))
		ch <- MustNewConstMetric(c.maxVsize, GaugeValue, float64(limits.AddressSpace))
	} else {
		c.reportError(ch, nil, err)
	}
}


text:
export default function assert(expr, msg, errorType = Error) {
  if (!expr) {
    throw new errorType(msg);
  }
}

export function assertInstance(value, type, msg) {
  const expr = value instanceof type;
  assert(expr, msg, TypeError);
}


text:
package nsqd

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"runtime"
	"strconv"
	"sync"
	"testing"
	"time"

	"strings"

	"github.com/nsqio/go-nsq"
	"github.com/nsqio/nsq/internal/test"
	"github.com/nsqio/nsq/internal/version"
	"github.com/nsqio/nsq/nsqlookupd"
)

type ErrMessage struct {
	Message string `json:"message"`
}

type InfoDoc struct {
	Version          string `json:"version"`
	BroadcastAddress string `json:"broadcast_address"`
	Hostname         string `json:"hostname"`
	HTTPPort         int    `json:"http_port"`
	TCPPort          int    `json:"tcp_port"`
	StartTime        int64  `json:"start_time"`
}

func TestHTTPpub(t *testing.T) {
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	topicName := "test_http_pub" + strconv.Itoa(int(time.Now().Unix()))
	topic := nsqd.GetTopic(topicName)

	buf := bytes.NewBuffer([]byte("test message"))
	url := fmt.Sprintf("http://%s/pub?topic=%s", httpAddr, topicName)
	resp, err := http.Post(url, "application/octet-stream", buf)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	test.Equal(t, "OK", string(body))

	time.Sleep(5 * time.Millisecond)

	test.Equal(t, int64(1), topic.Depth())
}

func TestHTTPpubEmpty(t *testing.T) {
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	topicName := "test_http_pub_empty" + strconv.Itoa(int(time.Now().Unix()))
	topic := nsqd.GetTopic(topicName)

	buf := bytes.NewBuffer([]byte(""))
	url := fmt.Sprintf("http://%s/pub?topic=%s", httpAddr, topicName)
	resp, err := http.Post(url, "application/octet-stream", buf)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	test.Equal(t, 400, resp.StatusCode)
	test.Equal(t, `{"message":"MSG_EMPTY"}`, string(body))

	time.Sleep(5 * time.Millisecond)

	test.Equal(t, int64(0), topic.Depth())
}

func TestHTTPmpub(t *testing.T) {
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	topicName := "test_http_mpub" + strconv.Itoa(int(time.Now().Unix()))
	topic := nsqd.GetTopic(topicName)

	msg := []byte("test message")
	msgs := make([][]byte, 4)
	for i := range msgs {
		msgs[i] = msg
	}
	buf := bytes.NewBuffer(bytes.Join(msgs, []byte("\n")))

	url := fmt.Sprintf("http://%s/mpub?topic=%s", httpAddr, topicName)
	resp, err := http.Post(url, "application/octet-stream", buf)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	test.Equal(t, "OK", string(body))

	time.Sleep(5 * time.Millisecond)

	test.Equal(t, int64(4), topic.Depth())
}

func TestHTTPmpubEmpty(t *testing.T) {
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	topicName := "test_http_mpub_empty" + strconv.Itoa(int(time.Now().Unix()))
	topic := nsqd.GetTopic(topicName)

	msg := []byte("test message")
	msgs := make([][]byte, 4)
	for i := range msgs {
		msgs[i] = msg
	}
	buf := bytes.NewBuffer(bytes.Join(msgs, []byte("\n")))
	_, err := buf.Write([]byte("\n"))
	test.Nil(t, err)

	url := fmt.Sprintf("http://%s/mpub?topic=%s", httpAddr, topicName)
	resp, err := http.Post(url, "application/octet-stream", buf)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	test.Equal(t, "OK", string(body))

	time.Sleep(5 * time.Millisecond)

	test.Equal(t, int64(4), topic.Depth())
}

func TestHTTPmpubBinary(t *testing.T) {
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	topicName := "test_http_mpub_bin" + strconv.Itoa(int(time.Now().Unix()))
	topic := nsqd.GetTopic(topicName)

	mpub := make([][]byte, 5)
	for i := range mpub {
		mpub[i] = make([]byte, 100)
	}
	cmd, _ := nsq.MultiPublish(topicName, mpub)
	buf := bytes.NewBuffer(cmd.Body)

	url := fmt.Sprintf("http://%s/mpub?topic=%s&binary=true", httpAddr, topicName)
	resp, err := http.Post(url, "application/octet-stream", buf)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	test.Equal(t, "OK", string(body))

	time.Sleep(5 * time.Millisecond)

	test.Equal(t, int64(5), topic.Depth())
}

func TestHTTPmpubForNonNormalizedBinaryParam(t *testing.T) {
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	topicName := "test_http_mpub_bin" + strconv.Itoa(int(time.Now().Unix()))
	topic := nsqd.GetTopic(topicName)

	mpub := make([][]byte, 5)
	for i := range mpub {
		mpub[i] = make([]byte, 100)
	}
	cmd, _ := nsq.MultiPublish(topicName, mpub)
	buf := bytes.NewBuffer(cmd.Body)

	url := fmt.Sprintf("http://%s/mpub?topic=%s&binary=non_normalized_binary_param", httpAddr, topicName)
	resp, err := http.Post(url, "application/octet-stream", buf)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	test.Equal(t, "OK", string(body))

	time.Sleep(5 * time.Millisecond)

	test.Equal(t, int64(5), topic.Depth())
}

func TestHTTPpubDefer(t *testing.T) {
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	topicName := "test_http_pub_defer" + strconv.Itoa(int(time.Now().Unix()))
	topic := nsqd.GetTopic(topicName)
	ch := topic.GetChannel("ch")

	buf := bytes.NewBuffer([]byte("test message"))
	url := fmt.Sprintf("http://%s/pub?topic=%s&defer=%d", httpAddr, topicName, 1000)
	resp, err := http.Post(url, "application/octet-stream", buf)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	test.Equal(t, "OK", string(body))

	time.Sleep(5 * time.Millisecond)

	ch.deferredMutex.Lock()
	numDef := len(ch.deferredMessages)
	ch.deferredMutex.Unlock()
	test.Equal(t, 1, numDef)
}

func TestHTTPSRequire(t *testing.T) {
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	opts.LogLevel = "debug"
	opts.TLSCert = "./test/certs/server.pem"
	opts.TLSKey = "./test/certs/server.key"
	opts.TLSClientAuthPolicy = "require"
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	topicName := "test_http_pub_req" + strconv.Itoa(int(time.Now().Unix()))
	topic := nsqd.GetTopic(topicName)

	buf := bytes.NewBuffer([]byte("test message"))
	url := fmt.Sprintf("http://%s/pub?topic=%s", httpAddr, topicName)
	resp, err := http.Post(url, "application/octet-stream", buf)
	test.Equal(t, 403, resp.StatusCode)

	httpsAddr := nsqd.httpsListener.Addr().(*net.TCPAddr)
	cert, err := tls.LoadX509KeyPair("./test/certs/cert.pem", "./test/certs/key.pem")
	test.Nil(t, err)
	tlsConfig := &tls.Config{
		Certificates:       []tls.Certificate{cert},
		InsecureSkipVerify: true,
		MinVersion:         0,
	}
	transport := &http.Transport{
		TLSClientConfig: tlsConfig,
	}
	client := &http.Client{Transport: transport}

	buf = bytes.NewBuffer([]byte("test message"))
	url = fmt.Sprintf("https://%s/pub?topic=%s", httpsAddr, topicName)
	resp, err = client.Post(url, "application/octet-stream", buf)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	test.Equal(t, "OK", string(body))

	time.Sleep(5 * time.Millisecond)

	test.Equal(t, int64(1), topic.Depth())
}

func TestHTTPSRequireVerify(t *testing.T) {
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	opts.LogLevel = "debug"
	opts.TLSCert = "./test/certs/server.pem"
	opts.TLSKey = "./test/certs/server.key"
	opts.TLSRootCAFile = "./test/certs/ca.pem"
	opts.TLSClientAuthPolicy = "require-verify"
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	httpsAddr := nsqd.httpsListener.Addr().(*net.TCPAddr)
	topicName := "test_http_pub_req_verf" + strconv.Itoa(int(time.Now().Unix()))
	topic := nsqd.GetTopic(topicName)

	// no cert
	buf := bytes.NewBuffer([]byte("test message"))
	url := fmt.Sprintf("http://%s/pub?topic=%s", httpAddr, topicName)
	resp, err := http.Post(url, "application/octet-stream", buf)
	test.Equal(t, 403, resp.StatusCode)

	// unsigned cert
	cert, err := tls.LoadX509KeyPair("./test/certs/cert.pem", "./test/certs/key.pem")
	test.Nil(t, err)
	tlsConfig := &tls.Config{
		Certificates:       []tls.Certificate{cert},
		InsecureSkipVerify: true,
	}
	transport := &http.Transport{
		TLSClientConfig: tlsConfig,
	}
	client := &http.Client{Transport: transport}

	buf = bytes.NewBuffer([]byte("test message"))
	url = fmt.Sprintf("https://%s/pub?topic=%s", httpsAddr, topicName)
	resp, err = client.Post(url, "application/octet-stream", buf)
	test.NotNil(t, err)

	// signed cert
	cert, err = tls.LoadX509KeyPair("./test/certs/client.pem", "./test/certs/client.key")
	test.Nil(t, err)
	tlsConfig = &tls.Config{
		Certificates:       []tls.Certificate{cert},
		InsecureSkipVerify: true,
	}
	transport = &http.Transport{
		TLSClientConfig: tlsConfig,
	}
	client = &http.Client{Transport: transport}

	buf = bytes.NewBuffer([]byte("test message"))
	url = fmt.Sprintf("https://%s/pub?topic=%s", httpsAddr, topicName)
	resp, err = client.Post(url, "application/octet-stream", buf)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	test.Equal(t, "OK", string(body))

	time.Sleep(5 * time.Millisecond)

	test.Equal(t, int64(1), topic.Depth())
}

func TestTLSRequireVerifyExceptHTTP(t *testing.T) {
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	opts.LogLevel = "debug"
	opts.TLSCert = "./test/certs/server.pem"
	opts.TLSKey = "./test/certs/server.key"
	opts.TLSRootCAFile = "./test/certs/ca.pem"
	opts.TLSClientAuthPolicy = "require-verify"
	opts.TLSRequired = TLSRequiredExceptHTTP
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	topicName := "test_http_req_verf_except_http" + strconv.Itoa(int(time.Now().Unix()))
	topic := nsqd.GetTopic(topicName)

	// no cert
	buf := bytes.NewBuffer([]byte("test message"))
	url := fmt.Sprintf("http://%s/pub?topic=%s", httpAddr, topicName)
	resp, err := http.Post(url, "application/octet-stream", buf)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	test.Equal(t, "OK", string(body))

	time.Sleep(5 * time.Millisecond)

	test.Equal(t, int64(1), topic.Depth())
}

func TestHTTPV1TopicChannel(t *testing.T) {
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	topicName := "test_http_topic_channel2" + strconv.Itoa(int(time.Now().Unix()))
	channelName := "ch2"

	url := fmt.Sprintf("http://%s/topic/create?topic=%s", httpAddr, topicName)
	resp, err := http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 200, resp.StatusCode)
	body, _ := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	test.Equal(t, "", string(body))
	test.Equal(t, "nsq; version=1.0", resp.Header.Get("X-NSQ-Content-Type"))

	url = fmt.Sprintf("http://%s/channel/create?topic=%s&channel=%s", httpAddr, topicName, channelName)
	resp, err = http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 200, resp.StatusCode)
	body, _ = ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	test.Equal(t, "", string(body))
	test.Equal(t, "nsq; version=1.0", resp.Header.Get("X-NSQ-Content-Type"))

	topic, err := nsqd.GetExistingTopic(topicName)
	test.Nil(t, err)
	test.NotNil(t, topic)

	channel, err := topic.GetExistingChannel(channelName)
	test.Nil(t, err)
	test.NotNil(t, channel)

	em := ErrMessage{}

	url = fmt.Sprintf("http://%s/topic/pause", httpAddr)
	resp, err = http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 400, resp.StatusCode)
	test.Equal(t, "Bad Request", http.StatusText(resp.StatusCode))
	body, _ = ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	t.Logf("%s", body)
	err = json.Unmarshal(body, &em)
	test.Nil(t, err)
	test.Equal(t, "MISSING_ARG_TOPIC", em.Message)

	url = fmt.Sprintf("http://%s/topic/pause?topic=%s", httpAddr, topicName+"abc")
	resp, err = http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 404, resp.StatusCode)
	test.Equal(t, "Not Found", http.StatusText(resp.StatusCode))
	body, _ = ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	t.Logf("%s", body)
	err = json.Unmarshal(body, &em)
	test.Nil(t, err)
	test.Equal(t, "TOPIC_NOT_FOUND", em.Message)

	url = fmt.Sprintf("http://%s/topic/pause?topic=%s", httpAddr, topicName)
	resp, err = http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 200, resp.StatusCode)
	body, _ = ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	test.Equal(t, "", string(body))
	test.Equal(t, "nsq; version=1.0", resp.Header.Get("X-NSQ-Content-Type"))

	test.Equal(t, true, topic.IsPaused())

	url = fmt.Sprintf("http://%s/topic/unpause?topic=%s", httpAddr, topicName)
	resp, err = http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 200, resp.StatusCode)
	body, _ = ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	test.Equal(t, "", string(body))
	test.Equal(t, "nsq; version=1.0", resp.Header.Get("X-NSQ-Content-Type"))

	test.Equal(t, false, topic.IsPaused())

	url = fmt.Sprintf("http://%s/channel/pause?topic=%s&channel=%s", httpAddr, topicName, channelName)
	resp, err = http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 200, resp.StatusCode)
	body, _ = ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	test.Equal(t, "", string(body))
	test.Equal(t, "nsq; version=1.0", resp.Header.Get("X-NSQ-Content-Type"))

	test.Equal(t, true, channel.IsPaused())

	url = fmt.Sprintf("http://%s/channel/unpause?topic=%s&channel=%s", httpAddr, topicName, channelName)
	resp, err = http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 200, resp.StatusCode)
	body, _ = ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	test.Equal(t, "", string(body))
	test.Equal(t, "nsq; version=1.0", resp.Header.Get("X-NSQ-Content-Type"))

	test.Equal(t, false, channel.IsPaused())

	url = fmt.Sprintf("http://%s/channel/delete?topic=%s&channel=%s", httpAddr, topicName, channelName)
	resp, err = http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 200, resp.StatusCode)
	body, _ = ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	test.Equal(t, "", string(body))
	test.Equal(t, "nsq; version=1.0", resp.Header.Get("X-NSQ-Content-Type"))

	_, err = topic.GetExistingChannel(channelName)
	test.NotNil(t, err)

	url = fmt.Sprintf("http://%s/topic/delete?topic=%s", httpAddr, topicName)
	resp, err = http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 200, resp.StatusCode)
	body, _ = ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	test.Equal(t, "", string(body))
	test.Equal(t, "nsq; version=1.0", resp.Header.Get("X-NSQ-Content-Type"))

	_, err = nsqd.GetExistingTopic(topicName)
	test.NotNil(t, err)
}

func TestHTTPgetStatusJSON(t *testing.T) {
	testTime := time.Now()
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	nsqd.startTime = testTime
	expectedJSON := fmt.Sprintf(`{"version":"%v","health":"OK","start_time":%v,"topics":[],"memory":{`, version.Binary, testTime.Unix())

	url := fmt.Sprintf("http://%s/stats?format=json", httpAddr)
	resp, err := http.Get(url)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	test.Equal(t, 200, resp.StatusCode)
	test.Equal(t, true, strings.HasPrefix(string(body), expectedJSON))
}

func TestHTTPgetStatusText(t *testing.T) {
	testTime := time.Now()
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	nsqd.startTime = testTime

	url := fmt.Sprintf("http://%s/stats?format=text", httpAddr)
	resp, err := http.Get(url)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	test.Equal(t, 200, resp.StatusCode)
	test.NotNil(t, body)
}

func TestHTTPconfig(t *testing.T) {
	lopts := nsqlookupd.NewOptions()
	lopts.Logger = test.NewTestLogger(t)

	lopts1 := *lopts
	_, _, lookupd1 := mustStartNSQLookupd(&lopts1)
	defer lookupd1.Exit()
	lopts2 := *lopts
	_, _, lookupd2 := mustStartNSQLookupd(&lopts2)
	defer lookupd2.Exit()

	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	url := fmt.Sprintf("http://%s/config/nsqlookupd_tcp_addresses", httpAddr)
	resp, err := http.Get(url)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	test.Equal(t, 200, resp.StatusCode)
	test.Equal(t, "[]", string(body))

	client := http.Client{}
	addrs := fmt.Sprintf(`["%s","%s"]`, lookupd1.RealTCPAddr().String(), lookupd2.RealTCPAddr().String())
	url = fmt.Sprintf("http://%s/config/nsqlookupd_tcp_addresses", httpAddr)
	req, err := http.NewRequest("PUT", url, bytes.NewBuffer([]byte(addrs)))
	test.Nil(t, err)
	resp, err = client.Do(req)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ = ioutil.ReadAll(resp.Body)
	test.Equal(t, 200, resp.StatusCode)
	test.Equal(t, addrs, string(body))

	url = fmt.Sprintf("http://%s/config/log_level", httpAddr)
	req, err = http.NewRequest("PUT", url, bytes.NewBuffer([]byte(`fatal`)))
	test.Nil(t, err)
	resp, err = client.Do(req)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ = ioutil.ReadAll(resp.Body)
	test.Equal(t, 200, resp.StatusCode)
	test.Equal(t, LOG_FATAL, nsqd.getOpts().logLevel)

	url = fmt.Sprintf("http://%s/config/log_level", httpAddr)
	req, err = http.NewRequest("PUT", url, bytes.NewBuffer([]byte(`bad`)))
	test.Nil(t, err)
	resp, err = client.Do(req)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ = ioutil.ReadAll(resp.Body)
	test.Equal(t, 400, resp.StatusCode)

	url = fmt.Sprintf("http://%s/config/verbose", httpAddr)
	req, err = http.NewRequest("PUT", url, bytes.NewBuffer([]byte(`true`)))
	test.Nil(t, err)
	resp, err = client.Do(req)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ = ioutil.ReadAll(resp.Body)
	test.Equal(t, 200, resp.StatusCode)
	test.Equal(t, true, nsqd.getOpts().Verbose)

	url = fmt.Sprintf("http://%s/config/verbose", httpAddr)
	req, err = http.NewRequest("PUT", url, bytes.NewBuffer([]byte(`bad`)))
	test.Nil(t, err)
	resp, err = client.Do(req)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ = ioutil.ReadAll(resp.Body)
	test.Equal(t, 400, resp.StatusCode)
}

func TestHTTPerrors(t *testing.T) {
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	url := fmt.Sprintf("http://%s/stats", httpAddr)
	resp, err := http.Post(url, "text/plain", nil)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	test.Equal(t, 405, resp.StatusCode)
	test.Equal(t, `{"message":"METHOD_NOT_ALLOWED"}`, string(body))

	url = fmt.Sprintf("http://%s/not_found", httpAddr)
	resp, err = http.Get(url)
	test.Nil(t, err)
	defer resp.Body.Close()
	body, _ = ioutil.ReadAll(resp.Body)
	test.Equal(t, 404, resp.StatusCode)
	test.Equal(t, `{"message":"NOT_FOUND"}`, string(body))
}

func TestDeleteTopic(t *testing.T) {
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	em := ErrMessage{}

	url := fmt.Sprintf("http://%s/topic/delete", httpAddr)
	resp, err := http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 400, resp.StatusCode)
	test.Equal(t, "Bad Request", http.StatusText(resp.StatusCode))
	body, _ := ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	t.Logf("%s", body)
	err = json.Unmarshal(body, &em)
	test.Nil(t, err)
	test.Equal(t, "MISSING_ARG_TOPIC", em.Message)

	topicName := "test_http_delete_topic" + strconv.Itoa(int(time.Now().Unix()))

	url = fmt.Sprintf("http://%s/topic/delete?topic=%s", httpAddr, topicName)
	resp, err = http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 404, resp.StatusCode)
	test.Equal(t, "Not Found", http.StatusText(resp.StatusCode))
	body, _ = ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	t.Logf("%s", body)
	err = json.Unmarshal(body, &em)
	test.Nil(t, err)
	test.Equal(t, "TOPIC_NOT_FOUND", em.Message)

	nsqd.GetTopic(topicName)

	resp, err = http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 200, resp.StatusCode)
	body, _ = ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	t.Logf("%s", body)
	test.Equal(t, []byte(""), body)
}

func TestEmptyTopic(t *testing.T) {
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	em := ErrMessage{}

	url := fmt.Sprintf("http://%s/topic/empty", httpAddr)
	resp, err := http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 400, resp.StatusCode)
	test.Equal(t, "Bad Request", http.StatusText(resp.StatusCode))
	body, _ := ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	t.Logf("%s", body)
	err = json.Unmarshal(body, &em)
	test.Nil(t, err)
	test.Equal(t, "MISSING_ARG_TOPIC", em.Message)

	topicName := "test_http_empty_topic" + strconv.Itoa(int(time.Now().Unix()))

	url = fmt.Sprintf("http://%s/topic/empty?topic=%s", httpAddr, topicName+"$")
	resp, err = http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 400, resp.StatusCode)
	test.Equal(t, "Bad Request", http.StatusText(resp.StatusCode))
	body, _ = ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	t.Logf("%s", body)
	err = json.Unmarshal(body, &em)
	test.Nil(t, err)
	test.Equal(t, "INVALID_TOPIC", em.Message)

	url = fmt.Sprintf("http://%s/topic/empty?topic=%s", httpAddr, topicName)
	resp, err = http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 404, resp.StatusCode)
	test.Equal(t, "Not Found", http.StatusText(resp.StatusCode))
	body, _ = ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	t.Logf("%s", body)
	err = json.Unmarshal(body, &em)
	test.Nil(t, err)
	test.Equal(t, "TOPIC_NOT_FOUND", em.Message)

	nsqd.GetTopic(topicName)

	resp, err = http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 200, resp.StatusCode)
	body, _ = ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	t.Logf("%s", body)
	test.Equal(t, []byte(""), body)
}

func TestEmptyChannel(t *testing.T) {
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	em := ErrMessage{}

	url := fmt.Sprintf("http://%s/channel/empty", httpAddr)
	resp, err := http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 400, resp.StatusCode)
	test.Equal(t, "Bad Request", http.StatusText(resp.StatusCode))
	body, _ := ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	t.Logf("%s", body)
	err = json.Unmarshal(body, &em)
	test.Nil(t, err)
	test.Equal(t, "MISSING_ARG_TOPIC", em.Message)

	topicName := "test_http_empty_channel" + strconv.Itoa(int(time.Now().Unix()))

	url = fmt.Sprintf("http://%s/channel/empty?topic=%s", httpAddr, topicName)
	resp, err = http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 400, resp.StatusCode)
	test.Equal(t, "Bad Request", http.StatusText(resp.StatusCode))
	body, _ = ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	t.Logf("%s", body)
	err = json.Unmarshal(body, &em)
	test.Nil(t, err)
	test.Equal(t, "MISSING_ARG_CHANNEL", em.Message)

	channelName := "ch"

	url = fmt.Sprintf("http://%s/channel/empty?topic=%s&channel=%s", httpAddr, topicName, channelName)
	resp, err = http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 404, resp.StatusCode)
	test.Equal(t, "Not Found", http.StatusText(resp.StatusCode))
	body, _ = ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	t.Logf("%s", body)
	err = json.Unmarshal(body, &em)
	test.Nil(t, err)
	test.Equal(t, "TOPIC_NOT_FOUND", em.Message)

	topic := nsqd.GetTopic(topicName)

	url = fmt.Sprintf("http://%s/channel/empty?topic=%s&channel=%s", httpAddr, topicName, channelName)
	resp, err = http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 404, resp.StatusCode)
	test.Equal(t, "Not Found", http.StatusText(resp.StatusCode))
	body, _ = ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	t.Logf("%s", body)
	err = json.Unmarshal(body, &em)
	test.Nil(t, err)
	test.Equal(t, "CHANNEL_NOT_FOUND", em.Message)

	topic.GetChannel(channelName)

	resp, err = http.Post(url, "application/json", nil)
	test.Nil(t, err)
	test.Equal(t, 200, resp.StatusCode)
	body, _ = ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	t.Logf("%s", body)
	test.Equal(t, []byte(""), body)
}

func TestInfo(t *testing.T) {
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(t)
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	defer nsqd.Exit()

	info := InfoDoc{}

	url := fmt.Sprintf("http://%s/info", httpAddr)
	resp, err := http.Get(url)
	test.Nil(t, err)
	test.Equal(t, 200, resp.StatusCode)
	body, _ := ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	t.Logf("%s", body)
	err = json.Unmarshal(body, &info)
	test.Nil(t, err)
	test.Equal(t, version.Binary, info.Version)
}

func BenchmarkHTTPpub(b *testing.B) {
	var wg sync.WaitGroup
	b.StopTimer()
	opts := NewOptions()
	opts.Logger = test.NewTestLogger(b)
	opts.MemQueueSize = int64(b.N)
	_, httpAddr, nsqd := mustStartNSQD(opts)
	defer os.RemoveAll(opts.DataPath)
	msg := make([]byte, 256)
	topicName := "bench_http_pub" + strconv.Itoa(int(time.Now().Unix()))
	url := fmt.Sprintf("http://%s/pub?topic=%s", httpAddr, topicName)
	client := &http.Client{}
	b.SetBytes(int64(len(msg)))
	b.StartTimer()

	for j := 0; j < runtime.GOMAXPROCS(0); j++ {
		wg.Add(1)
		go func() {
			num := b.N / runtime.GOMAXPROCS(0)
			for i := 0; i < num; i++ {
				buf := bytes.NewBuffer(msg)
				req, _ := http.NewRequest("POST", url, buf)
				resp, err := client.Do(req)
				if err != nil {
					panic(err.Error())
				}
				body, _ := ioutil.ReadAll(resp.Body)
				if !bytes.Equal(body, []byte("OK")) {
					panic("bad response")
				}
				resp.Body.Close()
			}
			wg.Done()
		}()
	}

	wg.Wait()

	b.StopTimer()
	nsqd.Exit()
}


text:
<span style="display: inline-block;">
[![Go Report Card](https://goreportcard.com/badge/github.com/tankzter/tankzter)](https://goreportcard.com/report/github.com/tankzter/tankzter)
[![Travis CI Status](https://travis-ci.org/tankzter/tankzter.svg?branch=master)](https://travis-ci.org/tankzter/tankzter)
[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/tankzter/tankzter/blob/master/LICENSE)
</span>

Tankzter is an oldschool tanks game server.

###Requirements
Tankzter requirements:
* [Golang](https://golang.org). To install it, follow this [guide](https://golang.org/doc/install).
* PostreSQL

###Installation
To install `tankzter` run the following:

    go get -u github.com/tankzter/tankzter

###Prepare

Create postgresql DB.

    ./scripts/pg_deps.sh # sudo -u postgres

Init database content.

    ./scripts/pg_data.sh

####Make

    go build tankzter_server.go

###Usage

    ./tankzter_server

###Tests

    go test -v ./...


text:
{-# LANGUAGE OverloadedStrings #-}

module Stashh.Repos.Model where

import Stashh.Table
import Stashh.Model.Type
import qualified Stashh.AnsiColor as C

import Data.Maybe
import Control.Applicative
import qualified Data.Vector as V
import Data.Aeson

----------------------------------------------
-- Repos

data ReposResult = ReposResult
  { start       :: Int
  , size        :: Int
  , limit       :: Int
  , filter      :: Maybe String
  , isLastPage  :: Bool
  , values      :: V.Vector Repo
  }
  deriving (Show, Eq)

data Repo = Repo
  { repoId        :: Int
  , slug          :: String
  , repoName      :: String
  , scmId         :: String
  , state         :: String
  , statusMessage :: String
  , forkable      :: Maybe Bool
  {- , project    :: Project -}
  , cloneUrl      :: String
  , link          :: Link
  }
  deriving (Show, Eq)

instance FromJSON ReposResult where
  parseJSON (Object v) = ReposResult
                          <$> v .:  "start"
                          <*> v .:  "size"
                          <*> v .:  "limit"
                          <*> v .:? "filter"
                          <*> v .:  "isLastPage"
                          <*> v .:?  "values" .!= V.empty
  parseJSON _          = fail "ReposResult"

instance FromJSON Repo where
  parseJSON (Object v) = Repo
                          <$> v .:  "id"
                          <*> v .:  "slug"
                          <*> v .:  "name"
                          <*> v .:  "scmId"
                          <*> v .:  "state"
                          <*> v .:  "statusMessage"
                          <*> v .:? "forkable"
                          <*> v .:  "cloneUrl"
                          <*> v .:  "link"
  parseJSON _          = fail "Repo"

instance TableDef Repo where
  columnsDef =
    [ ColDesc center "Id"            right C.cyan  (show . repoId)
    , ColDesc center "Slug"          left  C.green slug
    , ColDesc center "Name"          left  id      repoName
    , ColDesc center "ScmId"         left  id      scmId
    , ColDesc center "StatusMessage" left  C.blue  statusMessage
    , ColDesc center "Forkable"      left  id      (showMaybe forkable)
    , ColDesc left   "CloneUrl"      left  id      cloneUrl
    , ColDesc left   "Link"          left  id      (linkUrl . link)
    ]

instance PagingDef ReposResult where
  paging_start r = start r
  paging_size  r = size r
  paging_limit r = limit r
  paging_last r  = isLastPage r


text:
<?php

/**
 * BaseDmSentMail
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @property integer $dm_mail_template_id
 * @property string $subject
 * @property clob $body
 * @property string $from_email
 * @property string $to_email
 * @property string $cc_email
 * @property string $bcc_email
 * @property string $reply_to_email
 * @property string $sender_email
 * @property string $strategy
 * @property string $transport
 * @property string $culture
 * @property clob $debug_string
 * @property DmMailTemplate $Template
 *
 * @method integer        getDmMailTemplateId()    Returns the current record's "dm_mail_template_id" value
 * @method string         getSubject()             Returns the current record's "subject" value
 * @method clob           getBody()                Returns the current record's "body" value
 * @method string         getFromEmail()           Returns the current record's "from_email" value
 * @method string         getToEmail()             Returns the current record's "to_email" value
 * @method string         getCcEmail()             Returns the current record's "cc_email" value
 * @method string         getBccEmail()            Returns the current record's "bcc_email" value
 * @method string         getReplyToEmail()        Returns the current record's "reply_to_email" value
 * @method string         getSenderEmail()         Returns the current record's "sender_email" value
 * @method string         getStrategy()            Returns the current record's "strategy" value
 * @method string         getTransport()           Returns the current record's "transport" value
 * @method string         getCulture()             Returns the current record's "culture" value
 * @method clob           getDebugString()         Returns the current record's "debug_string" value
 * @method DmMailTemplate getTemplate()            Returns the current record's "Template" value
 * @method DmSentMail     setDmMailTemplateId()    Sets the current record's "dm_mail_template_id" value
 * @method DmSentMail     setSubject()             Sets the current record's "subject" value
 * @method DmSentMail     setBody()                Sets the current record's "body" value
 * @method DmSentMail     setFromEmail()           Sets the current record's "from_email" value
 * @method DmSentMail     setToEmail()             Sets the current record's "to_email" value
 * @method DmSentMail     setCcEmail()             Sets the current record's "cc_email" value
 * @method DmSentMail     setBccEmail()            Sets the current record's "bcc_email" value
 * @method DmSentMail     setReplyToEmail()        Sets the current record's "reply_to_email" value
 * @method DmSentMail     setSenderEmail()         Sets the current record's "sender_email" value
 * @method DmSentMail     setStrategy()            Sets the current record's "strategy" value
 * @method DmSentMail     setTransport()           Sets the current record's "transport" value
 * @method DmSentMail     setCulture()             Sets the current record's "culture" value
 * @method DmSentMail     setDebugString()         Sets the current record's "debug_string" value
 * @method DmSentMail     setTemplate()            Sets the current record's "Template" value
 *
 * @package    Acme
 * @subpackage model
 * @author     Your name here
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
abstract class BaseDmSentMail extends myDoctrineRecord
{
    public function setTableDefinition()
    {
        $this->setTableName('dm_sent_mail');
        $this->hasColumn('dm_mail_template_id', 'integer', null, array(
             'type' => 'integer',
             ));
        $this->hasColumn('subject', 'string', 5000, array(
             'type' => 'string',
             'notnull' => true,
             'length' => 5000,
             ));
        $this->hasColumn('body', 'clob', null, array(
             'type' => 'clob',
             'notnull' => true,
             ));
        $this->hasColumn('from_email', 'string', 5000, array(
             'type' => 'string',
             'notnull' => true,
             'length' => 5000,
             ));
        $this->hasColumn('to_email', 'string', 5000, array(
             'type' => 'string',
             'length' => 5000,
             ));
        $this->hasColumn('cc_email', 'string', 5000, array(
             'type' => 'string',
             'length' => 5000,
             ));
        $this->hasColumn('bcc_email', 'string', 5000, array(
             'type' => 'string',
             'length' => 5000,
             ));
        $this->hasColumn('reply_to_email', 'string', 5000, array(
             'type' => 'string',
             'length' => 5000,
             ));
        $this->hasColumn('sender_email', 'string', 5000, array(
             'type' => 'string',
             'length' => 5000,
             ));
        $this->hasColumn('strategy', 'string', 255, array(
             'type' => 'string',
             'length' => 255,
             ));
        $this->hasColumn('transport', 'string', 255, array(
             'type' => 'string',
             'length' => 255,
             ));
        $this->hasColumn('culture', 'string', 16, array(
             'type' => 'string',
             'length' => 16,
             ));
        $this->hasColumn('debug_string', 'clob', null, array(
             'type' => 'clob',
             ));
    }

    public function setUp()
    {
        parent::setUp();
        $this->hasOne('DmMailTemplate as Template', array(
             'local' => 'dm_mail_template_id',
             'foreign' => 'id',
             'onDelete' => 'SET NULL'));

        $timestampable0 = new Doctrine_Template_Timestampable(array(
             'updated' =>
             array(
              'disabled' => true,
             ),
             ));
        $this->actAs($timestampable0);
    }
}