text:
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace NonFactors.Mvc.Grid
{
    public class GridColumn<T, TValue> : IGridColumn<T, TValue> where T : class
    {
        public IGrid<T> Grid { get; set; }

        public String Name { get; set; }
        public Object Title { get; set; }
        public String? Format { get; set; }
        public Boolean IsHidden { get; set; }
        public String CssClasses { get; set; }
        public Boolean IsEncoded { get; set; }
        public GridProcessorType ProcessorType { get; set; }

        public Func<T, TValue> ExpressionValue { get; set; }
        public Func<T, Int32, Object?>? RenderValue { get; set; }
        public Expression<Func<T, TValue>> Expression { get; set; }

        IGridColumnSort IGridColumn.Sort => Sort;
        public virtual IGridColumnSort<T, TValue> Sort { get; set; }

        IGridColumnFilter IGridColumn.Filter => Filter;
        public virtual IGridColumnFilter<T, TValue> Filter { get; set; }

        public GridColumn(IGrid<T> grid, Expression<Func<T, TValue>> expression)
        {
            Grid = grid;
            CssClasses = "";
            IsEncoded = true;
            Expression = expression;
            Name = NameFor(expression);
            Title = TitleFor(expression);
            ProcessorType = GridProcessorType.Pre;
            ExpressionValue = expression.Compile();
            Sort = new GridColumnSort<T, TValue>(this);
            Filter = new GridColumnFilter<T, TValue>(this);
        }

        public virtual IQueryable<T> Process(IQueryable<T> items)
        {
            return Sort.Apply(Filter.Apply(items));
        }
        public virtual IHtmlString ValueFor(IGridRow<Object> row)
        {
            Object? value = ColumnValueFor(row);

            if (value == null)
                return MvcHtmlString.Empty;

            if (value is IHtmlString content)
                return content;

            if (Format != null)
                value = String.Format(Format, value);

            if (IsEncoded)
                return new HtmlString(WebUtility.HtmlEncode(value.ToString()));

            return new HtmlString(value.ToString());
        }

        private String TitleFor(Expression<Func<T, TValue>> expression)
        {
            MemberExpression? body = expression.Body as MemberExpression;
            DisplayAttribute? display = body?.Member.GetCustomAttribute<DisplayAttribute>();

            return display?.GetShortName() ?? "";
        }
        private String NameFor(Expression<Func<T, TValue>> expression)
        {
            String text = expression.Body is MemberExpression member ? member.ToString() : "";
            text = text.IndexOf('.') > 0 ? text.Substring(text.IndexOf('.') + 1) : text;
            text = text.Replace("_", "-");

            return String.Join("-", Regex.Split(text, "(?<=[a-zA-Z])(?=[A-Z])")).ToLower();
        }
        private Object? ColumnValueFor(IGridRow<Object> row)
        {
            try
            {
                if (RenderValue != null)
                    return RenderValue((row.Model as T)!, row.Index);

                Type type = Nullable.GetUnderlyingType(typeof(TValue)) ?? typeof(TValue);
                if (type.GetTypeInfo().IsEnum)
                    return EnumValue(type, ExpressionValue((row.Model as T)!)!.ToString()!);

                return ExpressionValue((row.Model as T)!);
            }
            catch (NullReferenceException)
            {
                return null;
            }
        }
        private String? EnumValue(Type type, String value)
        {
            return type
                .GetMember(value)
                .FirstOrDefault()?
                .GetCustomAttribute<DisplayAttribute>()?
                .GetName() ?? value;
        }
    }
}


text:
using System.ComponentModel;
namespace CTRC.Tests
{
    enum TestEnum
    {
        [Description("0")]
        Value0 = 0,
        [Description("x")]
        Value1 = 1,
        [Description("y")]
        Value2 = 2
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace c0710204\mirrorSite\ManagerBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * mirrorinfo
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class mirrorinfo
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    public $id;

    /**
     * @var string
     *
     * @ORM\Column(name="rootpath", type="string", length=255)
     */
    public $rootpath;

    /**
     * @var string
     *
     * @ORM\Column(name="href", type="string", length=255)
     */
    public $href;

    /**
     * @var string
     *
     * @ORM\Column(name="intro", type="text")
     */
    public $intro;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    public $name;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=255)
     */
    public $title;

    /**
     * @var boolean
     *
     * @ORM\Column(name="official", type="boolean")
     */
    public $official;

    /**
     * @var string
     *
     * @ORM\Column(name="worker_link", type="string", length=255)
     */
    public $workerLink;

    /**
     * @var string
     *
     * @ORM\Column(name="worker_name", type="string", length=255)
     */
    public $workerName;

    /**
     * @var integer
     * @ORM\OneToOne(targetEntity="mirrorstatus", cascade={"all"}, fetch="EAGER")
     */
    public $status;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set rootpath
     *
     * @param string $rootpath
     * @return mirrorinfo
     */
    public function setRootpath($rootpath)
    {
        $this->rootpath = $rootpath;

        return $this;
    }

    /**
     * Get rootpath
     *
     * @return string
     */
    public function getRootpath()
    {
        return $this->rootpath;
    }

    /**
     * Set href
     *
     * @param string $href
     * @return mirrorinfo
     */
    public function setHref($href)
    {
        $this->href = $href;

        return $this;
    }

    /**
     * Get href
     *
     * @return string
     */
    public function getHref()
    {
        return $this->href;
    }

    /**
     * Set intro
     *
     * @param string $intro
     * @return mirrorinfo
     */
    public function setIntro($intro)
    {
        $this->intro = $intro;

        return $this;
    }

    /**
     * Get intro
     *
     * @return string
     */
    public function getIntro()
    {
        return $this->intro;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return mirrorinfo
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return mirrorinfo
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set official
     *
     * @param boolean $official
     * @return mirrorinfo
     */
    public function setOfficial($official)
    {
        $this->official = $official;

        return $this;
    }

    /**
     * Get official
     *
     * @return boolean
     */
    public function getOfficial()
    {
        return $this->official;
    }

    /**
     * Set workerLink
     *
     * @param string $workerLink
     * @return mirrorinfo
     */
    public function setWorkerLink($workerLink)
    {
        $this->workerLink = $workerLink;

        return $this;
    }

    /**
     * Get workerLink
     *
     * @return string
     */
    public function getWorkerLink()
    {
        return $this->workerLink;
    }

    /**
     * Set workerName
     *
     * @param string $workerName
     * @return mirrorinfo
     */
    public function setWorkerName($workerName)
    {
        $this->workerName = $workerName;

        return $this;
    }

    /**
     * Get workerName
     *
     * @return string
     */
    public function getWorkerName()
    {
        return $this->workerName;
    }
    /**
     * Set status
     *
     * @param integer $status
     * @return mirrorinfo
     */
    public function setstatus($status)
    {
        $this->status = $status;

        return $this;
    }

    /**
     * Get status
     *
     * @return integer
     */
    public function getstatus()
    {
        return $this->status;
    }
    /**
     * Get description
     *
     * @return string
     */
    public function __tostring()
    {
        return $this->name;
    }
}


text:
package pl.newicom.dddd.messaging

import org.joda.time.DateTime.now
import pl.newicom.dddd.messaging.MetaAttribute._
import pl.newicom.dddd.utils.UUIDSupport.uuid

object MetaDataPropagationPolicy {
  val onCommandAccepted: OnCommandAcceptedByAR.type          = OnCommandAcceptedByAR
  val onCommandSentByPM: OnCommandDeliveryRequestedByPM.type = OnCommandDeliveryRequestedByPM
  val onEventAcceptedByPM: OnEventAcceptedByPM.type          = OnEventAcceptedByPM
}

sealed trait MetaDataPropagationPolicy {
  def apply(from: MetaData, to: MetaData): MetaData
}

case object OnCommandAcceptedByAR extends MetaDataPropagationPolicy {
  override def apply(command: MetaData, event: MetaData): MetaData = {
    event
      .withAttr(Causation_Id, command.get(Id))
      .withOptionalAttr(Correlation_Id, command.tryGet(Correlation_Id))
      .withAttr(Tags, Tags.merge(command, event))
  }
}

case object OnEventAcceptedByPM extends MetaDataPropagationPolicy {
  override def apply(receivedEvent: MetaData, eventToStore: MetaData): MetaData = {
    eventToStore
      .withAttr(Delivery_Id, receivedEvent.get(Delivery_Id))
      .withOptionalAttr(Must_Follow, receivedEvent.tryGet(Must_Follow))
      .withAttr(Causation_Id, receivedEvent.get(Id))
      .withOptionalAttr(Correlation_Id, receivedEvent.tryGet(Correlation_Id))
      .remove(Tags)
  }
}

case object OnCommandDeliveryRequestedByPM extends MetaDataPropagationPolicy {
  override def apply(event: MetaData, command: MetaData = MetaData.empty): MetaData = {
    command
      .withAttr(Id, uuid(event.get(Id)))
      .withAttr(Causation_Id, event.get(Id))
      .withOptionalAttr(Correlation_Id, event.tryGet(Correlation_Id))
      .withAttr(Tags, Tags.merge(event, command))
      .withAttr(Timestamp, now)
  }
}


text:
import os, re, subprocess, json, collections
from sphinx.addnodes import toctree
from docutils import io, nodes, statemachine, utils
from docutils.parsers.rst import Directive
from jinja2 import Environment, PackageLoader

# Maintain a cache of previously loaded examples
example_cache = {}

# Maintain a cache of previously loaded service descriptions
description_cache = {}

def setup(app):
    """
    see: http://sphinx.pocoo.org/ext/appapi.html
    this is the primary extension point for Sphinx
    """
    from sphinx.application import Sphinx
    if not isinstance(app, Sphinx): return

    app.add_directive('service', ServiceIntro)
    app.add_directive('apiref', ServiceApiRef)
    app.add_directive('indexlinks', ServiceIndexLinks)
    app.add_directive('example', ExampleDirective)

class ServiceDescription():
    """
    Loads the service description for a given source file
    """

    def __init__(self, service):
        self.service_name = service
        self.description = self.load_description(self.determine_filename())

    def determine_filename(self):
        """Determines the filename to load for a service"""
        # Determine the path to the mss-config
        path = os.path.abspath("../src/Mss/Common/Resources/mss-config.php")
        self.config = self.__load_php(path)

        # Iterate over the loaded dictionary and see if a matching service exists
        for key in self.config["services"]:
            alias = self.config["services"][key].get("alias", "")
            if key == self.service_name or alias == self.service_name:
                break
        else:
            raise ValueError("No service matches %s" % (self.service_name))

        # Determine the name of the client class to load
        class_path = self.config["services"][key]["class"].replace("\\", "/")
        client_path = os.path.abspath("../src/" + class_path + ".php")
        contents = open(client_path, 'r').read()

        # Determine the current version of the client (look at the LATEST_API_VERSION constant value)
        version = re.search("LATEST_API_VERSION = '(.+)'", contents).groups(0)[0]

        # Determine the name of the service description used by the client
        matches = re.search("__DIR__ \. '/Resources/(.+)\.php'", contents)
        description = matches.groups(0)[0] % (version)

        # Strip the filename of the client and determine the description path
        service_path = "/".join(client_path.split(os.sep)[0:-1])
        service_path += "/Resources/" + description + ".php"

        return service_path

    def load_description(self, path):
        """Determines the filename to load for a service

        :param path: Path to a service description to load
        """
        description = self.__load_php(path)

        return description

    def __load_php(self, path):
        """Load a PHP script that returns an array using JSON

        :param path: Path to the script to load
        """
        path = os.path.abspath(path)

        # Make command to each environment Linux/Mac and Windows
        if os.name == 'nt':
            sh = 'php -r \"$c = include \'' + path + '\'; echo json_encode($c);\"'
        else:
            sh = 'php -r \'$c = include "' + path + '"; echo json_encode($c);\''

        loaded = subprocess.check_output(sh, shell=True)
        return json.loads(loaded)

    def __getitem__(self, i):
        """Allows access to the service description items via the class"""
        return self.description.get(i)

def load_service_description(name):
    if name not in description_cache:
        description_cache[name] = ServiceDescription(name)
    return description_cache[name]

class ServiceDescriptionDirective(Directive):
    """
    Base class for directives that use information from service descriptions
    """

    required_arguments = 1
    optional_arguments = 1
    final_argument_whitespace = True

    def run(self):
        if len(self.arguments) == 2:
            api_version = self.arguments[1].strip()
        else:
            api_version = ""
        service_name = self.arguments[0].strip()
        service_description = load_service_description(service_name)

        rawtext = self.generate_rst(service_description, api_version)
        tab_width = 4
        include_lines = statemachine.string2lines(
            rawtext, tab_width, convert_whitespace=1)
        self.state_machine.insert_input(
            include_lines, os.path.abspath(__file__))
        return []

    def get_service_doc_url(self, namespace):
        """Determine the documentation link for a service"""
        namespace = namespace.lower()
        if namespace == "sts":
            return "http://aws.amazon.com/documentation/iam/"
        else:
            return "http://aws.amazon.com/documentation/" + namespace

    def get_api_ref_url(self, namespace):
        """Determine the PHP API documentation link for a service"""
        return "http://docs.aws.amazon.com/aws-sdk-php/v2/api/class-Mss." + namespace + "." + namespace + "Client.html"

    def get_locator_name(self, name):
        """Determine the service locator name for an endpoint"""
        return name

class ServiceIntro(ServiceDescriptionDirective):
    """
    Creates a service introduction to inject into a document
    """

    def generate_rst(self, d, api_version):
        rawtext = ""
        scalar = {}

        # Grab all of the simple strings from the description
        for key in d.description:
            if isinstance(d[key], str) or isinstance(d[key], unicode):
                scalar[key] = d[key]
                # Add substitutions for top-level data in a service description
                rawtext += ".. |%s| replace:: %s\n\n" % (key, scalar[key])

        # Determine the doc URL
        docs = self.get_service_doc_url(d["namespace"])

        # Determine the "namespace" used for linking to API docs
        if api_version:
            apiVersionSuffix = "_" + api_version.replace("-", "_")
        else:
            apiVersionSuffix = ""

        env = Environment(loader=PackageLoader('aws', 'templates'))
        template = env.get_template("client_intro")
        rawtext += template.render(
            scalar,
            doc_url=docs,
            specifiedApiVersion=api_version,
            apiVersionSuffix=apiVersionSuffix)

        return rawtext

class ServiceApiRef(ServiceDescriptionDirective):
    """
    Inserts a formatted PHPUnit example into the source
    """

    def generate_rst(self, d, api_version):
        rawtext = ""
        scalar = {}
        # Sort the operations by key
        operations = collections.OrderedDict(sorted(d.description['operations'].items()))

        # Grab all of the simple strings from the description
        for key in d.description:
            if isinstance(d[key], str) or isinstance(d[key], unicode):
                scalar[key] = d[key]
                # Add substitutions for top-level data in a service description
                rawtext += ".. |%s| replace:: %s\n\n" % (key, scalar[key])

        # Add magic methods to each operation
        for key in operations:
            operations[key]['magicMethod'] = key[0].lower() + key[1:]

        # Set the ordered dict of operations on the description
        d.description['operations'] = operations

        # Determine the "namespace" used for linking to API docs
        if api_version:
            apiVersionSuffix = "_" + api_version.replace("-", "_")
        else:
            apiVersionSuffix = ""

        env = Environment(loader=PackageLoader('aws', 'templates'))
        template = env.get_template("api_reference")
        rawtext += template.render(
            scalar,
            description=d.description,
            apiVersionSuffix=apiVersionSuffix)

        return rawtext

class ServiceIndexLinks(ServiceDescriptionDirective):
    """
    Inserts a formatted PHPUnit example into the source
    """

    def generate_rst(self, service_description, api_version):
        d = service_description.description

        service_name = d["serviceFullName"]
        if "serviceAbbreviation" in d:
            service_name = d["serviceAbbreviation"]

        rawtext = "* :doc:`Using the " + service_name + " PHP client <service-" + d["namespace"].lower() + ">`\n";
        rawtext += "* `PHP API reference <" + self.get_api_ref_url(d["namespace"]) + ">`_\n";
        #rawtext += "* `General service documentation for " + service_name + " <" + self.get_service_doc_url(d["namespace"]) + ">`_\n";

        return rawtext

class ExampleDirective(Directive):
    """
    Inserts a formatted PHPUnit example into the source
    """

    # Directive configuration
    required_arguments = 2
    optional_arguments = 0
    final_argument_whitespace = True

    def run(self):
        self.end_function = "    }\n"
        self.begin_tag = "        // @begin\n"
        self.end_tag = "        // @end\n"

        example_file = self.arguments[0].strip()
        example_name = self.arguments[1].strip()

        if not example_name:
            raise ValueError("Must specify both an example file and example name")

        contents = self.load_example(example_file, example_name)
        rawtext = self.generate_rst(contents)
        tab_width = 4
        include_lines = statemachine.string2lines(
            rawtext, tab_width, convert_whitespace=1)
        self.state_machine.insert_input(
            include_lines, os.path.abspath(__file__))
        return []

    def load_example(self, example_file, example_name):
        """Loads the contents of an example and strips out non-example parts"""
        key = example_file + '.' + example_name

        # Check if this example is cached already
        if key in example_cache:
            return example_cache[key]

        # Not cached, so index the example file functions
        path = os.path.abspath(__file__ + "/../../../../tests/Mss/Tests/" + example_file)

        f = open(path, 'r')
        in_example = False
        capturing = False
        buffer = ""

        # Scan each line of the file and create example hashes
        for line in f:
            if in_example:
                if line == self.end_function:
                    if in_example:
                        example_cache[in_example] = buffer
                    buffer = ""
                    in_example = False
                elif line == self.begin_tag:
                    # Look for the opening // @begin tag to begin capturing
                    buffer = ""
                    capturing = True
                elif line == self.end_tag:
                    # Look for the optional closing tag to stop capturing
                    capturing = False
                elif capturing:
                    buffer += line
            elif "public function test" in line:
                # Grab the function name from the line and keep track of the
                # name of the current example being captured
                current_name = re.search('function (.+)\s*\(', line).group(1)
                in_example = example_file + "." + current_name
        f.close()
        return example_cache[key]

    def generate_rst(self, contents):
        rawtext = ".. code-block:: php\n\n" + contents
        return rawtext


text:
/*!
 * module deps
 */

var createStore = require('dispatchr/utils/createStore'),
    elasticstream = require('elasticstream'),
    es = require('elasticsearch'),
    clone = require('lodash.clone'),
    Firequeue = require('firequeue'),
    Firenext = require('firenext'),
    firestream = require('firestream');

/*!
 * module globals
 */

var isServer = typeof window === 'undefined',
    jobEvents = {},
    streams = {},
    config, client, queue, ref, filter, stats, query, currentJobId;
/**
 * get Job by id
 *
 * @return {Promise}
 */

function getJobById(id) {
  return ref
    .child('jobs')
    .child(id)
    .exec();
}

/**
 * get job stream
 *
 * @param  {String} status
 */

function getStreamByStatus(status) {
  var stream;

  if (!status) status = 'all';
  if (streams[status]) return streams[status];

  if (status === 'all') {
    stream = firestream.create(ref.child('jobs'));
  } else {
    stream = firestream
    .create(ref.child('states').child(status))
    .map(function(data) {
      return getJobById(data.key());
    });
  }

  streams[status] = stream;
  return stream;
}

/**
 * get job stream
 *
 * @param  {String} status
 */

function getEventStream(jobId) {
  if (!jobId) return;

  if (!jobEvents[jobId]) {
    jobEvents[jobId] = firestream.create(ref.child('events').child(jobId));
  }
  return jobEvents[jobId];
}

/*!
 * exports Job Store
 */

module.exports = createStore({
  storeName: 'Job',
  handlers: {
    'UPDATE_CURRENT_JOB': 'onCurrentJobChange',
    'UPDATE_CURRENT_FILTER': 'onFilterChange',
    'UPDATE_SEARCH_QUERY': 'onSearchChange'
  },

  /**
   * get current Stream
   *
   * @return {Array}
   */

  getStream: function() {
    return getStreamByStatus(filter);
  },

  /**
   * get current event Stream
   *
   * @return {Array}
   */

  getEventStream: function() {
    return getEventStream(currentJobId);
  },

  /**
   * listen to stats changes
   */

  listenStatsChange: function() {
    ref.child('stats').on('value', function(snap) {
      stats = snap.val();
      this.emitChange();
    }.bind(this));
  },

  /**
   * create a new job
   */

  createJob: function(name, data) {
    return queue.client
      .create(name, data)
      .save();
  },

  getStats: function() {
    return stats;
  },

  getFilter: function() {
    return filter;
  },

  /**
   * update job state
   */

  changeJobState: function(key, fromState, toState) {
    return queue.client.changeState(key, fromState, toState);
  },

  /**
   * handle filter change
   * @param  {String} newFilter
   */

  onSearchChange: function (params) {
    var previousQuery = query,
        previousStream, currentStream;

    if (previousQuery === params.query) return;
    query = params.query;
    if (isServer) return;

    // init previous and current stream
    previousStream = getStreamByStatus(filter);
    currentStream = elasticstream
      .create(client, {
        query: {
          index: config.elasticsearch.index,
          type: config.elasticsearch.type,
          q: params.query
        }
      })
      .map(function(hit) {
        return getJobById(hit._id);
      })
      .filter(function(data) {
        return data.val() !== null;
      });

    // set new filter
    filter = 'search';
    streams[filter] = currentStream;

    // remove listener on previous stream
    previousStream.removeAllListeners();

    // listen and emit changes
    currentStream.on('value', this.emitChange.bind(this));

    // trigger first read
    if (!currentStream.isStarted()) currentStream.read();

    this.emitChange();
  },

  /**
   * handle filter change
   * @param  {String} newFilter
   */

  onFilterChange: function (params) {
    var previousFilter = filter,
        previousStream, currentStream;

    // set new currentJobId
    if (previousFilter === params.filter) return;
    filter = params.filter;
    if (isServer) return;

    // init previous and current stream
    previousStream = getStreamByStatus(filter);
    currentStream = getStreamByStatus(params.filter);

    // set new filter
    filter = params.filter;

    // remove listener on previous stream
    previousStream.removeAllListeners();

    // listen and emit changes
    currentStream.on('value', this.emitChange.bind(this));

    // trigger first read
    if (!currentStream.isStarted()) currentStream.read();

    this.emitChange();
  },

  /**
   * handle current job change
   *
   * @param  {String} newFilter
   */

  onCurrentJobChange: function (params) {
    var previousJobId = currentJobId,
        previousStream, currentStream;

    // set new currentJobId
    if (previousJobId === params.id) return;
    currentJobId = params.id;
    if (isServer) return;

    // init previous and current stream
    previousStream = getEventStream(currentJobId);
    currentStream = getEventStream(params.id);

    // remove listener on previous stream
    if (previousStream) previousStream.removeAllListeners();

    // listen and emit changes
    if (currentStream) {
      currentStream.on('value', this.emitChange.bind(this));
      if (!currentStream.isStarted()) currentStream.read();
    }
    this.emitChange();
  },

  getCurrentJobId: function() {
    return currentJobId;
  },

  setConfig: function(c) {
    config = clone(c);
    this.emitChange();
  },

  getConfig: function() {
    return config;
  },

  /**
   * dehydrate store
   */

  dehydrate: function () {
    return {
      config: config,
      filter: filter,
      id: currentJobId,
      query: query
    };
  },

  /**
   * rehydrate store
   */

  rehydrate: function (state) {
    this.setConfig(state.config);

    client = new es.Client(config.elasticsearch.client);
    ref =  new Firenext(config.firebase);
    queue = new Firequeue(config.firebase);

    this.listenStatsChange();
    this.onCurrentJobChange({ id: state.id });

    if (state === 'search') {
      this.onSearchChange({ query: state.query, id: state.id });
    } else {
      this.onFilterChange({ filter: state.filter || 'all', id: state.id });
    }
  }
});


text:
package receipt_parser;

import java.util.ArrayList;
import java.util.HashMap;

import budgeter.Expense;
import budgeter.PurchasedItem;
import ocr_reader.Cluster;
import ocr_reader.Reader;
import receipt_parser.float_list_factory.FloatListFactory;

public class ReceiptParser {

	public String imageUrl;

	public ReceiptParser(String imageUrl) {
		this.imageUrl = imageUrl;
	}

	public Expense parse() {
		ArrayList<Cluster> clusters = readImage();

		ArrayList<MyFloat> floats = getFloats(clusters);
		ArrayList<PurchasedItem> purchasedItems = makePurchasedItems(clusters, floats);
		Expense r = new Expense(purchasedItems);
		return r;
	}

	private ArrayList<Cluster> readImage() {
		Reader reader = new Reader(imageUrl);
		return reader.read();
	}

	private ArrayList<MyFloat> getFloats(ArrayList<Cluster> clusters) {
		FloatListFactory floatListFactory = makeFloatListFactory(clusters);
		return floatListFactory.getAssociatedFloats();
	}

	private ArrayList<PurchasedItem> makePurchasedItems(ArrayList<Cluster> clusters, ArrayList<MyFloat> floats) {
		FloatListFactory floatListFactory = makeFloatListFactory(clusters);
		HashMap<Integer, Phrase> map = floatListFactory.getLocationToWordMapWithoutFloats();
		PurchasedItemFactory purchasedItemFactory = new PurchasedItemFactory(map, floats);
		return purchasedItemFactory.makePuchasedItems();
	}

	private FloatListFactory makeFloatListFactory(ArrayList<Cluster> clusters) {
		FloatListFactory floatListFactory = new FloatListFactory();
		for (Cluster c : clusters) {
			floatListFactory.addData(c.location, c.words);
		}
		return floatListFactory;
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.jivesoftware.smack.initializer (smack-core 4.2.0-beta3-SNAPSHOT API)</title>
<meta name="date" content="2016-08-29">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.jivesoftware.smack.initializer

Code used to initialize Smack.

See: Description

Interface Summary

Interface
Description

SmackInitializer

Defines an initialization class that will be instantiated and invoked by the SmackConfiguration class during initialization.

Class Summary

Class
Description

UrlInitializer

Loads the provider file defined by the URL returned by UrlInitializer.getProvidersUrl() and the generic
 smack configuration file returned UrlInitializer.getConfigUrl().

VmArgInitializer

Looks for a provider file location based on the VM argument smack.provider.file</>.

Package org.jivesoftware.smack.initializer Description

Code used to initialize Smack.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
//var debug = require('debug')('appdata.nunit');

var Mongo = require('../../js/utils/mongo.js');

//var connectionStringTestDB = 'mongodb://localhost/testdb';
//  mongoose.connect('mongodb://localhost/nodeunit');

it('testOpen', async () => {
  expect.assertions(7);
  var fakeMongoose = {
    connect: function (str) {
      expect(str).toEqual('mongodb://localhost/nodeunit');
    },
    connection: {
      on: function (a, arg) {
        expect(a).toEqual('error');
      },
      once: function (a, arg) {
        if (a === 'open') {
          expect(typeof arg).toEqual('function');
          setTimeout(arg, 0);
        } else if (a === 'error') {
          expect(typeof arg).toEqual('function');
        } else {
          expect(1).toEqual(0);
        }
      }
    }
  };

  fakeMongoose.connection.once.setMaxListeners = function () {
    expect(arguments[0]).toEqual(0);
    expect(arguments.length).toEqual(1);
  };
  fakeMongoose.connection.on.setMaxListeners = function () {
    expect(arguments[0]).toEqual(0);
    expect(arguments.length).toEqual(1);
  };

  Mongo.openMongoose(fakeMongoose, undefined).then(res => {
    //test.done()

  }
  );
});

it('testDisconnectReset', async () => {
  expect.assertions(2);
  var fakeMongoose = {
    connection: {
      modelNames: function () {
        return ['abc'];
      },
      models: { 'abc': 1 },
      readyState: 1
    },
    disconnect: function () {
      expect(arguments.length).toEqual(0);
    }
  };
  Mongo.disconnectReset(fakeMongoose);
  expect(Object.keys(fakeMongoose.connection.models).length).toEqual(0);

});

it('testGetCollectionNames', async () => {
  expect.assertions(1);
  var fakeMongoose = {
    connection: {
      db: {
        collections : function() {
          return Promise.resolve([ { collectionName : 'abc'}, { collectionName : 'def'}]);
        }
      }
    },
  };
  Mongo.getCollectionNames(fakeMongoose).then( cols => {
    expect(cols).toEqual(['abc', 'def']);

    //test.done()

  });
});


text:
My dotfiles with a quick installation script.
I do not advice anyone to install it as is but rather
to look at the script if it can help you!

## Installation

```sh
sh -c "$(curl -fsSL https://raw.githubusercontent.com/lenemson/dotfiles/master/setup.sh)"
```

Curl, Git, Vim and Bash must be installed.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                "http://www.w3.org/TR/REC-html40/loose.dtd">

  <title>Description of Metabolite</title>
  <meta name="keywords" content="Metabolite">
  <meta name="description" content="Metabolite">
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="generator" content="m2html v1.5 © 2003-2005 Guillaume Flandin">
  <meta name="robots" content="index, follow">
  <link type="text/css" rel="stylesheet" href="../../../../../../../../m2html.css">

Home >  simulation > src > +edu > +stanford > +covert > +cell > +sim > +state > Metabolite.m

Metabolite

PURPOSE

Metabolite

SYNOPSIS

This is a script file.

DESCRIPTION

Metabolite

 Author: Jonathan Karr, jkarr@stanford.edu
 Affiliation: Covert Lab, Department of Bioengineering, Stanford University
 Last Updated: 1/5/2011

CROSS-REFERENCE INFORMATION

This function calls:

Metabolite	Metabolite

This function is called by:

Metabolite	Metabolite

SUBFUNCTIONS

function this = Metabolite(wholeCellModelID, name)

function initializeConstants(this, knowledgeBase, simulation)

function allocateMemory(this, numTimePoints)

function value = get.metabolismProduction(this)

function value = get.experimentalNMPComposition(this)

function value = get.experimentalAAComposition(this)

function value = get.nmpComposition(this)

function value = get.aaComposition(this)

function value = calcDryWeight(this)

function value = get.wetWeight(this)

SOURCE CODE

0001 %Metabolite
0002 %
0003 % Author: Jonathan Karr, jkarr@stanford.edu
0004 % Affiliation: Covert Lab, Department of Bioengineering, Stanford University
0005 % Last Updated: 1/5/2011
0006 classdef Metabolite < edu.stanford.covert.cell.sim.MoleculeCountState
0007     %Constants
0008     properties (Constant)
0009         optionNames             = {   %names of properties that are options
0010             'verbosity'
0011             'seed'
0012             };
0013         fixedConstantNames      = {   %names of process properties that are considered fixed constants
0014             'molecularWeights'
0015             'baseCounts'
0016             'lengths'
0017             'halfLives'
0018             'compartments'
0019             'meanNTPConcentration'
0020             'meanNDPConcentration'
0021             'meanNMPConcentration'
0022             };
0023         fittedConstantNames     = {   %names of process properties that are considered fitted constants, and should be stored with the simulation as such
0024             'biomassComposition'
0025             'biomassProduction'
0026             'byproducts'
0027             };
0028         stateNames              = {   %names of properties which are part of the simulation's state
0029             'counts'
0030             'processRequirements'
0031             'processAllocations'
0032             'processUsages'
0033             };
0034         dependentStateNames     = {}; %names of properties which can be calculated from the simulation's state
0035     end
0036
0037     %indices
0038     properties
0039         hydrophobicIndexs    %indices of hydrophobic counts
0040         aminoAcidIndexs      %amino acids indices within counts
0041         dnmpIndexs           %dAMP, dCMP, dGMP, dTMP indices within counts
0042         dndpIndexs           %dADP, dCDP, dGDP, dTDP indices within counts
0043         dntpIndexs           %dATP, dCTP, dGTP, dTTP indices within counts
0044         nmpIndexs            %AMP, CMP, GMP, UMP indices within counts
0045         ndpIndexs            %ADP, CDP, GDP, UDP indices within counts
0046         ntpIndexs            %ATP, CTP, GTP, UTP indices within counts
0047         ampIndexs            %AMP index within counts
0048         adpIndexs            %ADP index within counts
0049         atpIndexs            %ATP index within counts
0050         phosphateIndexs      %Pi index within counts
0051         diphosphateIndexs    %PPi index within counts
0052         waterIndexs          %H2O index within counts
0053         hydrogenIndexs       %H index within counts
0054         dr5pIndexs           %DR5P index within counts
0055         unmodifiedBaseIndexs %AD, CSN, GN, THY indices within counts
0056         m6ADIndexs           %m6AD index within counts
0057         lipidIndexs          %lipid indices within counts
0058         polyamineIndexs      %polyamine indices within counts
0059         carbohydrateIndexs   %carbohydrate indices within counts
0060         vitaminIndexs        %vitamin indices within counts
0061         ionIndexs            %ion indices within counts
0062         antibioticIndexs     %antibiotic indices within counts
0063     end
0064
0065     %constants
0066     properties
0067         setCounts                                     %experimentally set metabolic conditions (concentration, time when concentration is applied)
0068
0069         experimentalBiomassComposition                %experimentally observed biomass composition (molecules / cell)
0070         experimentalBiomassCompositionWeightFractions %experimentally observed biomass composition (weight fraction)
0071         experimentalBiomassCompositionMolFractions    %experimentally observed biomass composition (mol fraction)
0072         biomassComposition                            %metabolite composition of biomass (mollecules / cell) (metabolites X compartments)
0073         biomassProduction                             %biomass production
0074         byproducts                                    %expected energy and other byproducts of networks (ADP, AMP, PPi, Pi, H)
0075         processBiomassProduction                      %expected metabolic demand of each process
0076         processByproduct                              %expected metabolic byproducts produced by each process
0077
0078         meanNTPConcentration                          %mean ATP, GTP concentration (mM)
0079         meanNDPConcentration                          %mean ADP, GDP concentration (mM)
0080         meanNMPConcentration                          %mean AMP, CMP, GMP, UMP concentration (mM)
0081
0082         processWholeCellModelIDs                      %IDs of processes
0083     end
0084
0085     %constants
0086     properties (Dependent)
0087         metabolismProduction       %biomass production
0088
0089         experimentalNMPComposition %experimentally determined mol fractions of NMPs
0090         experimentalAAComposition  %experimentally determined mol fractions of AAs
0091
0092         nmpComposition             %mol fractions of NMPs
0093         aaComposition              %mol fractions of AAs
0094
0095         wetWeight                  %water weight (g)
0096     end
0097
0098     %state
0099     properties
0100         processRequirements        %instantaneous metabolic requirements of each process
0101         processAllocations         %instantaneous metabolites allocated to each process
0102         processUsages              %instantaneous metabolic usages of each process
0103     end
0104
0105     %constructor
0106     methods
0107         function this = Metabolite(wholeCellModelID, name)
0108             this = this@edu.stanford.covert.cell.sim.MoleculeCountState(wholeCellModelID, name);
0109         end
0110     end
0111
0112     methods
0113         function initializeConstants(this, knowledgeBase, simulation)
0114             import edu.stanford.covert.cell.sim.constant.Condition;
0115             import edu.stanford.covert.util.ConstantUtil;
0116
0117             this.initializeConstants@edu.stanford.covert.cell.sim.MoleculeCountState(knowledgeBase, simulation);
0118
0119             %ids, names, weights
0120             this.wholeCellModelIDs = {knowledgeBase.metabolites.wholeCellModelID}';
0121             this.names             = {knowledgeBase.metabolites.name}';
0122             this.molecularWeights  = [knowledgeBase.metabolites.molecularWeight]';
0123
0124             %indices
0125             this.hydrophobicIndexs    = find([knowledgeBase.metabolites.hydrophobic]);
0126             this.aminoAcidIndexs      = this.getIndexs({'ALA'; 'ARG'; 'ASN'; 'ASP'; 'CYS'; 'GLN'; 'GLU'; 'GLY'; 'HIS'; 'ILE'; 'LEU'; 'LYS'; 'MET'; 'PHE'; 'PRO'; 'SER'; 'THR'; 'TRP'; 'TYR'; 'VAL'; 'FMET'});
0127             this.dnmpIndexs           = this.getIndexs({'DAMP'; 'DCMP'; 'DGMP'; 'DTMP'});
0128             this.dndpIndexs           = this.getIndexs({'DADP'; 'DCDP'; 'DGDP'; 'DTDP'});
0129             this.dntpIndexs           = this.getIndexs({'DATP'; 'DCTP'; 'DGTP'; 'DTTP'});
0130             this.nmpIndexs            = this.getIndexs({'AMP';  'CMP';  'GMP';  'UMP'});
0131             this.ndpIndexs            = this.getIndexs({'ADP';  'CDP';  'GDP';  'UDP'});
0132             this.ntpIndexs            = this.getIndexs({'ATP';  'CTP';  'GTP';  'UTP'});
0133             this.ampIndexs            = this.getIndexs({'AMP'});
0134             this.adpIndexs            = this.getIndexs({'ADP'});
0135             this.atpIndexs            = this.getIndexs({'ATP'});
0136             this.phosphateIndexs      = this.getIndexs({'PI'});
0137             this.diphosphateIndexs    = this.getIndexs({'PPI'});
0138             this.waterIndexs          = this.getIndexs({'H2O'});
0139             this.hydrogenIndexs       = this.getIndexs({'H'});
0140             this.dr5pIndexs           = this.getIndexs({'DR5P'});
0141             this.unmodifiedBaseIndexs = this.getIndexs({'AD'; 'CSN'; 'GN'; 'THY'});
0142             this.m6ADIndexs           = this.getIndexs({'m6AD'});
0143             this.lipidIndexs          = find(strcmp({knowledgeBase.metabolites.category}', 'lipid'));
0144             this.polyamineIndexs      = find(strcmp({knowledgeBase.metabolites.category}', 'polyamine'));
0145             this.carbohydrateIndexs   = find(strcmp({knowledgeBase.metabolites.category}', 'carbohydrate'));
0146             this.vitaminIndexs        = find(strcmp({knowledgeBase.metabolites.category}', 'vitamin'));
0147             this.ionIndexs            = find(strcmp({knowledgeBase.metabolites.category}', 'ion'));
0148             this.antibioticIndexs     = find(strcmp({knowledgeBase.metabolites.category}', 'antibiotic'));
0149
0150             %media
0151             this.setCounts = zeros(0, 6);
0152             for i = 1:knowledgeBase.numMetabolites
0153                 if isempty(knowledgeBase.metabolites(i).mediaCompartments); continue; end;
0154
0155                 value = zeros(length(knowledgeBase.metabolites(i).mediaCompartments), 6);
0156                 value(:, Condition.objectIndexs)      = knowledgeBase.metabolites(i).idx;
0157                 value(:, Condition.compartmentIndexs) = [knowledgeBase.metabolites(i).mediaCompartments.idx];
0158                 value(:, Condition.valueIndexs)       = knowledgeBase.metabolites(i).mediaConcentrations;
0159                 value(:, Condition.initialTimeIndexs) = knowledgeBase.metabolites(i).mediaInitialTimes;
0160                 value(:, Condition.finalTimeIndexs)   = knowledgeBase.metabolites(i).mediaFinalTimes;
0161                 value(:, Condition.objectCompartmentIndexs) = sub2ind([knowledgeBase.numMetabolites knowledgeBase.numCompartments],...
0162                     value(:, Condition.objectIndexs),...
0163                     value(:, Condition.compartmentIndexs));
0164
0165                 this.setCounts = [this.setCounts; value];
0166             end
0167
0168             this.setCounts(:, Condition.valueIndexs) = round(...
0169                 this.setCounts(:, Condition.valueIndexs) * ...
0170                 edu.stanford.covert.util.ConstantUtil.nAvogadro / 1000 * simulation.state('Geometry').chamberVolume);
0171
0172             %biomass
0173             this.experimentalBiomassComposition = -knowledgeBase.biomassComposition;
0174             this.experimentalBiomassCompositionMolFractions = sum(this.experimentalBiomassComposition, 2) / sum(this.experimentalBiomassComposition(:));
0175             this.experimentalBiomassCompositionWeightFractions = ...
0176                 sum(this.experimentalBiomassCompositionMolFractions, 2) .* this.molecularWeights / ...
0177                 (sum(this.experimentalBiomassCompositionMolFractions, 2)' * this.molecularWeights);
0178
0179             %processes
0180             this.processWholeCellModelIDs = {knowledgeBase.processes.wholeCellModelID}';
0181         end
0182
0183         function allocateMemory(this, numTimePoints)
0184             import edu.stanford.covert.util.SparseMat;
0185
0186             this.allocateMemory@edu.stanford.covert.cell.sim.MoleculeCountState(numTimePoints);
0187
0188             nProcesses = numel(this.processWholeCellModelIDs);
0189             this.processRequirements = SparseMat([], [], [numel(this.wholeCellModelIDs) * this.compartment.count  nProcesses  numTimePoints]);
0190             this.processAllocations = SparseMat([], [], [numel(this.wholeCellModelIDs) * this.compartment.count  nProcesses  numTimePoints]);
0191             this.processUsages = SparseMat([], [], [numel(this.wholeCellModelIDs) * this.compartment.count  nProcesses  numTimePoints]);
0192         end
0193     end
0194
0195     %getters
0196     methods
0197         function value = get.metabolismProduction(this)
0198             value = this.biomassProduction - this.byproducts;
0199         end
0200
0201         %experimental composition
0202         function value = get.experimentalNMPComposition(this)
0203             value = this.experimentalBiomassCompositionMolFractions(this.nmpIndexs);
0204             value = value / sum(value);
0205         end
0206
0207         function value = get.experimentalAAComposition(this)
0208             value = this.experimentalBiomassCompositionMolFractions(this.aminoAcidIndexs);
0209             value = value / sum(value);
0210         end
0211
0212         %composition
0213         function value = get.nmpComposition(this)
0214             value = this.biomassComposition(this.nmpIndexs, :);
0215             value = value / sum(value(:));
0216         end
0217
0218         function value = get.aaComposition(this)
0219             value = sum(this.biomassComposition(this.aminoAcidIndexs, :), 2);
0220             value = value / sum(value(:));
0221         end
0222
0223         %weight
0224         function value = calcDryWeight(this)
0225             if size(this.counts, 3) == 1
0226                 value = this.molecularWeights' * this.counts;
0227             else
0228                 value = multiprod(this.molecularWeights', this.counts, [1 2], [1 2]);
0229             end
0230             value = ...
0231                 + value / edu.stanford.covert.util.ConstantUtil.nAvogadro ...
0232                 - this.wetWeight;
0233         end
0234
0235         function value = get.wetWeight(this)
0236             value = this.counts(this.waterIndexs, :, :) * this.molecularWeights(this.waterIndexs) / edu.stanford.covert.util.ConstantUtil.nAvogadro;
0237         end
0238     end
0239 end

<address>Generated on Thu 19-Jul-2012 18:32:13 by m2html © 2005</address>


text:
<?php

namespace Spore\HttpFoundation\Tests\Units;

require_once __DIR__ . '/../../../vendor/autoload.php';

use Spore;

class Request extends Spore\Test\Unit
{
    public function testClass()
    {
        $request = new \Spore\HttpFoundation\Request();

        $this->assert->object($request)
            ->isInstanceOf('\Spore\HttpFoundation\Request');

        $request->setUri('http://username:passwd@www.google.com:8080/search?q=test');

        $this->assert->string($request->getUri())
            ->isEqualTo('http://username:passwd@www.google.com:8080/search?q=test');

        $request->setUri('http://username:passwd@www.google.com:80/search?q=test');

        $this->assert->string($request->getUri())
            ->isEqualTo('http://username:passwd@www.google.com/search?q=test');

        $request->setMethod('GET');

        $this->assert->exception(function() use ($request) {
            $request->setMethod('FOOT');
        })
        ->isInstanceOf('\InvalidArgumentException');

        $this->assert->string($request->getPath())
            ->isEqualTo('/search');

        $this->assert->string($request->getScheme())
            ->isEqualTo('http');

        $this->assert->string($request->getHost())
            ->isEqualTo('www.google.com');

        $this->assert->integer($request->getPort())
            ->isEqualTo(80);

        $request->setPort(8080);

        $this->assert->integer($request->getPort())
            ->isEqualTo(8080);

        $this->assert->string($request->getMethod())
            ->isEqualTo('GET');

        $this->assert->boolean($request->isGet())
            ->isTrue();

        $this->assert->boolean($request->isPost())
            ->isFalse();

        $this->assert->boolean($request->isDelete())
            ->isFalse();

        $this->assert->boolean($request->isPatch())
            ->isFalse();

        $this->assert->boolean($request->isOptions())
            ->isFalse();

        $this->assert->boolean($request->isTrace())
            ->isFalse();

        $this->assert->boolean($request->isConnect())
            ->isFalse();

        $this->assert->boolean($request->isPut())
            ->isFalse();

        $this->assert->boolean($request->isHead())
            ->isFalse();

        $this->assert->string($request->getUser())
            ->isEqualTo('username');

        $this->assert->string($request->getPassword())
            ->isEqualTo('passwd');

        $request->setUser('username1');

        $this->assert->string($request->getUser())
            ->isEqualTo('username1');

        $request->setPassword('passwd2');

        $this->assert->string($request->getPassword())
            ->isEqualTo('passwd2');

        $this->assert->boolean($request->isAuth())
            ->isTrue();

        $request = new \Spore\HttpFoundation\Request('http://www.google.com/search?q=test');

        $request->setQuery('q=toto&hl=fr');

        $this->assert->object($request->getQuery())
            ->isInstanceOf('\Symfony\Component\HttpFoundation\ParameterBag');

        $this->assert->array($request->getQuery()->all())
            ->isEqualTo(array(
                'q' => 'toto',
                'hl' => 'fr'
            ));

        $request->setQuery(array(
            'foot' => 'bar'
        ));

        $this->assert->array($request->getQuery()->all())
            ->isEqualTo(array(
                'q' => 'toto',
                'hl' => 'fr',
                'foot' => 'bar'
            ));

        $this->assert->exception(function() use ($request) {
            $request->setQuery(1);
        })
        ->isInstanceOf('\InvalidArgumentException');

        $request = new \Spore\HttpFoundation\Request();

        $this->assert->object($request->getQuery())
            ->isInstanceOf('\Symfony\Component\HttpFoundation\ParameterBag');

        $request->setData('test');

        $this->assert->string($request->getData())
            ->isEqualTo('test');
    }
}


text:
/**
 * DEVELOPMENT WEBPACK CONFIGURATION
 */

/* eslint-disable import/no-extraneous-dependencies */
const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const CircularDependencyPlugin = require('circular-dependency-plugin');
const logger = require('../../server/logger');
const pkg = require('../../package.json');
const dllPlugin = pkg.dllPlugin;
/* eslint-enable import/no-extraneous-dependencies */

const plugins = [
  new webpack.HotModuleReplacementPlugin(),
  new webpack.NoEmitOnErrorsPlugin(),
  new CircularDependencyPlugin({
    exclude: /a\.js|node_modules/,
    // show a warning when there is a circular dependency
    failOnError: false,
  }),
];

module.exports = require('./webpack.base.babel')({
  // Add hot reloading in development
  entry: {
    main: [
      'babel-polyfill',
      'eventsource-polyfill',
      'react-hot-loader/patch',
      'webpack-hot-middleware/client',
      path.join(process.cwd(), 'app/main.js'),
    ],
  },

  // Don't use hashes in dev mode for better performance
  output: {
    filename: '[name].js',
    chunkFilename: '[name].chunk.js',
  },

  // Add development plugins
  plugins: dependencyHandlers().concat(plugins), // eslint-disable-line no-use-before-define

  // Tell babel that we want to hot-reload
  babelQuery: {
    // require.resolve solves the issue of relative presets when dealing with
    // locally linked packages. This is an issue with babel and webpack.
    // See https://github.com/babel/babel-loader/issues/149 and
    // https://github.com/webpack/webpack/issues/1866
    presets: ['babel-preset-react-hmre'].map(require.resolve),
  },

  // Emit a source map for easier debugging
  devtool: 'cheap-module-eval-source-map',

  performance: {
    hints: false,
  },
});

/**
 * Select which plugins to use to optimize the bundle's handling of
 * third party dependencies.
 *
 * If there is a dllPlugin key on the project's package.json, the
 * Webpack DLL Plugin will be used.  Otherwise the CommonsChunkPlugin
 * will be used.
 *
 */
function dependencyHandlers() {
  // Don't do anything during the DLL Build step
  if (process.env.BUILDING_DLL) { return []; }

  // If the package.json does not have a dllPlugin property, use the CommonsChunkPlugin
  if (!dllPlugin) {
    return [
      new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor',
        children: true,
        minChunks: 2,
        async: true,
      }),
    ];
  }

  const dllPath = path.resolve(process.cwd(), dllPlugin.path || 'node_modules/react-boilerplate-dlls');

  /**
   * If DLLs aren't explicitly defined, we assume all production dependencies listed in package.json
   * Reminder: You need to exclude any server side dependencies by listing them in dllConfig.exclude
   */
  if (!dllPlugin.dlls) {
    const manifestPath = path.resolve(dllPath, 'reactBoilerplateDeps.json');

    if (!fs.existsSync(manifestPath)) {
      logger.error('The DLL manifest is missing. Please run `npm run build:dll`');
      process.exit(0);
    }

    return [
      new webpack.DllReferencePlugin({
        context: process.cwd(),
        manifest: require(manifestPath), // eslint-disable-line global-require, import/no-dynamic-require
      }),
    ];
  }

  // If DLLs are explicitly defined, we automatically create a DLLReferencePlugin for each of them.
  const dllManifests = Object.keys(dllPlugin.dlls).map((name) => path.join(dllPath, `/${name}.json`));

  return dllManifests.map((manifestPath) => {
    if (!fs.existsSync(path)) {
      if (!fs.existsSync(manifestPath)) {
        logger.error(`The following Webpack DLL manifest is missing: ${path.basename(manifestPath)}`);
        logger.error(`Expected to find it in ${dllPath}`);
        logger.error('Please run: npm run build:dll');

        process.exit(0);
      }
    }

    return new webpack.DllReferencePlugin({
      context: process.cwd(),
      manifest: require(manifestPath), // eslint-disable-line global-require, import/no-dynamic-require
    });
  });
}


text:
import unittest

from pythonosc import dispatcher

class TestDispatcher(unittest.TestCase):

  def setUp(self):
    super().setUp()
    self.dispatcher = dispatcher.Dispatcher()

  def sortAndAssertSequenceEqual(self, expected, result):
    return self.assertSequenceEqual(sorted(expected), sorted(result))

  def test_empty_by_default(self):
    self.sortAndAssertSequenceEqual([], self.dispatcher.handlers_for_address('/test'))

  def test_use_default_handler_when_set_and_no_match(self):
    handler = object()
    self.dispatcher.set_default_handler(handler)

    self.sortAndAssertSequenceEqual([dispatcher.Handler(handler, [])], self.dispatcher.handlers_for_address('/test'))

  def test_simple_map_and_match(self):
    handler = object()
    self.dispatcher.map('/test', handler, 1, 2, 3)
    self.dispatcher.map('/test2', handler)
    self.sortAndAssertSequenceEqual(
        [dispatcher.Handler(handler, [1, 2, 3])], self.dispatcher.handlers_for_address('/test'))
    self.sortAndAssertSequenceEqual(
        [dispatcher.Handler(handler, [])], self.dispatcher.handlers_for_address('/test2'))

  def test_example_from_spec(self):
    addresses = [
        "/first/this/one",
        "/second/1",
        "/second/2",
        "/third/a",
        "/third/b",
        "/third/c",
    ]
    for index, address in enumerate(addresses):
      self.dispatcher.map(address, index)

    for index, address in enumerate(addresses):
      self.sortAndAssertSequenceEqual(
          [(index, [])], self.dispatcher.handlers_for_address(address))

    self.sortAndAssertSequenceEqual(
        [(1, []), (2, [])], self.dispatcher.handlers_for_address("/second/?"))

    self.sortAndAssertSequenceEqual(
        [(3, []), (4, []), (5, [])],
        self.dispatcher.handlers_for_address("/third/*"))

  def test_do_not_match_over_slash(self):
    self.dispatcher.map('/foo/bar/1', 1)
    self.dispatcher.map('/foo/bar/2', 2)

    self.sortAndAssertSequenceEqual(
        [], self.dispatcher.handlers_for_address("/*"))

  def test_match_middle_star(self):
    self.dispatcher.map('/foo/bar/1', 1)
    self.dispatcher.map('/foo/bar/2', 2)

    self.sortAndAssertSequenceEqual(
        [(2, [])], self.dispatcher.handlers_for_address("/foo/*/2"))

  def test_match_multiple_stars(self):
    self.dispatcher.map('/foo/bar/1', 1)
    self.dispatcher.map('/foo/bar/2', 2)

    self.sortAndAssertSequenceEqual(
        [(1, []), (2, [])], self.dispatcher.handlers_for_address("/*/*/*"))

  def test_match_address_contains_plus_as_character(self):
    self.dispatcher.map('/footest/bar+tender/1', 1)

    self.sortAndAssertSequenceEqual(
        [(1, [])], self.dispatcher.handlers_for_address("/foo*/bar+*/*"))
    self.sortAndAssertSequenceEqual(
        [(1, [])], self.dispatcher.handlers_for_address("/foo*/bar*/*"))

  def test_call_correct_dispatcher_on_star(self):
    self.dispatcher.map('/a+b', 1)
    self.dispatcher.map('/aaab', 2)
    self.sortAndAssertSequenceEqual(
        [(2, [])], self.dispatcher.handlers_for_address('/aaab'))
    self.sortAndAssertSequenceEqual(
        [(1, [])], self.dispatcher.handlers_for_address('/a+b'))

  def test_map_star(self):
    self.dispatcher.map('/starbase/*', 1)
    self.sortAndAssertSequenceEqual(
        [(1, [])], self.dispatcher.handlers_for_address("/starbase/bar"))

  def test_map_root_star(self):
    self.dispatcher.map('/*', 1)
    self.sortAndAssertSequenceEqual(
        [(1, [])], self.dispatcher.handlers_for_address("/anything/matches"))

  def test_map_double_stars(self):
    self.dispatcher.map('/foo/*/bar/*', 1)
    self.sortAndAssertSequenceEqual(
        [(1, [])], self.dispatcher.handlers_for_address("/foo/wild/bar/wild"))
    self.sortAndAssertSequenceEqual(
        [], self.dispatcher.handlers_for_address("/foo/wild/nomatch/wild"))

  def test_multiple_handlers(self):
    self.dispatcher.map('/foo/bar', 1)
    self.dispatcher.map('/foo/bar', 2)
    self.sortAndAssertSequenceEqual(
        [dispatcher.Handler(1, []), dispatcher.Handler(2, [])], self.dispatcher.handlers_for_address("/foo/bar"))

  def test_multiple_handlers_with_wildcard_map(self):
    self.dispatcher.map('/foo/bar', 1)
    self.dispatcher.map('/*', 2)
    self.sortAndAssertSequenceEqual(
        [dispatcher.Handler(1, []), dispatcher.Handler(2, [])], self.dispatcher.handlers_for_address("/foo/bar"))

if __name__ == "__main__":
  unittest.main()


text:
yahoo-finance-tools
===================

1. access to [Toyota Yahoo Finance][http://finance.yahoo.com/q/cf?s=TM&annual]
2. javascript console open.
3. fs.js copy all and paste to javascript console.
4. call is getData(), getHeadLine(), getSummary()


text:
<!DOCTYPE html>

    {% load static %}
    <meta charset="UTF-8">
    <title>Certificates</title>

    {% include 'nav.html' %}

        下载根证书 Download Root Certificate

You can make https safe by importing root certificate

        下载服务器证书 Download Server Certificate


text: package go_fasthttp


text:
$:.unshift(File.dirname(__FILE__))

require 'active_record'

require 'core_ext/module'

require 'rails_sql_views/connection_adapters/abstract/schema_definitions'
require 'rails_sql_views/connection_adapters/abstract/schema_statements'
require 'rails_sql_views/connection_adapters/abstract_adapter'
require 'rails_sql_views/schema_dumper'
require 'rails_sql_views/loader'

ActiveRecord::ConnectionAdapters::AbstractAdapter.class_eval do
  include RailsSqlViews::ConnectionAdapters::SchemaStatements
  def self.inherited(sub)
    RailsSqlViews::Loader.load_extensions
  end
end

ActiveRecord::SchemaDumper.class_eval do
  include RailsSqlViews::SchemaDumper
end

RailsSqlViews::Loader.load_extensions


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System.Collections.Generic;
using osu.Framework.Localisation;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Resources.Localisation.Web;

namespace osu.Game.Overlays.Dashboard.Home
{
    public class DrawableNewBeatmapList : DrawableBeatmapList
    {
        public DrawableNewBeatmapList(List<APIBeatmapSet> beatmapSets)
            : base(beatmapSets)
        {
        }

        protected override DashboardBeatmapPanel CreateBeatmapPanel(APIBeatmapSet beatmapSet) => new DashboardNewBeatmapPanel(beatmapSet);

        protected override LocalisableString Title => HomeStrings.UserBeatmapsNew;
    }
}


text:
/**
 * @file  选择器
 * @author  Firede[firede@firede.us]
 */

define(function () {

    var exports = {};

    /**
     * 根据id获取指定的DOM元素
     *
     * @public
     * @param {string|HTMLElement} id 元素的id或DOM元素
     * @return {HTMLElement|null} 获取的元素,找不到时返回null
     */
    exports.g = function (id) {
        if (!id) {
            return null;
        }

        return typeof id === 'string' ? document.getElementById(id) : id;
    };

    /**
     * 根据选择器获取指定DOM元素
     *
     * @public
     * @param {string} selector 元素的selector
     * @param {HTMLElement=} context 上下文
     * @return {HTMLElement|null} 获取的元素,找不到时返回null
     */
    exports.query = function (selector, context) {
        if ('string' !== typeof selector) {
            return selector;
        }

        context = context || document.body;

        return context.querySelector(selector);
    };

    /**
     * 根据选择器选择DOM元素列表
     *
     * @public
     * @param {string} selector 元素的selector
     * @param {HTMLElement=} context 上下文
     * @return {Array} 获取的元素列表,找不到时为空数组
     */
    exports.queryAll = function (selector, context) {
        if (Array.isArray(selector)) {
            return selector;
        }

        context = context || document.body;

        var nodeList = context.querySelectorAll(selector);

        return Array.prototype.slice.call(nodeList);
    };

    /**
     * 判断DOM元素与选择器是否匹配
     *
     * @param {HTMLElement} element 目标DOM元素
     * @param {string} selector 待判断的selector
     * @return {boolean} 是否匹配
     */
    exports.matches = function (element, selector) {
        var proto = Element.prototype;
        var matches = proto.matches
            || proto.webkitMatchesSelector
            || proto.mozMatchesSelector
            || proto.msMatchesSelector;

        if (matches) {
            return matches.call(element, selector);
        }

        var elements = exports.queryAll(selector, element.parentNode);
        for (var i = 0; i < elements.length; i++) {
            if (elements[i] === element) {
                return true;
            }
        }
        return false;
    };

    return exports;

});


text:
$(function(){
//Вываливающийся список из-под черной стрелки
	$(".black_arrow").on("mouseenter", function(){
		$(this).find(".nav_show").stop(0).slideDown();
		}).on("mouseleave",function(){
		$(this).find(".nav_show").stop(0).slideUp();
		});

//Вываливающийся список из-под серой стрелки
	$(".small_arrow_menu").on("mouseenter", function(){
		$(this).find(".showCurrency").stop(0).slideDown();
		}).on("mouseleave",function(){
		$(this).find(".showCurrency").stop(0).slideUp();
		});

//Выдвигающееся меню поиска
	$(".search").on("click",function(){
		if(!$(this).hasClass("block_")){
			$(".header-2").find(".inputSearch").show();
			$(this).toggleClass("block_");
		} else{
			$(".header-2").find(".inputSearch").hide();
			$(this).toggleClass("block_");
		};
	});
});


text:
package app.domain.dtos.workshops;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Set;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "workshop")
@XmlAccessorType(XmlAccessType.FIELD)
public class WorkshopXmlDto {

	@XmlAttribute(name = "name")
	private String name;

	@XmlAttribute(name = "start-date")
	private Date startDate;

	@XmlAttribute(name = "end-date")
	private Date endDate;

	@XmlAttribute(name = "location")
	private String location;

	@XmlAttribute(name = "price")
	private BigDecimal pricePerParticipant;

	@XmlElement(name = "trainer")
	private String trainerFullName;

	@XmlElementWrapper(name = "participants")
	@XmlElement(name = "participant")
	private Set<ParticipantXmlDto> participants;

	public WorkshopXmlDto() {
		super();
	}

	public String getName() {
		return name;
	}

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

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	public BigDecimal getPricePerParticipant() {
		return pricePerParticipant;
	}

	public void setPricePerParticipant(BigDecimal pricePerParticipant) {
		this.pricePerParticipant = pricePerParticipant;
	}

	public String getTrainerFullName() {
		return trainerFullName;
	}

	public void setTrainerFullName(String trainerFullName) {
		this.trainerFullName = trainerFullName;
	}

	public Set<ParticipantXmlDto> getParticipants() {
		return participants;
	}

	public void setParticipants(Set<ParticipantXmlDto> participants) {
		this.participants = participants;
	}

}


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

namespace Login.Api.Infrastructure.Configuration
{
    public class JwtConfiguration
    {
        public JwtConfiguration()
        {}

        public string TokenSecret { get; set; }
        public string CookieName { get; set; }
        public string CookieDomain { get; set; }
        public string CookiePath { get; set; }
        public int CookieExpiryDays { get; set; }
    }
}


text:
"""SCons.Tool.CVS.py

Tool-specific initialization for CVS.

There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.

"""

# Copyright (c) 2001 - 2014 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

__revision__ = "src/engine/SCons/Tool/CVS.py  2014/08/24 12:12:31 garyo"

import SCons.Action
import SCons.Builder
import SCons.Util

def generate(env):
    """Add a Builder factory function and construction variables for
    CVS to an Environment."""

    def CVSFactory(repos, module='', env=env):
        """ """
        import SCons.Warnings as W
        W.warn(W.DeprecatedSourceCodeWarning, """The CVS() factory is deprecated and there is no replacement.""")
        # fail if repos is not an absolute path name?
        if module != '':
           # Don't use os.path.join() because the name we fetch might
           # be across a network and must use POSIX slashes as separators.
           module = module + '/'
           env['CVSCOM']   = '$CVS $CVSFLAGS co $CVSCOFLAGS -d ${TARGET.dir} $CVSMODULE${TARGET.posix}'
        act = SCons.Action.Action('$CVSCOM', '$CVSCOMSTR')
        return SCons.Builder.Builder(action = act,
                                     env = env,
                                     CVSREPOSITORY = repos,
                                     CVSMODULE = module)

    #setattr(env, 'CVS', CVSFactory)
    env.CVS = CVSFactory

    env['CVS']        = 'cvs'
    env['CVSFLAGS']   = SCons.Util.CLVar('-d $CVSREPOSITORY')
    env['CVSCOFLAGS'] = SCons.Util.CLVar('')
    env['CVSCOM']     = '$CVS $CVSFLAGS co $CVSCOFLAGS ${TARGET.posix}'

def exists(env):
    return env.Detect('cvs')

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:


text:
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __EEPROM_H
#define __EEPROM_H

/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_conf.h"

/* Exported constants --------------------------------------------------------*/
/* Define the size of the sectors to be used */
#define PAGE_SIZE               (uint32_t)0x4000  /* Page size = 16KByte */

/* Device voltage range supposed to be [2.7V to 3.6V], the operation will
   be done by word  */
#define VOLTAGE_RANGE           (uint8_t)VoltageRange_3

/* EEPROM start address in Flash */
#define EEPROM_START_ADDRESS  ((uint32_t)0x08004000) /* EEPROM emulation start address:
                                                  from sector1 : after 16KByte of used
                                                  Flash memory */

/* Pages 0 and 1 base and end addresses */
#define PAGE0_BASE_ADDRESS    ((uint32_t)(EEPROM_START_ADDRESS + 0x0000))
#define PAGE0_END_ADDRESS     ((uint32_t)(EEPROM_START_ADDRESS + (PAGE_SIZE - 1)))
#define PAGE0_ID              FLASH_Sector_1

#define PAGE1_BASE_ADDRESS    ((uint32_t)(EEPROM_START_ADDRESS + 0x4000))
#define PAGE1_END_ADDRESS     ((uint32_t)(EEPROM_START_ADDRESS + (2 * PAGE_SIZE - 1)))
#define PAGE1_ID              FLASH_Sector_2

/* Used Flash pages for EEPROM emulation */
#define PAGE0                 ((uint16_t)0x0000)
#define PAGE1                 ((uint16_t)0x0001)

/* No valid page define */
#define NO_VALID_PAGE         ((uint16_t)0x00AB)

/* Page status definitions */
#define ERASED                ((uint16_t)0xFFFF)     /* Page is empty */
#define RECEIVE_DATA          ((uint16_t)0xEEEE)     /* Page is marked to receive data */
#define VALID_PAGE            ((uint16_t)0x0000)     /* Page containing valid data */

/* Valid pages in read and write defines */
#define READ_FROM_VALID_PAGE  ((uint8_t)0x00)
#define WRITE_IN_VALID_PAGE   ((uint8_t)0x01)

/* Page full define */
#define PAGE_FULL             ((uint8_t)0x80)

/* Variables' number */
#define NB_OF_VAR             ((uint8_t)160)

/* Exported types ------------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
uint16_t EE_Init(void);
uint16_t EE_ReadVariable(uint16_t VirtAddress, uint16_t* Data);
uint16_t EE_WriteVariable(uint16_t VirtAddress, uint16_t Data);

#endif /* __EEPROM_H */

/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/


text:
package eu.eumssi.uima.pipeline.test;

import static org.apache.uima.fit.factory.AnalysisEngineFactory.createEngineDescription;
import static org.apache.uima.fit.factory.CollectionReaderFactory.createReaderDescription;
import static org.apache.uima.fit.util.JCasUtil.select;
import static org.apache.uima.fit.util.JCasUtil.selectCovered;
import static org.apache.uima.fit.util.JCasUtil.selectSingle;

import java.util.logging.Logger;

import org.apache.uima.analysis_engine.AnalysisEngineDescription;
import org.apache.uima.collection.CollectionReaderDescription;
import org.apache.uima.fit.pipeline.JCasIterable;
import org.apache.uima.jcas.JCas;
import org.dbpedia.spotlight.uima.SpotlightAnnotator;
import org.dbpedia.spotlight.uima.types.DBpediaResource;
import org.dbpedia.spotlight.uima.types.TopDBpediaResource;

import com.iai.uima.analysis_component.KeyPhraseAnnotator;

import de.tudarmstadt.ukp.dkpro.core.api.ner.type.NamedEntity;
import de.tudarmstadt.ukp.dkpro.core.io.xmi.XmiWriter;
import de.tudarmstadt.ukp.dkpro.core.languagetool.LanguageToolSegmenter;
import de.tudarmstadt.ukp.dkpro.core.stanfordnlp.StanfordNamedEntityRecognizer;
import eu.eumssi.uima.consumer.OcrNerlConsumer;
import eu.eumssi.uima.reader.OcrReader;
import eu.eumssi.uima.ts.OcrSegment;
import eu.eumssi.uima.ts.SourceMeta;
import eu.eumssi.uima.ts.TopOcrSegment;

/**
 * In this pipeline, we use dbpedia-spotlight to annotate entities.
 * It is configured to use the public endpoint, but should preferably point to a local one.
 */
public class OcrTest
{
	public static void main(String[] args) throws Exception
	{

		Logger logger = Logger.getLogger(OcrTest.class.toString());

		String mongoDb = "eumssi_db";
		String mongoCollection = "content_items";
		//String mongoUri = "mongodb://localhost:1234"; // through ssh tunnel
		String mongoUri = "mongodb://localhost:27017"; // default (local)

		CollectionReaderDescription reader = createReaderDescription(OcrReader.class,
				OcrReader.PARAM_MAXITEMS,10000,
				OcrReader.PARAM_MONGOURI, mongoUri,
				OcrReader.PARAM_MONGODB, mongoDb,
				OcrReader.PARAM_MONGOCOLLECTION, mongoCollection,
				OcrReader.PARAM_FIELDS, "processing.results.video_ocr",
				//				OcrReader.PARAM_QUERY,"{'meta.source.inLanguage':'en',"
				//						+ "'processing.available_data': 'video_ocr',"
				//						+ "'processing.available_data': {'$ne': 'text_ocr-nerl'}}",
				OcrReader.PARAM_QUERY,"{'meta.source.inLanguage':'en',"
				 		+ "'processing.available_data': 'video_ocr'}", // reprocess everything
				OcrReader.PARAM_LANG,"{'$literal':'en'}",
				OcrReader.PARAM_ONLYBEST,false,
				OcrReader.PARAM_VERTICALLY_ALIGNED,false
				);

		// make sure sentences are limited to individual OCR hypotheses
		AnalysisEngineDescription segmenter = createEngineDescription(LanguageToolSegmenter.class,
				LanguageToolSegmenter.PARAM_ZONE_TYPES, OcrSegment.class.getCanonicalName());

		AnalysisEngineDescription dbpedia = createEngineDescription(SpotlightAnnotator.class,
				SpotlightAnnotator.PARAM_ENDPOINT, "http://localhost:2222/rest",
				SpotlightAnnotator.PARAM_CONFIDENCE, 0.6f,
				SpotlightAnnotator.PARAM_ALL_CANDIDATES, false);

		AnalysisEngineDescription key = createEngineDescription(KeyPhraseAnnotator.class,
				KeyPhraseAnnotator.PARAM_LANGUAGE, "en",
				KeyPhraseAnnotator.PARAM_KEYPHRASE_RATIO, 10);

		AnalysisEngineDescription ner = createEngineDescription(StanfordNamedEntityRecognizer.class);

		AnalysisEngineDescription xmiWriter = createEngineDescription(XmiWriter.class,
				XmiWriter.PARAM_TARGET_LOCATION, "output",
				XmiWriter.PARAM_TYPE_SYSTEM_FILE, "output/TypeSystem.xml");

		JCasIterable pipeline = new JCasIterable(
				reader,
				segmenter,
				dbpedia,
				//key,
				ner,
				xmiWriter
				);

		// Run and show results in console
		for (JCas jcas : pipeline) {
			SourceMeta meta = selectSingle(jcas, SourceMeta.class);
			System.out.println("\n\n=========\n\n" + meta.getDocumentId() + ":\n" + jcas.getDocumentText() + "\n");
			for (OcrSegment ocrSegment : select(jcas, TopOcrSegment.class)) {
				logger.info(String.format("  %-16s\t%-16s\t%-10d\t%-10d\t%-10d\t%-10d\t\n",
						ocrSegment.getCoveredText(),
						ocrSegment.getText(),
						ocrSegment.getBeginTime(),
						ocrSegment.getEndTime(),
						ocrSegment.getBegin(),
						ocrSegment.getEnd()
						));
				for (DBpediaResource resource : selectCovered(TopDBpediaResource.class, ocrSegment)) {
					logger.info(String.format("  %-16s\t%-10s\t%-10s%n",
							resource.getCoveredText(),
							resource.getUri(),
							resource.getTypes()
							));
				}
				for (NamedEntity entity : selectCovered(jcas, NamedEntity.class, ocrSegment)) {
					logger.info(String.format("  %-16s %-10s %n",
							entity.getCoveredText(),
							entity.getValue()));
				}
			}
			logger.info("=== everything ===");
			for (NamedEntity entity : select(jcas, NamedEntity.class)) {
				logger.info(String.format("  %-16s %-10s %n",
						entity.getCoveredText(),
						entity.getValue()));
			}

		}
	}
}


text:
\courseTemplate[
code = {MATH2010},
title = {Analysis of Ordinary Differential Equations},
score = 4,
prereq = {MATH1052},
contact = {2L},
coordinator = {Prof Mark Gould (m.gould1@uq.edu.au)},
assessment = {
example & example\% & example \\
},
review = {
    review here
},
preparation = {
    \item thingo
}]{}


text:
module DC

  # Mapping of document statuses to integers, for efficient storage/querying.
  module DocumentStatus

    STATUS_NEW = 1
    STATUS_DE1 = 2
    STATUS_DE2 = 3
    STATUS_READY_QC = 4
    STATUS_IN_QC = 5
    STATUS_READY_QA = 6
    STATUS_IN_QA = 7
    STATUS_READY_EXT = 8
    STATUS_READY_SUPP_DE = 9
    STATUS_IN_SUPP_DE = 10
    STATUS_READY_SUPP_QC = 11
    STATUS_IN_SUPP_QC = 12
    STATUS_READY_SUPP_QA = 13
    STATUS_IN_SUPP_QA = 14

    STATUS_MAP = {
        :status_new       => STATUS_NEW,
        :status_de1       => STATUS_DE1,
        :status_de2       => STATUS_DE2,
        :status_ready_qc  => STATUS_READY_QC,
        :status_in_qc     => STATUS_IN_QC,
        :status_ready_qa  => STATUS_READY_QA,
        :status_in_qa     => STATUS_IN_QA,
        :status_ready_ext => STATUS_READY_EXT,
        :status_ready_supp_de   => STATUS_READY_SUPP_DE,
        :status_in_supp_de      => STATUS_IN_SUPP_DE,
        :status_ready_supp_qc   => STATUS_READY_SUPP_QC,
        :status_in_supp_qc      => STATUS_IN_SUPP_QC,
        :status_ready_supp_qa   => STATUS_READY_SUPP_QA,
        :status_in_supp_qa      => STATUS_IN_SUPP_QA
    }

    STATUS_TEXT = {
      'New'                         => 1,
      'In Data Entry (1 Claim)'     => 2,
      'In Data Entry (2 Claims)'    => 3,
      'Ready for Quality Control'   => 4,
      'In Quality Control'          => 5,
      'Ready for Quality Assurance' => 6,
      'In Quality Assurance'        => 7,
      'Ready for Extraction'        => 8,
      'Ready for Supplemental Data Entry' => 9,
      'In Supplemental Data Entry' => 10,
      'Ready for Supplemental Quality Control' => 11,
      'In Supplemental Quality Control' => 12,
      'Ready for Supplemental Quality Assurance' => 13,
      'In Supplemental Quality Assurance' => 14
    }

    #Which statuses are accessible to which roles
    DE_ACCESS = [STATUS_NEW, STATUS_DE1, STATUS_READY_SUPP_DE]
    QC_ACCESS = [STATUS_NEW, STATUS_DE1, STATUS_READY_QC, STATUS_READY_SUPP_DE, STATUS_READY_SUPP_QC]
    QA_ACCESS = [STATUS_NEW, STATUS_DE1, STATUS_READY_QC, STATUS_READY_QA, STATUS_READY_SUPP_DE, STATUS_READY_SUPP_QC, STATUS_READY_SUPP_QA]
    EXTRACT_ACCESS = [STATUS_READY_EXT]

    #Which statuses allow claims
    CLAIMABLE_STATUS = [STATUS_NEW, STATUS_DE1, STATUS_READY_QC, STATUS_READY_QA, STATUS_READY_EXT, STATUS_READY_SUPP_DE, STATUS_READY_SUPP_QC, STATUS_READY_SUPP_QA]

    #Returns what the status will be when the current status is claimed
    def claimed_status(current)
      case current
        when STATUS_NEW, STATUS_DE1, STATUS_READY_QC, STATUS_READY_QA, STATUS_READY_SUPP_DE, STATUS_READY_SUPP_QC, STATUS_READY_SUPP_QA
          return current+1
        else
          return nil
      end
    end

  end

end


text:
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:context=".GameActivity">
    <include
        android:id="@+id/large1"
        layout="@layout/small_board"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="0"
        android:layout_margin="@dimen/small_board_margin"
        android:layout_row="0" />
    <include
        android:id="@+id/large2"
        layout="@layout/small_board"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="1"
        android:layout_margin="@dimen/small_board_margin"
        android:layout_row="0" />
    <include
        android:id="@+id/large3"
        layout="@layout/small_board"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="2"
        android:layout_margin="@dimen/small_board_margin"
        android:layout_row="0" />
    <include
        android:id="@+id/large4"
        layout="@layout/small_board"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="0"
        android:layout_margin="@dimen/small_board_margin"
        android:layout_row="1" />
    <include
        android:id="@+id/large5"
        layout="@layout/small_board"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="1"
        android:layout_margin="@dimen/small_board_margin"
        android:layout_row="1" />
    <include
        android:id="@+id/large6"
        layout="@layout/small_board"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="2"
        android:layout_margin="@dimen/small_board_margin"
        android:layout_row="1" />
    <include
        android:id="@+id/large7"
        layout="@layout/small_board"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="0"
        android:layout_margin="@dimen/small_board_margin"
        android:layout_row="2" />
    <include
        android:id="@+id/large8"
        layout="@layout/small_board"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="1"
        android:layout_margin="@dimen/small_board_margin"
        android:layout_row="2" />
    <include
        android:id="@+id/large9"
        layout="@layout/small_board"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="2"
        android:layout_margin="@dimen/small_board_margin"
        android:layout_row="2" />
</GridLayout>


text:
package to.us.harha.jpath.tracer;

import java.util.ArrayList;

import to.us.harha.jpath.tracer.object.Material;
import to.us.harha.jpath.tracer.object.Mesh;
import to.us.harha.jpath.tracer.object.TracerObject;
import to.us.harha.jpath.util.math.Plane;
import to.us.harha.jpath.util.math.Primitive;
import to.us.harha.jpath.util.math.Quaternion;
import to.us.harha.jpath.util.math.Sphere;
import to.us.harha.jpath.util.math.Transform;
import to.us.harha.jpath.util.math.Vec3f;

public class Scene
{

	private ArrayList<TracerObject> m_objects;
	private ArrayList<Camera>       m_cameras;

	public Scene()
	{
		m_objects = new ArrayList<TracerObject>();
		m_cameras = new ArrayList<Camera>();

		m_cameras.add(new Camera(new Vec3f(0, 1.0f, 5.0f), new Quaternion().initIdentity().mul(new Quaternion().createFromAxisAngle(1, 0, 0, 5)), 0.0025f, 0.1f));

		Material mat_diffuse_white = new Material(new Vec3f(0.0f), new Vec3f(1.0f));
		Material mat_diffuse_blue = new Material(new Vec3f(0.0f), new Vec3f(0.0f, 0.0f, 1.0f));
		Material mat_refractive_glass = new Material(new Vec3f(0.0f), 0.0f, 1.0f, 1.52f, 0.0f);
		Material mat_mirror = new Material(new Vec3f(0.0f, 1.0f, 0.0f), 1.0f, 0.0f, 1.0f, 0.0f);
		Material mat_light_white = new Material(new Vec3f(12.5f), new Vec3f(0.0f));

		Primitive plane_floor = new Plane(new Vec3f(0.0f, 0.0f, 0.0f), new Vec3f(0.0f, 1.0f, 0.0f));
		Primitive plane_ceiling = new Plane(new Vec3f(0.0f, 4.0f, 0.0f), new Vec3f(0.0f, -1.0f, 0.0f));
		Primitive plane_left = new Plane(new Vec3f(-2.5f, 0.0f, 0.0f), new Vec3f(1.0f, 0.0f, 0.0f));
		Primitive plane_right = new Plane(new Vec3f(2.5f, 0.0f, 0.0f), new Vec3f(-1.0f, 0.0f, 0.0f));
		Primitive plane_forward = new Plane(new Vec3f(0.0f, 0.0f, 4.0f), new Vec3f(0.0f, 0.0f, -1.0f));
		Primitive plane_back = new Plane(new Vec3f(0.0f, 0.0f, -4.0f), new Vec3f(0.0f, 0.0f, 1.0f));

		TracerObject obj_lamp_0 = new TracerObject(new Mesh("lamp.obj"), mat_light_white, new Transform(new Vec3f(0.0f, 4.0f, 0.0f), new Quaternion().initIdentity(), new Vec3f(0.5f, 1.0f, 0.5f)));
		TracerObject obj_cube_0 = new TracerObject(new Mesh("cube.obj"), mat_diffuse_white, new Transform(new Vec3f(1.0f, 0.25f, 2.0f), new Quaternion().initIdentity().mul(new Quaternion().createFromAxisAngle(0, 1, 0, 45)), new Vec3f(0.25f)));
		TracerObject obj_diffuse_white = new TracerObject(mat_diffuse_white);
		TracerObject obj_diffuse_blue = new TracerObject(mat_diffuse_blue);
		TracerObject obj_refractive_glass = new TracerObject(mat_refractive_glass);
		TracerObject obj_mirror = new TracerObject(mat_mirror);
		TracerObject obj_light_white = new TracerObject(mat_light_white);

		obj_diffuse_white.addPrimitive(plane_floor);
		obj_diffuse_white.addPrimitive(plane_ceiling);
		obj_diffuse_white.addPrimitive(plane_left);
		obj_diffuse_blue.addPrimitive(plane_right);
		obj_diffuse_white.addPrimitive(plane_forward);
		obj_diffuse_white.addPrimitive(plane_back);

		obj_refractive_glass.addPrimitive(new Sphere(new Vec3f(-0.75f, 0.6f, 0.5f), 0.5f));
		obj_mirror.addPrimitive(new Sphere(new Vec3f(0.75f, 0.6f, 0.5f), 0.5f));

		m_objects.add(obj_refractive_glass);
		m_objects.add(obj_mirror);
		m_objects.add(obj_lamp_0);
		m_objects.add(obj_cube_0);
		m_objects.add(obj_diffuse_white);
		m_objects.add(obj_diffuse_blue);
		m_objects.add(obj_light_white);
	}

	public ArrayList<TracerObject> getObjects()
	{
		return m_objects;
	}

	public ArrayList<Camera> getCameras()
	{
		return m_cameras;
	}

	public void setObjects(ArrayList<TracerObject> m_objects)
	{
		this.m_objects = m_objects;
	}

	public void setCameras(ArrayList<Camera> m_cameras)
	{
		this.m_cameras = m_cameras;
	}

}