text:
'''
Main file for dispatching jobs to a cluster, creates remote files, etc.

@authors: David Duvenaud (dkd23@cam.ac.uk)
          James Robert Lloyd (jrl44@cam.ac.uk)
          Roger Grosse (rgrosse@mit.edu)

Created Jan 2013
'''

import flexiblekernel as fk
from flexiblekernel import ScoredKernel
import grammar
import gpml
import utils.latex
import utils.fear
try:
    from config import *
except:
    print '\n\nERROR : source/config.py not found\n\nPlease create it following example file as a guide\n\n'
    raise Exception('No config')
from utils import gaussians, psd_matrices

import numpy as np
nax = np.newaxis
import pylab
import scipy.io
import sys
import os
import tempfile
import subprocess
import time

import cblparallel
from cblparallel.util import mkstemp_safe
import re

import shutil
import random

def covariance_distance(kernels, X, local_computation=True, verbose=True):
    '''
    Evaluate a distance matrix of kernels, in terms of their covariance matrix evaluated on training inputs
    Input:
     - kernels           - A list of fk.ScoredKernel
     - X                 - A matrix (data_points x dimensions) of input locations
     - local_computation - Boolean indicating if computation should be performed on cluster or on local machine
    Return:
     - A matrix of similarities between the input kernels
    '''
    assert(len(kernels) > 0) #### FIXME - This sort of check should happen earlier
    # Make data into matrices in case they're unidimensional.
    if X.ndim == 1: X = X[:, nax]
    # Save temporary data file in standard temporary directory
    data_file = cblparallel.create_temp_file('.mat')
    scipy.io.savemat(data_file, {'X': X})
    # Copy onto cluster server if necessary
    if not local_computation:
        if verbose:
            print 'Moving data file to fear'
        cblparallel.copy_to_remote(data_file)
    # Construct testing code
    code = gpml.DISTANCE_CODE_HEADER % {'datafile': data_file.split('/')[-1],
                                          'gpml_path': cblparallel.gpml_path(local_computation)}
    for (i, kernel) in enumerate([k.k_opt for k in kernels]):
        code = code + gpml.DISTANCE_CODE_COV % {'iter' : i + 1,
                                                  'kernel_family': kernel.gpml_kernel_expression(),
                                                  'kernel_params': '[ %s ]' % ' '.join(str(p) for p in kernel.param_vector())}
    code = code + gpml.DISTANCE_CODE_FOOTER_HIGH_MEM % {'writefile': '%(output_file)s'} # N.B. cblparallel manages output files
    code = re.sub('% ', '%% ', code) # HACK - cblparallel not fond of % signs at the moment
    # Run code - either locally or on cluster - returning location of output file
    if local_computation:
        output_file = cblparallel.run_batch_locally([code], language='matlab', max_cpu=1.1, max_mem=1.1, job_check_sleep=30, verbose=verbose, single_thread=False)[0]
    else:
        output_file = cblparallel.run_batch_on_fear([code], language='matlab', max_jobs=500, verbose=verbose)[0]
    # Read in results from experiment
    gpml_result = scipy.io.loadmat(output_file)
    distance = gpml_result['sim_matrix']
    # Remove temporary files (perhaps on the cluster server)
    cblparallel.remove_temp_file(output_file, local_computation)
    cblparallel.remove_temp_file(data_file, local_computation)
    # Return distance matrix
    return distance

def evaluate_kernels(kernels, X, y, verbose=True, noise=None, iters=300, local_computation=False, zip_files=False, max_jobs=500, zero_mean=False, random_seed=0):
    '''
    Sets up the kernel optimisation and nll calculation experiments, returns the results as scored kernels
    Input:
     - kernels           - A list of kernels (i.e. not scored kernels)
     - X                 - A matrix (data_points x dimensions) of input locations
     - y                 - A matrix (data_points x 1) of output values
     - ...
    Return:
     - A list of ScoredKernel objects
    '''

    # Make data into matrices in case they're unidimensional.
    if X.ndim == 1: X = X[:, nax]
    if y.ndim == 1: y = y[:, nax]
    ndata = y.shape[0]

    # Set default noise using a heuristic.
    if noise is None:
        noise = np.log(np.var(y)/10)

    # Create data file
    if verbose:
        print 'Creating data file locally'
    data_file = cblparallel.create_temp_file('.mat')
    scipy.io.savemat(data_file, {'X': X, 'y': y}) # Save regression data

    # Move to fear if necessary
    if not local_computation:
        if verbose:
            print 'Moving data file to fear'
        cblparallel.copy_to_remote(data_file)

    # Create a list of MATLAB scripts to assess and optimise parameters for each kernel
    if verbose:
        print 'Creating scripts'
    scripts = [None] * len(kernels)
    for (i, kernel) in enumerate(kernels):
        parameters = {'datafile': data_file.split('/')[-1],
                      'writefile': '%(output_file)s', # N.B. cblparallel manages output files
                      'gpml_path': cblparallel.gpml_path(local_computation),
                      'kernel_family': kernel.gpml_kernel_expression(),
                      'kernel_params': '[ %s ]' % ' '.join(str(p) for p in kernel.param_vector()),
                      'noise': str(noise),
                      'iters': str(iters),
                      'seed': str(random_seed)}
        if zero_mean:
            scripts[i] = gpml.OPTIMIZE_KERNEL_CODE_ZERO_MEAN % parameters
        else:
            scripts[i] = gpml.OPTIMIZE_KERNEL_CODE % parameters
        #### Need to be careful with % signs
        #### For the moment, cblparallel expects no single % signs - FIXME
        scripts[i] = re.sub('% ', '%% ', scripts[i])

    # Send to cblparallel and save output_files
    if verbose:
        print 'Sending scripts to cblparallel'
    if local_computation:
        output_files = cblparallel.run_batch_locally(scripts, language='matlab', max_cpu=1.1, job_check_sleep=5, submit_sleep=0.1, max_running_jobs=10, verbose=verbose)
    else:
        output_files = cblparallel.run_batch_on_fear(scripts, language='matlab', max_jobs=max_jobs, verbose=verbose, zip_files=zip_files)

    # Read in results
    results = [None] * len(kernels)
    for (i, output_file) in enumerate(output_files):
        if verbose:
            print 'Reading output file %d of %d' % (i + 1, len(kernels))
        results[i] = ScoredKernel.from_matlab_output(gpml.read_outputs(output_file), kernels[i].family(), ndata)

    # Tidy up local output files
    for (i, output_file) in enumerate(output_files):
        if verbose:
            print 'Removing output file %d of %d' % (i + 1, len(kernels))
        os.remove(output_file)
    # Remove temporary data file (perhaps on the cluster server)
    cblparallel.remove_temp_file(data_file, local_computation)

    # Return results i.e. list of ScoredKernel objects
    return results

def make_predictions(X, y, Xtest, ytest, best_scored_kernel, local_computation=False, max_jobs=500, verbose=True, zero_mean=False, random_seed=0):
    '''
    Evaluates a kernel on held out data
    Input:
     - X                  - A matrix (data_points x dimensions) of input locations
     - y                  - A matrix (data_points x 1) of output values
     - Xtest              - Held out X data
     - ytest              - Held out y data
     - best_scored_kernel - A Scored Kernel object to be evaluated on the held out data
     - ...
    Return:
     - A dictionary of results from the MATLAB script containing:
       - loglik - an array of log likelihoods of test data
       - predictions - an array of mean predictions for the held out data
       - actuals - ytest
       - model - I'm not sure FIXME
       - timestamp - A time stamp of some sort
    '''
    # Make data into matrices in case they're unidimensional.
    if X.ndim == 1: X = X[:, nax]
    if y.ndim == 1: y = y[:, nax]
    ndata = y.shape[0]
    # Save temporary data file in standard temporary directory
    data_file = cblparallel.create_temp_file('.mat')
    scipy.io.savemat(data_file, {'X': X, 'y': y, 'Xtest' : Xtest, 'ytest' : ytest})
    # Copy onto cluster server if necessary
    if not local_computation:
        if verbose:
            print 'Moving data file to fear'
        cblparallel.copy_to_remote(data_file)
    # Create prediction code
    parameters ={'datafile': data_file.split('/')[-1],
                 'writefile': '%(output_file)s',
                 'gpml_path': cblparallel.gpml_path(local_computation),
                 'kernel_family': best_scored_kernel.k_opt.gpml_kernel_expression(),
                 'kernel_params': '[ %s ]' % ' '.join(str(p) for p in best_scored_kernel.k_opt.param_vector()),
                 'noise': str(best_scored_kernel.noise),
                 'iters': str(30),
                 'seed': str(random_seed)}
    if zero_mean:
        code = gpml.PREDICT_AND_SAVE_CODE_ZERO_MEAN % parameters
    else:
        code = gpml.PREDICT_AND_SAVE_CODE % parameters
    code = re.sub('% ', '%% ', code) # HACK - cblparallel currently does not like % signs
    # Evaluate code - potentially on cluster
    if local_computation:
        temp_results_file = cblparallel.run_batch_locally([code], language='matlab', max_cpu=1.1, max_mem=1.1, verbose=verbose)[0]
    else:
        temp_results_file = cblparallel.run_batch_on_fear([code], language='matlab', max_jobs=max_jobs, verbose=verbose)[0]
    results = scipy.io.loadmat(temp_results_file)
    # Remove temporary files (perhaps on the cluster server)
    cblparallel.remove_temp_file(temp_results_file, local_computation)
    cblparallel.remove_temp_file(data_file, local_computation)
    # Return dictionary of MATLAB results
    return results


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Authy\V1;

use Twilio\Exceptions\TwilioException;
use Twilio\InstanceContext;
use Twilio\Values;
use Twilio\Version;

/**
 * PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
 */
class FormContext extends InstanceContext {
    /**
     * Initialize the FormContext
     *
     * @param \Twilio\Version $version Version that contains the resource
     * @param string $formType The Type of this Form
     * @return \Twilio\Rest\Authy\V1\FormContext
     */
    public function __construct(Version $version, $formType) {
        parent::__construct($version);

        // Path Solution
        $this->solution = array('formType' => $formType, );

        $this->uri = '/Forms/' . \rawurlencode($formType) . '';
    }

    /**
     * Fetch a FormInstance
     *
     * @return FormInstance Fetched FormInstance
     * @throws TwilioException When an HTTP error occurs.
     */
    public function fetch() {
        $params = Values::of(array());

        $payload = $this->version->fetch(
            'GET',
            $this->uri,
            $params
        );

        return new FormInstance($this->version, $payload, $this->solution['formType']);
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString() {
        $context = array();
        foreach ($this->solution as $key => $value) {
            $context[] = "$key=$value";
        }
        return '[Twilio.Authy.V1.FormContext ' . \implode(' ', $context) . ']';
    }
}

redpajama_set_name: RedPajamaGithub


text:
package scala.collection

import scala.collection
import scala.collection.immutable.{Nil, List}

trait BagBucket[A]
  extends Iterable[A] {

  protected type BagBucket <: collection.BagBucket[A]

  def sentinel: A

  def multiplicity(elem: A): Int

  def maxMultiplicity: Int = {
    if (isEmpty)
      throw new UnsupportedOperationException("empty.maxMultiplicity")

    distinctIterator.map(elem => multiplicity(elem)).max
  }

  def minMultiplicity: Int = {
    if (isEmpty)
      throw new UnsupportedOperationException("empty.maxMultiplicity")

    distinctIterator.map(elem => multiplicity(elem)).min
  }

  def intersect(that: collection.BagBucket[A]): BagBucket

  def diff(that: collection.BagBucket[A]): BagBucket

  def subsetOf(that: collection.BagBucket[A]): Boolean = {
    this.distinctIterator.forall(elem => this.multiplicity(elem) <= that.multiplicity(elem))
  }

  def +(elem: A): BagBucket = added(elem, 1)

  def +(elemCount: (A, Int)): BagBucket = added(elemCount._1, elemCount._2)

  def added(elem: A, count: Int): BagBucket

  def addedBucket(bucket: collection.BagBucket[A]): BagBucket

  def -(elem: A): BagBucket = removed(elem, 1)

  def removed(elem: A, count: Int): BagBucket

  def distinct: BagBucket

  def distinctIterator: Iterator[A]
}

trait MultiplicityBagBucket[A] extends BagBucket[A] {

  def multiplicity: Int

  def multiplicity(elem: A): Int = if (elem == sentinel) multiplicity else 0

  override def maxMultiplicity: Int = {
    if (multiplicity == 0)
      throw new UnsupportedOperationException("empty.maxMultiplicity")

    multiplicity
  }

  override def minMultiplicity: Int = {
    if (multiplicity == 0)
      throw new UnsupportedOperationException("empty.minMultiplicity")

    multiplicity
  }

  override def subsetOf(that: collection.BagBucket[A]): Boolean = multiplicity <= that.multiplicity(sentinel)

  override def exists(p: (A) => Boolean): Boolean = p(sentinel)

  override def forall(p: (A) => Boolean): Boolean = p(sentinel)

  override def isEmpty: Boolean = multiplicity == 0

  override def iterator: Iterator[A] = Iterator.fill(multiplicity)(sentinel)

  override def sum[B >: A](implicit num: Numeric[B]): B = num.times(sentinel, num.fromInt(multiplicity))

  override def min[B >: A](implicit cmp: Ordering[B]): A = {
    if (isEmpty)
      throw new UnsupportedOperationException("emptyBag.minBy")

    sentinel
  }

  override def max[B >: A](implicit cmp: Ordering[B]): A = {
    if (isEmpty)
      throw new UnsupportedOperationException("emptyBag.minBy")

    sentinel
  }

  override def minBy[B](f: (A) => B)(implicit cmp: Ordering[B]): A = {
    if (isEmpty)
      throw new UnsupportedOperationException("emptyBag.minBy")

    sentinel
  }

  override def maxBy[B](f: (A) => B)(implicit cmp: Ordering[B]): A = {
    if (isEmpty)
      throw new UnsupportedOperationException("emptyBag.minBy")

    sentinel
  }

  override def count(p: (A) => Boolean): Int = if (p(sentinel)) multiplicity else 0

  override def size: Int = multiplicity

  override def find(p: (A) => Boolean): Option[A] = if (p(sentinel)) Some(sentinel) else None

  def distinctIterator: Iterator[A] = Iterator(sentinel)
}

trait BagOfMultiplicitiesBagBucket[A] extends BagBucket[A] {

  def bag: collection.Bag[A]

  def multiplicity(elem: A): Int = bag.multiplicity(elem)

  def distinctIterator: Iterator[A] = bag.distinctIterator

  def iterator: Iterator[A] = bag.iterator

  override def size: Int = bag.size

  override def nonEmpty: Boolean = bag.nonEmpty

  override def count(p: (A) => Boolean): Int = bag.count(p)

  override def min[B >: A](implicit cmp: Ordering[B]): A = bag.min(cmp)

  override def max[B >: A](implicit cmp: Ordering[B]): A = bag.max(cmp)

  override def maxBy[B](f: (A) => B)(implicit cmp: Ordering[B]): A = bag.maxBy(f)(cmp)

  override def minBy[B](f: (A) => B)(implicit cmp: Ordering[B]): A = bag.minBy(f)(cmp)

  override def sum[B >: A](implicit num: Numeric[B]): B = bag.sum(num)

  override def product[B >: A](implicit num: Numeric[B]): B = bag.product(num)

  override def foldLeft[B](z: B)(op: (B, A) => B): B = bag.foldLeft(z)(op)

  override def reduceLeft[B >: A](op: (B, A) => B): B = bag.reduceLeft(op)

  override def forall(p: (A) => Boolean): Boolean = bag.forall(p)

  override def exists(p: (A) => Boolean): Boolean = bag.exists(p)

  override def find(p: (A) => Boolean): Option[A] = bag.find(p)

  override def isEmpty: Boolean = bag.isEmpty

  override def foldRight[B](z: B)(op: (A, B) => B): B = bag.foldRight(z)(op)

  override def reduceRight[B >: A](op: (A, B) => B): B = bag.reduceRight(op)

  override def maxMultiplicity: Int = bag.maxMultiplicity

  override def minMultiplicity: Int = bag.minMultiplicity

}

trait ListBagBucket[A] extends BagBucket[A] {

  def list: List[A]

  def multiplicity(elem: A): Int = list.count(_ == elem)

  def iterator: Iterator[A] = list.iterator

  def distinctIterator: Iterator[A] = {
    val seen = mutable.Set.empty[A]
    for (elem <- list.iterator if !seen(elem)) yield {
      seen += elem
      elem
    }
  }

  protected def removedFromList(elem: A, list: List[A], count: Int): List[A] = {
    def removedRec(l: List[A], c: Int): List[A] = {
      if (c > 0) l match {
        case `elem` :: tail => removedRec(tail, c - 1)
        case hd :: tail => hd :: removedRec(tail, c)
        case Nil => Nil
      }
      else l
    }
    removedRec(list, count)
  }
}


text:
using System;
using System.Collections.Generic;
using System.Windows.Data;

namespace NuGet.Dialog.PackageManagerUI
{
    public class StringCollectionsToStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (targetType == typeof(string))
            {
                string stringValue = value as string;
                if (stringValue != null)
                {
                    return stringValue;
                }
                else if (value == null)
                {
                    return String.Empty;
                }
                else
                {
                    IEnumerable<string> parts = (IEnumerable<string>)value;
                    return String.Join(", ", parts);
                }
            }

            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}


text:
import logging
from datetime import timedelta
from functools import partial

from tornado import gen
from tornadoredis import Client
from tornadoredis.exceptions import ResponseError
from tornadoredis.pubsub import BaseSubscriber

logger = logging.getLogger(__name__)

class CelerySubscriber(BaseSubscriber):
    def unsubscribe_channel(self, channel_name, callback=None):
        """Unsubscribes the redis client from the channel"""
        del self.subscribers[channel_name]
        del self.subscriber_count[channel_name]
        self.redis.unsubscribe(channel_name, callback)

    def on_message(self, msg):
        logger.info('Calling on_message in tcelery.redis.CelerySubscriber')
        if not msg:
            return
        try:
            if msg.kind == 'message' and msg.body:
                # Get the list of subscribers for this channel
                for subscriber in self.subscribers[msg.channel].keys():
                    subscriber(msg.body)
        finally:
            super(CelerySubscriber, self).on_message(msg)

class RedisClient(Client):
    @gen.engine
    def _consume_bulk(self, tail, callback=None):
        response = yield gen.Task(self.connection.read, int(tail) + 2)
        if isinstance(response, Exception):
            raise response
        if not response:
            raise ResponseError('EmptyResponse')
        else:
            # We don't cast try to convert to unicode here as the response
            # may not be utf-8 encoded, for example if using msgpack as a
            # serializer
            # response = to_unicode(response)
            response = response[:-2]
        callback(response)

class RedisConsumer(object):
    def __init__(self, producer):
        self.producer = producer
        backend = producer.app.backend
        self.client = RedisClient(host=backend.connparams['host'],
                                  port=backend.connparams['port'],
                                  password=backend.connparams['password'],
                                  selected_db=backend.connparams['db'],
                                  io_loop=producer.conn_pool.io_loop)
        self.client.connect()
        self.subscriber = CelerySubscriber(self.client)

    def wait_for(self, task_id, callback, expires=None, persistent=None):
        key = self.producer.app.backend.get_key_for_task(task_id)
        if expires:
            timeout = self.producer.conn_pool.io_loop.add_timeout(
                timedelta(milliseconds=expires), self.on_timeout, key)
        else:
            timeout = None
        logger.info("Subscription timeout expiration {}".format(expires))
        logger.info("Subscribing to key %s (%s) with timeout %s",
                     task_id, key, timeout)
        self.subscriber.subscribe(
            key, partial(self.on_result, key, callback, timeout))
        logger.info("Subscribed to key %s (%s) with timeout %s",
                     task_id, key, timeout)

    def on_result(self, key, callback, timeout, result):
        import inspect
        curframe = inspect.currentframe()
        calframe = inspect.getouterframes(curframe, 2)
        logger.info('on_result caller name: {}'.format(calframe[1][3]))
        if timeout:
            self.producer.conn_pool.io_loop.remove_timeout(timeout)
        logger.info("Got result for key %s, unsubscribing...", key)

        self.subscriber.unsubscribe_channel(
            key, partial(self.on_unsubscribed, key, callback, result))

    def on_unsubscribed(self, key, callback, result):
        logger.info("Unsubscribed from %s", key)
        callback(result)

    def on_timeout(self, key):
        logger.info("Task timed out on key %s")
        self.subscriber.unsubscribe_channel(key)


text:
/* ==> Do not modify this file!!  It is created automatically
   from bsd_callg_bl.m using the gen-c-prog.awk script.  <== */

#include <stdio.h>
#include "ansidecl.h"

void  bsd_callg_blurb (FILE *);
void
bsd_callg_blurb (file)
     FILE *file;
{
  fputs ("\n", file);
  fputs ("\n", file);
  fputs ("\n", file);
  fputs ("call graph profile:\n", file);
  fputs ("          The sum of self and descendents is the major sort\n", file);
  fputs ("          for this listing.\n", file);
  fputs ("\n", file);
  fputs ("          function entries:\n", file);
  fputs ("\n", file);
  fputs ("index     the index of the function in the call graph\n", file);
  fputs ("          listing, as an aid to locating it (see below).\n", file);
  fputs ("\n", file);
  fputs ("%time     the percentage of the total time of the program\n", file);
  fputs ("          accounted for by this function and its\n", file);
  fputs ("          descendents.\n", file);
  fputs ("\n", file);
  fputs ("self      the number of seconds spent in this function\n", file);
  fputs ("          itself.\n", file);
  fputs ("\n", file);
  fputs ("descendents\n", file);
  fputs ("          the number of seconds spent in the descendents of\n", file);
  fputs ("          this function on behalf of this function.\n", file);
  fputs ("\n", file);
  fputs ("called    the number of times this function is called (other\n", file);
  fputs ("          than recursive calls).\n", file);
  fputs ("\n", file);
  fputs ("self      the number of times this function calls itself\n", file);
  fputs ("          recursively.\n", file);
  fputs ("\n", file);
  fputs ("name      the name of the function, with an indication of\n", file);
  fputs ("          its membership in a cycle, if any.\n", file);
  fputs ("\n", file);
  fputs ("index     the index of the function in the call graph\n", file);
  fputs ("          listing, as an aid to locating it.\n", file);
  fputs ("\n", file);
  fputs ("\n", file);
  fputs ("\n", file);
  fputs ("          parent listings:\n", file);
  fputs ("\n", file);
  fputs ("self*     the number of seconds of this function's self time\n", file);
  fputs ("          which is due to calls from this parent.\n", file);
  fputs ("\n", file);
  fputs ("descendents*\n", file);
  fputs ("          the number of seconds of this function's\n", file);
  fputs ("          descendent time which is due to calls from this\n", file);
  fputs ("          parent.\n", file);
  fputs ("\n", file);
  fputs ("called**  the number of times this function is called by\n", file);
  fputs ("          this parent.  This is the numerator of the\n", file);
  fputs ("          fraction which divides up the function's time to\n", file);
  fputs ("          its parents.\n", file);
  fputs ("\n", file);
  fputs ("total*    the number of times this function was called by\n", file);
  fputs ("          all of its parents.  This is the denominator of\n", file);
  fputs ("          the propagation fraction.\n", file);
  fputs ("\n", file);
  fputs ("parents   the name of this parent, with an indication of the\n", file);
  fputs ("          parent's membership in a cycle, if any.\n", file);
  fputs ("\n", file);
  fputs ("index     the index of this parent in the call graph\n", file);
  fputs ("          listing, as an aid in locating it.\n", file);
  fputs ("\n", file);
  fputs ("\n", file);
  fputs ("\n", file);
  fputs ("          children listings:\n", file);
  fputs ("\n", file);
  fputs ("self*     the number of seconds of this child's self time\n", file);
  fputs ("          which is due to being called by this function.\n", file);
  fputs ("\n", file);
  fputs ("descendent*\n", file);
  fputs ("          the number of seconds of this child's descendent's\n", file);
  fputs ("          time which is due to being called by this\n", file);
  fputs ("          function.\n", file);
  fputs ("\n", file);
  fputs ("called**  the number of times this child is called by this\n", file);
  fputs ("          function.  This is the numerator of the\n", file);
  fputs ("          propagation fraction for this child.\n", file);
  fputs ("\n", file);
  fputs ("total*    the number of times this child is called by all\n", file);
  fputs ("          functions.  This is the denominator of the\n", file);
  fputs ("          propagation fraction.\n", file);
  fputs ("\n", file);
  fputs ("children  the name of this child, and an indication of its\n", file);
  fputs ("          membership in a cycle, if any.\n", file);
  fputs ("\n", file);
  fputs ("index     the index of this child in the call graph listing,\n", file);
  fputs ("          as an aid to locating it.\n", file);
  fputs ("\n", file);
  fputs ("\n", file);
  fputs ("\n", file);
  fputs ("          * these fields are omitted for parents (or\n", file);
  fputs ("          children) in the same cycle as the function.  If\n", file);
  fputs ("          the function (or child) is a member of a cycle,\n", file);
  fputs ("          the propagated times and propagation denominator\n", file);
  fputs ("          represent the self time and descendent time of the\n", file);
  fputs ("          cycle as a whole.\n", file);
  fputs ("\n", file);
  fputs ("          ** static-only parents and children are indicated\n", file);
  fputs ("          by a call count of 0.\n", file);
  fputs ("\n", file);
  fputs ("\n", file);
  fputs ("\n", file);
  fputs ("          cycle listings:\n", file);
  fputs ("          the cycle as a whole is listed with the same\n", file);
  fputs ("          fields as a function entry.  Below it are listed\n", file);
  fputs ("          the members of the cycle, and their contributions\n", file);
  fputs ("          to the time and call counts of the cycle.\n", file);
  fputs ("\n", file);
}


text:
@interface OFChatRoomDefinitionService : OFService

OPENFEINT_DECLARE_AS_SERVICE(OFChatRoomDefinitionService);

+ (void) getIndexOnSuccess:(const OFDelegate&)onSuccess onFailure:(const OFDelegate&)onFailure;
+ (void) getPage:(NSInteger)pageIndex
includeGlobalRooms:(bool)includeGlobalRooms
includeDeveloperRooms:(bool)includeDeveloperRooms
includeApplicationRooms:(bool)includeApplicationRooms
includeLastVisitedRoom:(bool)includeLastVisitedRoom
	   onSuccess:(const OFDelegate&)onSuccess
	   onFailure:(const OFDelegate&)onFailure;
@end


text:
param($installPath, $toolsPath, $package, $project)

<# Get the project location #>
$projectPath = $project.FullName;
$projectDirectory = (Get-Item $projectPath).DirectoryName

<# Remove gulp.cmd #>
Remove-Item ($projectDirectory + '\gulp.cmd')

<# Remove the build target #>
#$buildProject = @([Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($projectPath))[0]
<#foreach ($import in $buildProject.Xml.Imports) {
	if ($import.Project -eq "App_Build\gulp.targets") {
		#$buildProject.Xml.RemoveChild($import);
		break;
	}
}#>
##$buildProject.Save();


text:
"""
Demo light platform that implements lights.

For more details about this platform, please refer to the documentation
https://home-assistant.io/components/demo/
"""
import random

from homeassistant.components.light import (
    ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_RGB_COLOR, ATTR_WHITE_VALUE,
    ATTR_XY_COLOR, SUPPORT_BRIGHTNESS, SUPPORT_COLOR_TEMP, SUPPORT_RGB_COLOR,
    SUPPORT_WHITE_VALUE, Light)

LIGHT_COLORS = [
    [237, 224, 33],
    [255, 63, 111],
]

LIGHT_TEMPS = [240, 380]

SUPPORT_DEMO = (SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP | SUPPORT_RGB_COLOR |
                SUPPORT_WHITE_VALUE)

def setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """Setup the demo light platform."""
    add_devices_callback([
        DemoLight("Bed Light", False),
        DemoLight("Ceiling Lights", True, LIGHT_COLORS[0], LIGHT_TEMPS[1]),
        DemoLight("Kitchen Lights", True, LIGHT_COLORS[1], LIGHT_TEMPS[0])
    ])

class DemoLight(Light):
    """Represenation of a demo light."""

    # pylint: disable=too-many-arguments
    def __init__(
            self, name, state, rgb=None, ct=None, brightness=180,
            xy_color=(.5, .5), white=200):
        """Initialize the light."""
        self._name = name
        self._state = state
        self._rgb = rgb
        self._ct = ct or random.choice(LIGHT_TEMPS)
        self._brightness = brightness
        self._xy_color = xy_color
        self._white = white

    @property
    def should_poll(self):
        """No polling needed for a demo light."""
        return False

    @property
    def name(self):
        """Return the name of the light if any."""
        return self._name

    @property
    def brightness(self):
        """Return the brightness of this light between 0..255."""
        return self._brightness

    @property
    def xy_color(self):
        """Return the XY color value [float, float]."""
        return self._xy_color

    @property
    def rgb_color(self):
        """Return the RBG color value."""
        return self._rgb

    @property
    def color_temp(self):
        """Return the CT color temperature."""
        return self._ct

    @property
    def white_value(self):
        """Return the white value of this light between 0..255."""
        return self._white

    @property
    def is_on(self):
        """Return true if light is on."""
        return self._state

    @property
    def supported_features(self):
        """Flag supported features."""
        return SUPPORT_DEMO

    def turn_on(self, **kwargs):
        """Turn the light on."""
        self._state = True

        if ATTR_RGB_COLOR in kwargs:
            self._rgb = kwargs[ATTR_RGB_COLOR]

        if ATTR_COLOR_TEMP in kwargs:
            self._ct = kwargs[ATTR_COLOR_TEMP]

        if ATTR_BRIGHTNESS in kwargs:
            self._brightness = kwargs[ATTR_BRIGHTNESS]

        if ATTR_XY_COLOR in kwargs:
            self._xy_color = kwargs[ATTR_XY_COLOR]

        if ATTR_WHITE_VALUE in kwargs:
            self._white = kwargs[ATTR_WHITE_VALUE]

        self.update_ha_state()

    def turn_off(self, **kwargs):
        """Turn the light off."""
        self._state = False
        self.update_ha_state()


text:
This is a multiplayer UNO card game based on the client-server architecture written in C++ and JavaScript. The following keywords are related in the current state of the project: C++, JavaScript, node.js, HTML5, CSS3, Socket.IO, publish-subscribe. A few may follow later: Java, Andriod, OpenGL.

Currently there are no easily accessible working versions of the game, however, there are such versions buried deep in the history.

##Directory Structure
The v0.2 branch has a brand new structure as follows:

- docs
- server - acts as a separate npm module
  - lib - server related js files and link to the compiled addon
  - addon - C++ resources
- client-browser - acts as separate npm module, files related to the client are here


text:
<?php

class Twig_Node_Expression_Binary_Equal extends Twig_Node_Expression_Binary
{
    public function operator(Twig_Compiler $compiler)
    {
        return $compiler->raw('==');
    }
}


text:
#ifndef CMARK_CMARK_CTYPE_H
#define CMARK_CMARK_CTYPE_H

#ifdef __cplusplus
extern "C" {
#endif

#include "cmark-gfm_export.h"

/** Locale-independent versions of functions from ctype.h.
 * We want cmark to behave the same no matter what the system locale.
 */

CMARK_GFM_EXPORT
int cmark_isspace(char c);

CMARK_GFM_EXPORT
int cmark_ispunct(char c);

CMARK_GFM_EXPORT
int cmark_isalnum(char c);

CMARK_GFM_EXPORT
int cmark_isdigit(char c);

CMARK_GFM_EXPORT
int cmark_isalpha(char c);

#ifdef __cplusplus
}
#endif

#endif


text:
<?php

namespace App\Models;

class JsonQuiz extends QuizAbstract implements QuizInterface
{
    public $quizName = null;

    /**
     * Return a Quiz object based on a filename.
     *
     * @param $filename
     * @static
     * @return QuizInterface | false
     */
    public static function getByFilename($filename)
    {
        if (strpos($filename, '.json') === false) {
            $filename = $filename . '.json';
        }

        if (!file_exists('../data/'.$filename)) {
            return false;
        }

        $contents = file_get_contents('../data/'.$filename);
        $contents = json_decode($contents);

        $obj = new static();
        $obj->name = str_replace('.json', '', basename($filename));
        foreach ($contents as $key => $val) {
            $obj->{$key} = $val;
        }

        return $obj;
    }

    /**
     * Return a Quiz object based on a slug.
     *
     * @param $slug
     * @static
     * @return QuizInterface | false
     */
    public static function getBySlug($slug)
    {
        $list = static::getList();

        foreach ($list as $quiz) {
            if ($quiz->getSlug() == $slug) {
                return $quiz;
            }
        }

        return false;
    }

    /**
     * Returns list of Quiz objects.
     *
     * Searches for files ending with .json in data directory.
     * Each file is appended as Quiz object to the array.
     *
     * @static
     * @return array[] QuizInterface
     */
    public static function getList()
    {
        $list = [];
        foreach (glob("../data/*.json") as $filename) {
            $quiz = static::getByFilename($filename);

            if ($quiz) {
                $list[] = $quiz;
            }
        }

        return $list;
    }

    /**
     * @return int
     */
    public function getMaxScore()
    {
        $max = 0;
        foreach ($this->questions as $question) {
            $answerMax = 0;
            foreach($question->answers as $answer) {
                if ($answer->score > $answerMax) {
                    $answerMax = $answer->score;
                }
            }
            $max += $answerMax;
        }

        return $max;
    }
}


text:
package edu.ucdenver.ccp.nlp.core.annotation;

import java.util.Comparator;

import edu.ucdenver.ccp.nlp.core.annotation.comparison.StrictSpanComparator;

/**
 * A Comparator used for sorting TextAnnotations, e.g. Collections.sort(List<TextAnnotation>,
 * TextAnnotationSortComparator);
 *
 * @author Colorado Computational Pharmacology, UC Denver; ccpsupport@ucdenver.edu
 *
 */
public class TextAnnotationSortComparator implements Comparator<TextAnnotation> {

	public int compare(TextAnnotation ta1, TextAnnotation ta2) {
		return new StrictSpanComparator().compare(ta1.getAggregateSpan(), ta2.getAggregateSpan());
	}

}


text:
// Controller Actions|Scripts|0020
namespace VRTK
{
    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    using Highlighters;

    [System.Serializable]
    public class VRTK_ControllerModelElementPaths
    {
        public string bodyModelPath = "";
        public string triggerModelPath = "";
        public string leftGripModelPath = "";
        public string rightGripModelPath = "";
        public string touchpadModelPath = "";
        public string appMenuModelPath = "";
        public string systemMenuModelPath = "";
    }

    [System.Serializable]
    public struct VRTK_ControllerElementHighlighers
    {
        public VRTK_BaseHighlighter body;
        public VRTK_BaseHighlighter trigger;
        public VRTK_BaseHighlighter gripLeft;
        public VRTK_BaseHighlighter gripRight;
        public VRTK_BaseHighlighter touchpad;
        public VRTK_BaseHighlighter appMenu;
        public VRTK_BaseHighlighter systemMenu;
    }

    /// <summary>
    /// Event Payload
    /// </summary>
    /// <param name="controllerIndex">The index of the controller that was used.</param>
    public struct ControllerActionsEventArgs
    {
        public uint controllerIndex;
    }

    /// <summary>
    /// Event Payload
    /// </summary>
    /// <param name="sender">this object</param>
    /// <param name="e"><see cref="ControllerActionsEventArgs"/></param>
    public delegate void ControllerActionsEventHandler(object sender, ControllerActionsEventArgs e);

    /// <summary>
    /// The Controller Actions script provides helper methods to deal with common controller actions. It deals with actions that can be done to the controller.
    /// </summary>
    /// <remarks>
    /// The highlighting of the controller is defaulted to use the `VRTK_MaterialColorSwapHighlighter` if no other highlighter is applied to the Object.
    /// </remarks>
    /// <example>
    /// `VRTK/Examples/016_Controller_HapticRumble` demonstrates the ability to hide a controller model and make the controller vibrate for a given length of time at a given intensity.
    ///
    /// `VRTK/Examples/035_Controller_OpacityAndHighlighting` demonstrates the ability to change the opacity of a controller model and to highlight specific elements of a controller such as the buttons or even the entire controller model.
    /// </example>
    public class VRTK_ControllerActions : MonoBehaviour
    {
        [Tooltip("A collection of strings that determine the path to the controller model sub elements for identifying the model parts at runtime. If the paths are left empty they will default to the model element paths of the selected SDK Bridge.\n\n"
         + "* The available model sub elements are:\n\n"
         + " * `Body Model Path`: The overall shape of the controller.\n"
         + " * `Trigger Model Path`: The model that represents the trigger button.\n"
         + " * `Grip Left Model Path`: The model that represents the left grip button.\n"
         + " * `Grip Right Model Path`: The model that represents the right grip button.\n"
         + " * `Touchpad Model Path`: The model that represents the touchpad.\n"
         + " * `App Menu Model Path`: The model that represents the application menu button.\n"
         + " * `System Menu Model Path`: The model that represents the system menu button.")]
        public VRTK_ControllerModelElementPaths modelElementPaths;

        [Tooltip("A collection of highlighter overrides for each controller model sub element. If no highlighter override is given then highlighter on the Controller game object is used.\n\n"
         + "* The available model sub elements are:\n\n"
         + " * `Body`: The highlighter to use on the overall shape of the controller.\n"
         + " * `Trigger`: The highlighter to use on the trigger button.\n"
         + " * `Grip Left`: The highlighter to use on the left grip button.\n"
         + " * `Grip Right`: The highlighter to use on the  right grip button.\n"
         + " * `Touchpad`: The highlighter to use on the touchpad.\n"
         + " * `App Menu`: The highlighter to use on the application menu button.\n"
         + " * `System Menu`: The highlighter to use on the system menu button.")]
        public VRTK_ControllerElementHighlighers elementHighlighterOverrides;

        /// <summary>
        /// Emitted when the controller model is toggled to be visible.
        /// </summary>
        public event ControllerActionsEventHandler ControllerModelVisible;

        /// <summary>
        /// Emitted when the controller model is toggled to be invisible.
        /// </summary>
        public event ControllerActionsEventHandler ControllerModelInvisible;

        private bool controllerVisible = true;
        private ushort hapticPulseStrength;
        private uint controllerIndex;
        private ushort maxHapticVibration = 3999;
        private bool controllerHighlighted = false;
        private Dictionary<string, Transform> cachedElements;
        private Dictionary<string, object> highlighterOptions;

        public virtual void OnControllerModelVisible(ControllerActionsEventArgs e)
        {
            if (ControllerModelVisible != null)
            {
                ControllerModelVisible(this, e);
            }
        }

        public virtual void OnControllerModelInvisible(ControllerActionsEventArgs e)
        {
            if (ControllerModelInvisible != null)
            {
                ControllerModelInvisible(this, e);
            }
        }

        /// <summary>
        /// The IsControllerVisible method returns true if the controller is currently visible by whether the renderers on the controller are enabled.
        /// </summary>
        /// <returns>Is true if the controller model has the renderers that are attached to it are enabled.</returns>
        public bool IsControllerVisible()
        {
            return controllerVisible;
        }

        /// <summary>
        /// The ToggleControllerModel method is used to turn on or off the controller model by enabling or disabling the renderers on the object. It will also work for any custom controllers. It should also not disable any objects being held by the controller if they are a child of the controller object.
        /// </summary>
        /// <param name="state">The visibility state to toggle the controller to, `true` will make the controller visible - `false` will hide the controller model.</param>
        /// <param name="grabbedChildObject">If an object is being held by the controller then this can be passed through to prevent hiding the grabbed game object as well.</param>
        public void ToggleControllerModel(bool state, GameObject grabbedChildObject)
        {
            if (!enabled)
            {
                return;
            }

            foreach (MeshRenderer renderer in GetComponentsInChildren<MeshRenderer>())
            {
                if (renderer.gameObject != grabbedChildObject && (grabbedChildObject == null || !renderer.transform.IsChildOf(grabbedChildObject.transform)))
                {
                    renderer.enabled = state;
                }
            }

            foreach (SkinnedMeshRenderer renderer in GetComponentsInChildren<SkinnedMeshRenderer>())
            {
                if (renderer.gameObject != grabbedChildObject && (grabbedChildObject == null || !renderer.transform.IsChildOf(grabbedChildObject.transform)))
                {
                    renderer.enabled = state;
                }
            }

            controllerVisible = state;
            if (state)
            {
                OnControllerModelVisible(SetActionEvent(controllerIndex));
            }
            else
            {
                OnControllerModelInvisible(SetActionEvent(controllerIndex));
            }
        }

        /// <summary>
        /// The SetControllerOpacity method allows the opacity of the controller model to be changed to make the controller more transparent. A lower alpha value will make the object more transparent, such as `0.5f` will make the controller partially transparent where as `0f` will make the controller completely transparent.
        /// </summary>
        /// <param name="alpha">The alpha level to apply to opacity of the controller object. `0f` to `1f`.</param>
        public void SetControllerOpacity(float alpha)
        {
            if (!enabled)
            {
                return;
            }

            alpha = Mathf.Clamp(alpha, 0f, 1f);
            foreach (var renderer in gameObject.GetComponentsInChildren<Renderer>())
            {
                if (alpha < 1f)
                {
                    renderer.material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                    renderer.material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                    renderer.material.SetInt("_ZWrite", 0);
                    renderer.material.DisableKeyword("_ALPHATEST_ON");
                    renderer.material.DisableKeyword("_ALPHABLEND_ON");
                    renderer.material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
                    renderer.material.renderQueue = 3000;
                }
                else
                {
                    renderer.material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                    renderer.material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                    renderer.material.SetInt("_ZWrite", 1);
                    renderer.material.DisableKeyword("_ALPHATEST_ON");
                    renderer.material.DisableKeyword("_ALPHABLEND_ON");
                    renderer.material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                    renderer.material.renderQueue = -1;
                }

                if (renderer.material.HasProperty("_Color"))
                {
                    renderer.material.color = new Color(renderer.material.color.r, renderer.material.color.g, renderer.material.color.b, alpha);
                }
            }
        }

        /// <summary>
        /// The HighlightControllerElement method allows for an element of the controller to have its colour changed to simulate a highlighting effect of that element on the controller. It's useful for being able to draw a user's attention to a specific button on the controller.
        /// </summary>
        /// <param name="element">The element of the controller to apply the highlight to.</param>
        /// <param name="highlight">The colour of the highlight.</param>
        /// <param name="fadeDuration">The duration of fade from white to the highlight colour. Optional parameter defaults to `0f`.</param>
        public void HighlightControllerElement(GameObject element, Color? highlight, float fadeDuration = 0f)
        {
            if (!enabled)
            {
                return;
            }

            var highlighter = element.GetComponent<VRTK_BaseHighlighter>();
            if (highlighter)
            {
                highlighter.Highlight(highlight ?? Color.white, fadeDuration);
            }
        }

        /// <summary>
        /// The UnhighlightControllerElement method is the inverse of the HighlightControllerElement method and resets the controller element to its original colour.
        /// </summary>
        /// <param name="element">The element of the controller to remove the highlight from.</param>
        public void UnhighlightControllerElement(GameObject element)
        {
            if (!enabled)
            {
                return;
            }

            var highlighter = element.GetComponent<VRTK_BaseHighlighter>();
            if (highlighter)
            {
                highlighter.Unhighlight();
            }
        }

        /// <summary>
        /// The ToggleHighlightControllerElement method is a shortcut method that makes it easier to highlight and unhighlight a controller element in a single method rather than using the HighlightControllerElement and UnhighlightControllerElement methods separately.
        /// </summary>
        /// <param name="state">The highlight colour state, `true` will enable the highlight on the given element and `false` will remove the highlight from the given element.</param>
        /// <param name="element">The element of the controller to apply the highlight to.</param>
        /// <param name="highlight">The colour of the highlight.</param>
        /// <param name="duration">The duration of fade from white to the highlight colour.</param>
        public void ToggleHighlightControllerElement(bool state, GameObject element, Color? highlight = null, float duration = 0f)
        {
            if (element)
            {
                if (state)
                {
                    HighlightControllerElement(element.gameObject, highlight ?? Color.white, duration);
                }
                else
                {
                    UnhighlightControllerElement(element.gameObject);
                }
            }
        }

        /// <summary>
        /// The ToggleHighlightTrigger method is a shortcut method that makes it easier to toggle the highlight state of the controller trigger element.
        /// </summary>
        /// <param name="state">The highlight colour state, `true` will enable the highlight on the trigger and `false` will remove the highlight from the trigger.</param>
        /// <param name="highlight">The colour to highlight the trigger with.</param>
        /// <param name="duration">The duration of fade from white to the highlight colour.</param>
        public void ToggleHighlightTrigger(bool state, Color? highlight = null, float duration = 0f)
        {
            if (!state && controllerHighlighted)
            {
                return;
            }
            ToggleHighlightAlias(state, modelElementPaths.triggerModelPath, highlight, duration);
        }

        /// <summary>
        /// The ToggleHighlightGrip method is a shortcut method that makes it easier to toggle the highlight state of the controller grip element.
        /// </summary>
        /// <param name="state">The highlight colour state, `true` will enable the highlight on the grip and `false` will remove the highlight from the grip.</param>
        /// <param name="highlight">The colour to highlight the grip with.</param>
        /// <param name="duration">The duration of fade from white to the highlight colour.</param>
        public void ToggleHighlightGrip(bool state, Color? highlight = null, float duration = 0f)
        {
            if (!state && controllerHighlighted)
            {
                return;
            }
            ToggleHighlightAlias(state, modelElementPaths.leftGripModelPath, highlight, duration);
            ToggleHighlightAlias(state, modelElementPaths.rightGripModelPath, highlight, duration);
        }

        /// <summary>
        /// The ToggleHighlightTouchpad method is a shortcut method that makes it easier to toggle the highlight state of the controller touchpad element.
        /// </summary>
        /// <param name="state">The highlight colour state, `true` will enable the highlight on the touchpad and `false` will remove the highlight from the touchpad.</param>
        /// <param name="highlight">The colour to highlight the touchpad with.</param>
        /// <param name="duration">The duration of fade from white to the highlight colour.</param>
        public void ToggleHighlightTouchpad(bool state, Color? highlight = null, float duration = 0f)
        {
            if (!state && controllerHighlighted)
            {
                return;
            }
            ToggleHighlightAlias(state, modelElementPaths.touchpadModelPath, highlight, duration);
        }

        /// <summary>
        /// The ToggleHighlightApplicationMenu method is a shortcut method that makes it easier to toggle the highlight state of the controller application menu element.
        /// </summary>
        /// <param name="state">The highlight colour state, `true` will enable the highlight on the application menu and `false` will remove the highlight from the application menu.</param>
        /// <param name="highlight">The colour to highlight the application menu with.</param>
        /// <param name="duration">The duration of fade from white to the highlight colour.</param>
        public void ToggleHighlightApplicationMenu(bool state, Color? highlight = null, float duration = 0f)
        {
            if (!state && controllerHighlighted)
            {
                return;
            }
            ToggleHighlightAlias(state, modelElementPaths.appMenuModelPath, highlight, duration);
        }

        /// <summary>
        /// The ToggleHighlighBody method is a shortcut method that makes it easier to toggle the highlight state of the controller body element.
        /// </summary>
        /// <param name="state">The highlight colour state, `true` will enable the highlight on the body and `false` will remove the highlight from the body.</param>
        /// <param name="highlight">The colour to highlight the body with.</param>
        /// <param name="duration">The duration of fade from white to the highlight colour.</param>
        public void ToggleHighlighBody(bool state, Color? highlight = null, float duration = 0f)
        {
            if (!state && controllerHighlighted)
            {
                return;
            }
            ToggleHighlightAlias(state, modelElementPaths.bodyModelPath, highlight, duration);
        }

        /// <summary>
        /// The ToggleHighlightController method is a shortcut method that makes it easier to toggle the highlight state of the entire controller.
        /// </summary>
        /// <param name="state">The highlight colour state, `true` will enable the highlight on the entire controller `false` will remove the highlight from the entire controller.</param>
        /// <param name="highlight">The colour to highlight the entire controller with.</param>
        /// <param name="duration">The duration of fade from white to the highlight colour.</param>
        public void ToggleHighlightController(bool state, Color? highlight = null, float duration = 0f)
        {
            controllerHighlighted = state;
            ToggleHighlightTrigger(state, highlight, duration);
            ToggleHighlightGrip(state, highlight, duration);
            ToggleHighlightTouchpad(state, highlight, duration);
            ToggleHighlightApplicationMenu(state, highlight, duration);
            ToggleHighlightAlias(state, modelElementPaths.systemMenuModelPath, highlight, duration);
            ToggleHighlightAlias(state, modelElementPaths.bodyModelPath, highlight, duration);
        }

        /// <summary>
        /// The TriggerHapticPulse/1 method calls a single haptic pulse call on the controller for a single tick.
        /// </summary>
        /// <param name="strength">The intensity of the rumble of the controller motor. `0` to `3999`.</param>
        public void TriggerHapticPulse(ushort strength)
        {
            if (!enabled)
            {
                return;
            }

            hapticPulseStrength = (strength <= maxHapticVibration ? strength : maxHapticVibration);
            VRTK_SDK_Bridge.HapticPulseOnIndex(controllerIndex, hapticPulseStrength);
        }

        /// <summary>
        /// The TriggerHapticPulse/3 method calls a haptic pulse for a specified amount of time rather than just a single tick. Each pulse can be separated by providing a `pulseInterval` to pause between each haptic pulse.
        /// </summary>
        /// <param name="strength">The intensity of the rumble of the controller motor. `0` to `3999`.</param>
        /// <param name="duration">The length of time the rumble should continue for.</param>
        /// <param name="pulseInterval">The interval to wait between each haptic pulse.</param>
        public void TriggerHapticPulse(ushort strength, float duration, float pulseInterval)
        {
            if (!enabled)
            {
                return;
            }

            hapticPulseStrength = (strength <= maxHapticVibration ? strength : maxHapticVibration);
            StartCoroutine(HapticPulse(duration, hapticPulseStrength, pulseInterval));
        }

        /// <summary>
        /// The InitaliseHighlighters method sets up the highlighters on the controller model.
        /// </summary>
        public void InitaliseHighlighters()
        {

            highlighterOptions = new Dictionary<string, object>();
            highlighterOptions.Add("resetMainTexture", true);
            VRTK_BaseHighlighter objectHighlighter = Utilities.GetActiveHighlighter(gameObject);

            if (objectHighlighter == null)
            {
                objectHighlighter = gameObject.AddComponent<VRTK_MaterialColorSwapHighlighter>();
            }

            objectHighlighter.Initialise(null, highlighterOptions);
            AddHighlighterToElement(GetElementTransform(VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.ApplicationMenu)), objectHighlighter, elementHighlighterOverrides.appMenu);
            AddHighlighterToElement(GetElementTransform(VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.Body)), objectHighlighter, elementHighlighterOverrides.body);
            AddHighlighterToElement(GetElementTransform(VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.GripLeft)), objectHighlighter, elementHighlighterOverrides.gripLeft);
            AddHighlighterToElement(GetElementTransform(VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.GripRight)), objectHighlighter, elementHighlighterOverrides.gripRight);
            AddHighlighterToElement(GetElementTransform(VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.SystemMenu)), objectHighlighter, elementHighlighterOverrides.systemMenu);
            AddHighlighterToElement(GetElementTransform(VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.Touchpad)), objectHighlighter, elementHighlighterOverrides.touchpad);
            AddHighlighterToElement(GetElementTransform(VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.Trigger)), objectHighlighter, elementHighlighterOverrides.trigger);
        }

        private void Awake()
        {
            gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");
            cachedElements = new Dictionary<string, Transform>();

            var controllerHand = VRTK_DeviceFinder.GetControllerHand(gameObject);

            if (modelElementPaths.bodyModelPath.Trim() == "")
            {
                modelElementPaths.bodyModelPath = VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.Body, controllerHand);
            }
            if (modelElementPaths.triggerModelPath.Trim() == "")
            {
                modelElementPaths.triggerModelPath = VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.Trigger, controllerHand);
            }
            if (modelElementPaths.leftGripModelPath.Trim() == "")
            {
                modelElementPaths.leftGripModelPath = VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.GripLeft, controllerHand);
            }
            if (modelElementPaths.rightGripModelPath.Trim() == "")
            {
                modelElementPaths.rightGripModelPath = VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.GripRight, controllerHand);
            }
            if (modelElementPaths.touchpadModelPath.Trim() == "")
            {
                modelElementPaths.touchpadModelPath = VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.Touchpad, controllerHand);
            }
            if (modelElementPaths.appMenuModelPath.Trim() == "")
            {
                modelElementPaths.appMenuModelPath = VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.ApplicationMenu, controllerHand);
            }
            if (modelElementPaths.systemMenuModelPath.Trim() == "")
            {
                modelElementPaths.systemMenuModelPath = VRTK_SDK_Bridge.GetControllerElementPath(SDK_Base.ControllerElelements.SystemMenu, controllerHand);
            }
        }

        private void OnEnable()
        {
            StartCoroutine(WaitForModel());
        }

        private void Update()
        {
            controllerIndex = VRTK_DeviceFinder.GetControllerIndex(gameObject);
        }

        private IEnumerator WaitForModel()
        {
            while (GetElementTransform(modelElementPaths.bodyModelPath) == null)
            {
                yield return null;
            }

            InitaliseHighlighters();
        }

        private void AddHighlighterToElement(Transform element, VRTK_BaseHighlighter parentHighlighter, VRTK_BaseHighlighter overrideHighlighter)
        {
            if (element)
            {
                var highlighter = (overrideHighlighter != null ? overrideHighlighter : parentHighlighter);
                VRTK_BaseHighlighter clonedHighlighter = (VRTK_BaseHighlighter)Utilities.CloneComponent(highlighter, element.gameObject);
                clonedHighlighter.Initialise(null, highlighterOptions);
            }
        }

        private IEnumerator HapticPulse(float duration, ushort hapticPulseStrength, float pulseInterval)
        {
            if (pulseInterval <= 0)
            {
                yield break;
            }

            while (duration > 0)
            {
                VRTK_SDK_Bridge.HapticPulseOnIndex(controllerIndex, hapticPulseStrength);
                yield return new WaitForSeconds(pulseInterval);
                duration -= pulseInterval;
            }
        }

        private IEnumerator CycleColor(Material material, Color startColor, Color endColor, float duration)
        {
            var elapsedTime = 0f;
            while (elapsedTime <= duration)
            {
                elapsedTime += Time.deltaTime;
                if (material.HasProperty("_Color"))
                {
                    material.color = Color.Lerp(startColor, endColor, (elapsedTime / duration));
                }
                yield return null;
            }
        }

        private Transform GetElementTransform(string path)
        {
            if (cachedElements == null)
            {
                return null;
            }

            if (!cachedElements.ContainsKey(path) || cachedElements[path] == null)
            {
                cachedElements[path] = transform.Find(path);
            }
            return cachedElements[path];
        }

        private void ToggleHighlightAlias(bool state, string transformPath, Color? highlight, float duration = 0f)
        {
            var element = GetElementTransform(transformPath);
            if (element)
            {
                ToggleHighlightControllerElement(state, element.gameObject, highlight, duration);
            }
        }

        private ControllerActionsEventArgs SetActionEvent(uint index)
        {
            ControllerActionsEventArgs e;
            e.controllerIndex = index;
            return e;
        }
    }
}


text:
package org.camunda.community.mockito;

import org.camunda.bpm.engine.AuthorizationService;
import org.camunda.bpm.engine.CaseService;
import org.camunda.bpm.engine.ExternalTaskService;
import org.camunda.bpm.engine.FilterService;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.IdentityService;
import org.camunda.bpm.engine.ManagementService;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.community.mockito.query.ActivityStatisticsQueryMock;
import org.camunda.community.mockito.query.AuthorizationQueryMock;
import org.camunda.community.mockito.query.BatchQueryMock;
import org.camunda.community.mockito.query.BatchStatisticsQueryMock;
import org.camunda.community.mockito.query.CaseDefinitionQueryMock;
import org.camunda.community.mockito.query.CaseExecutionQueryMock;
import org.camunda.community.mockito.query.CaseInstanceQueryMock;
import org.camunda.community.mockito.query.DecisionDefinitionQueryMock;
import org.camunda.community.mockito.query.DeploymentQueryMock;
import org.camunda.community.mockito.query.DeploymentStatisticsQueryMock;
import org.camunda.community.mockito.query.EventSubscriptionQueryMock;
import org.camunda.community.mockito.query.ExecutionQueryMock;
import org.camunda.community.mockito.query.ExternalTaskQueryMock;
import org.camunda.community.mockito.query.FilterQueryMock;
import org.camunda.community.mockito.query.GroupQueryMock;
import org.camunda.community.mockito.query.HistoricActivityInstanceQueryMock;
import org.camunda.community.mockito.query.HistoricActivityStatisticsQueryMock;
import org.camunda.community.mockito.query.HistoricBatchQueryMock;
import org.camunda.community.mockito.query.HistoricCaseActivityInstanceQueryMock;
import org.camunda.community.mockito.query.HistoricCaseInstanceQueryMock;
import org.camunda.community.mockito.query.HistoricDecisionInstanceQueryMock;
import org.camunda.community.mockito.query.HistoricDetailQueryMock;
import org.camunda.community.mockito.query.HistoricIdentityLinkLogQueryMock;
import org.camunda.community.mockito.query.HistoricIncidentQueryMock;
import org.camunda.community.mockito.query.HistoricJobLogQueryMock;
import org.camunda.community.mockito.query.HistoricProcessInstanceQueryMock;
import org.camunda.community.mockito.query.HistoricTaskInstanceQueryMock;
import org.camunda.community.mockito.query.HistoricVariableInstanceQueryMock;
import org.camunda.community.mockito.query.IncidentQueryMock;
import org.camunda.community.mockito.query.JobDefinitionQueryMock;
import org.camunda.community.mockito.query.JobQueryMock;
import org.camunda.community.mockito.query.ProcessDefinitionQueryMock;
import org.camunda.community.mockito.query.ProcessDefinitionStatisticsQueryMock;
import org.camunda.community.mockito.query.ProcessInstanceQueryMock;
import org.camunda.community.mockito.query.TaskQueryMock;
import org.camunda.community.mockito.query.TenantQueryMock;
import org.camunda.community.mockito.query.UserOperationLogQueryMock;
import org.camunda.community.mockito.query.UserQueryMock;
import org.camunda.community.mockito.query.VariableInstanceQueryMock;

@SuppressWarnings("unused")
public enum QueryMocks {
  ;

  public static FilterQueryMock mockFilterQuery(final FilterService serviceMock) {
    return new FilterQueryMock().forService(serviceMock);
  }

  public static TaskQueryMock mockTaskQuery(final TaskService serviceMock) {
    return new TaskQueryMock().forService(serviceMock);
  }

  public static CaseInstanceQueryMock mockCaseInstanceQuery(final CaseService serviceMock) {
    return new CaseInstanceQueryMock().forService(serviceMock);
  }

  public static CaseExecutionQueryMock mockCaseExecutionQuery(final CaseService serviceMock) {
    return new CaseExecutionQueryMock().forService(serviceMock);
  }

  public static ExecutionQueryMock mockExecutionQuery(final RuntimeService serviceMock) {
    return new ExecutionQueryMock().forService(serviceMock);
  }

  public static ProcessInstanceQueryMock mockProcessInstanceQuery(final RuntimeService serviceMock) {
    return new ProcessInstanceQueryMock().forService(serviceMock);
  }

  public static IncidentQueryMock mockIncidentQuery(final RuntimeService serviceMock) {
    return new IncidentQueryMock().forService(serviceMock);
  }

  public static EventSubscriptionQueryMock mockEventSubscriptionQuery(final RuntimeService serviceMock) {
    return new EventSubscriptionQueryMock().forService(serviceMock);
  }

  public static VariableInstanceQueryMock mockVariableInstanceQuery(final RuntimeService serviceMock) {
    return new VariableInstanceQueryMock().forService(serviceMock);
  }

  public static ProcessDefinitionQueryMock mockProcessDefinitionQuery(final RepositoryService serviceMock) {
    return new ProcessDefinitionQueryMock().forService(serviceMock);
  }

  public static CaseDefinitionQueryMock mockCaseDefinitionQuery(final RepositoryService serviceMock) {
    return new CaseDefinitionQueryMock().forService(serviceMock);
  }

  public static DecisionDefinitionQueryMock mockDecisionDefinitionQuery(final RepositoryService serviceMock) {
    return new DecisionDefinitionQueryMock().forService(serviceMock);
  }

  public static DeploymentQueryMock mockDeploymentQuery(final RepositoryService serviceMock) {
    return new DeploymentQueryMock().forService(serviceMock);
  }

  public static HistoricIdentityLinkLogQueryMock mockHistoricIdentityLinkLogQuery(final HistoryService serviceMock) {
    return new HistoricIdentityLinkLogQueryMock().forService(serviceMock);
  }

  public static HistoricProcessInstanceQueryMock mockHistoricProcessInstanceQuery(final HistoryService serviceMock) {
    return new HistoricProcessInstanceQueryMock().forService(serviceMock);
  }

  public static HistoricActivityInstanceQueryMock mockHistoricActivityInstanceQuery(final HistoryService serviceMock) {
    return new HistoricActivityInstanceQueryMock().forService(serviceMock);
  }

  public static HistoricActivityStatisticsQueryMock mockHistoricActivityStatisticsQuery(final HistoryService serviceMock) {
    return new HistoricActivityStatisticsQueryMock().forService(serviceMock);
  }

  public static HistoricVariableInstanceQueryMock mockHistoricVariableInstanceQuery(final HistoryService serviceMock) {
    return new HistoricVariableInstanceQueryMock().forService(serviceMock);
  }

  public static HistoricCaseActivityInstanceQueryMock mockHistoricCaseActivityInstanceQuery(final HistoryService serviceMock) {
    return new HistoricCaseActivityInstanceQueryMock().forService(serviceMock);
  }

  public static HistoricDecisionInstanceQueryMock mockHistoricDecisionInstanceQuery(final HistoryService serviceMock) {
    return new HistoricDecisionInstanceQueryMock().forService(serviceMock);
  }

  public static HistoricTaskInstanceQueryMock mockHistoricTaskInstanceQuery(final HistoryService serviceMock) {
    return new HistoricTaskInstanceQueryMock().forService(serviceMock);
  }

  public static HistoricDetailQueryMock mockHistoricDetailQuery(final HistoryService serviceMock) {
    return new HistoricDetailQueryMock().forService(serviceMock);
  }

  public static UserOperationLogQueryMock mockUserOperationLogQuery(final HistoryService serviceMock) {
    return new UserOperationLogQueryMock().forService(serviceMock);
  }

  public static HistoricIncidentQueryMock mockHistoricIncidentQuery(final HistoryService serviceMock) {
    return new HistoricIncidentQueryMock().forService(serviceMock);
  }

  public static HistoricCaseInstanceQueryMock mockHistoricCaseInstanceQuery(final HistoryService serviceMock) {
    return new HistoricCaseInstanceQueryMock().forService(serviceMock);
  }

  public static HistoricJobLogQueryMock mockHistoricJobLogQuery(final HistoryService serviceMock) {
    return new HistoricJobLogQueryMock().forService(serviceMock);
  }

  public static HistoricBatchQueryMock mockHistoricBatchQuery(final HistoryService serviceMock) {
    return new HistoricBatchQueryMock().forService(serviceMock);
  }

  public static UserQueryMock mockUserQuery(final IdentityService serviceMock) {
    return new UserQueryMock().forService(serviceMock);
  }

  public static GroupQueryMock mockGroupQuery(final IdentityService serviceMock) {
    return new GroupQueryMock().forService(serviceMock);
  }

  public static TenantQueryMock mockTenantQuery(final IdentityService serviceMock) {
    return new TenantQueryMock().forService(serviceMock);
  }

  public static JobQueryMock mockJobQuery(final ManagementService serviceMock) {
    return new JobQueryMock().forService(serviceMock);
  }

  public static BatchQueryMock mockBatchQuery(final ManagementService serviceMock) {
    return new BatchQueryMock().forService(serviceMock);
  }

  public static ProcessDefinitionStatisticsQueryMock mockProcessDefinitionStatisticsQuery(final ManagementService serviceMock) {
    return new ProcessDefinitionStatisticsQueryMock().forService(serviceMock);
  }

  public static JobDefinitionQueryMock mockJobDefinitionQuery(final ManagementService serviceMock) {
    return new JobDefinitionQueryMock().forService(serviceMock);
  }

  public static DeploymentStatisticsQueryMock mockDeploymentStatisticsQuery(final ManagementService serviceMock) {
    return new DeploymentStatisticsQueryMock().forService(serviceMock);
  }

  public static ActivityStatisticsQueryMock mockActivityStatisticsQuery(final ManagementService serviceMock) {
    return new ActivityStatisticsQueryMock().forService(serviceMock);
  }

  public static BatchStatisticsQueryMock mockBatchStatisticsQuery(final ManagementService serviceMock) {
    return new BatchStatisticsQueryMock().forService(serviceMock);
  }

  public static AuthorizationQueryMock mockAuthorizationQuery(final AuthorizationService serviceMock) {
    return new AuthorizationQueryMock().forService(serviceMock);
  }

  public static ExternalTaskQueryMock mockExternalTaskQuery(final ExternalTaskService serviceMock) {
    return new ExternalTaskQueryMock().forService(serviceMock);
  }

}


text:
<?xml version="1.0"?>
<assembly>
    <id></id>
    <formats>
        <format>zip</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    <dependencySets>
        <dependencySet>
            <outputDirectory>/</outputDirectory>
            <useProjectArtifact>true</useProjectArtifact>
            <useTransitiveDependencies>false</useTransitiveDependencies>
            <excludes>
                <exclude>org.elasticsearch:elasticsearch</exclude>
            </excludes>
        </dependencySet>
    </dependencySets>
    <files>
		<file>
	      <outputDirectory></outputDirectory>
	      <source>${project.basedir}/src/main/resources/plugin-descriptor.properties</source>
          <filtered>true</filtered>
	    </file>
  	</files>
</assembly>


text:
from django.db import models

class ForumThreadPostQuerySet(models.query.QuerySet):

    def iterator(self):
        queryset = super().iterator()
        reverse = self._posts_manager_params["reverse"]
        thread = self._posts_manager_params["thread"]
        if not reverse:
            yield thread
        yield from queryset
        if reverse:
            yield thread

    def _clone(self, *args, **kwargs):
        kwargs["_posts_manager_params"] = self._posts_manager_params
        return super()._clone(*args, **kwargs)

class ForumThreadManager(models.Manager):

    def posts(self, thread, reverse=False):
        from .models import ForumReply  # @@@ this seems like a code smell
        queryset = ForumThreadPostQuerySet(ForumReply, using=self._db)
        queryset._posts_manager_params = {
            "reverse": reverse,
            "thread": thread,
        }
        queryset = queryset.filter(thread=thread)
        queryset = queryset.select_related("thread")
        queryset = queryset.order_by("{}created".format(reverse and "-" or ""))
        return queryset


text:
<?php
/**
 * The template for displaying all single posts and attachments
 *
 * @package WordPress
 * @subpackage mmoser
 * @since mmoser
 */
get_header();
?>

<a href="<?php echo get_permalink(); ?>" class="active">Home Block

 ← back

<?php the_title() ?>

        	        <?php
        			// Start the loop.
        			while ( have_posts() ) : the_post();
        				/*
        				 * Include the post format-specific template for the content. If you want to
        				 * use this in a child theme, then include a file called called content-___.php
        				 * (where ___ is the post format) and that will be used instead.
        				 */
        				the_content();
        			// End the loop.
        			endwhile;
        			?>

<?php get_footer(); ?>


text:
using System;

namespace Prometheus.Parser.Executors.Attributes
{
    /// <summary>
    /// Base class for attributes that identify executable methods.
    /// </summary>
    [AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public abstract class ExecuteAttribute : Attribute
    {
        /// <summary>
        /// Returns an identifier of the kind of method the derived attribute is defining.
        /// </summary>
        /// <typeparam name="T">Must match the property type in the derived class.</typeparam>
        /// <returns>The identifier</returns>
        public abstract T GetExecutorType<T>();
    }
}


text:
categories: []
comments: true
layout: attachment
published: false
status: inherit
tags: []
title: "Feliz Navidad"
type: attachment
---


text:
#include <algorithm>
#include <cassert>
#include <cstring>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <algorithm>

#include <zorba/util/base64_util.h>
#include <zorba/config.h>
#include <zorba/diagnostic_list.h>
#include <zorba/error.h>
#include <zorba/item.h>
#include <zorba/item_factory.h>
#include <zorba/util/transcode_stream.h>
#include <zorba/xmldatamanager.h>
#include <zorba/xquery_exception.h>
#include <zorba/xquery_exception.h>
#include <zorba/xquery_functions.h>
#include <zorba/internal/unique_ptr.h>

#include "util/curl_streambuf.h"

#include "http_response_parser.h"
#include "http_request_handler.h"

namespace zorba {

namespace http_client {

void parse_content_type( std::string const &media_type, std::string *mime_type,
                                std::string *charset )
{
  std::string::size_type start = 0;
  std::string::size_type end = media_type.find( ';' );
  *mime_type = media_type.substr( start, end - start );

  if ( std::strncmp( mime_type->c_str(), "text/", 5 ) == 0 ) {
    //
    // RFC 2616: "Hypertext Transfer Protocol -- HTTP/1.1," section 3.7.1,
    // "Canonicalization and Text Defaults":
    //
    //    The "charset" parameter is used with some media types to define the
    //    character set (section 3.4) of the data. When no explicit charset
    //    parameter is provided by the sender, media subtypes of the "text"
    //    type are defined to have a default charset value of "ISO-8859-1" when
    //    received via HTTP.
    //
    *charset = "ISO-8859-1";
  } else
    charset->clear();

  //media-type = type "/" subtype *( ";" parameter )
  //type = token
  //subtype = token
  //parameter = attribute "=" value
  //attribute = token
  //value = token | quoted-string
  //quoted-string  = ( <"> *(qdtext) <"> )
  //qdtext = <any TEXT except <">>
  std::vector<std::string> fields;
  while ((end = media_type.find(';',start)) != std::string::npos)
  {
    fields.push_back(media_type.substr(start,end-start));
    start = end+1;
  }
  fields.push_back(media_type.substr(start));

  std::vector<std::string>::iterator it = fields.begin();
  for (;it!=fields.end();++it)
  {
    std::string& field =*it;
    std::transform(field.begin(), field.end(), field.begin(), ::tolower);
    field.erase(remove_if(field.begin(), field.end(), ::isspace), field.end());
    if ((start = field.find("charset=")) != std::string::npos)
    {
      std::string t = field.substr(start + 8);
      if (!t.empty())
      {
        if (t[0] == '"' && t[t.length()-1] == '"')
        {
          t.erase( 0, 1 );
          t.erase(t.length() -1, 1);
        }
        *charset = t;
      }
    }
  }
}

  HttpResponseParser::HttpResponseParser(HttpResponseHandler& aHandler, CURL* aCurl,
                                         ErrorThrower& aErrorThrower,
                                         std::string aOverridenContentType,
                                         bool aStatusOnly) :
  theHandler(aHandler),
  theCurl(aCurl),
  theErrorThrower(aErrorThrower),
  theStatus(-1),
  theStreamBuffer(0),
  theInsideRead(false),
  theOverridenContentType(aOverridenContentType),
  theStatusOnly(aStatusOnly),
  theSelfContained(true)
  {
    registerHandler();
    theStreamBuffer = new zorba::curl::streambuf(theCurl);
  }

  HttpResponseParser::~HttpResponseParser()
  {
    delete theStreamBuffer;
  }

  CURLcode HttpResponseParser::parse()
  {
    theStreamBuffer->set_listener(this);
    theHandler.begin();
    bool lStatusAndMesssageParsed = false;
    CURLcode lCurlCode = theStreamBuffer->curl_multi_info_read(false);
    if (lCurlCode)
      return lCurlCode;

    if (!theStatusOnly)
    {
      if (!theOverridenContentType.empty())
      {
        parse_content_type(
          theOverridenContentType, &theCurrentContentType, &theCurrentCharset
        );
      }

      std::unique_ptr<std::istream> lStream;
      try
      {
        if ( !theCurrentCharset.empty() &&
             transcode::is_necessary( theCurrentCharset.c_str() ) )
        {
          lStream.reset(
            new transcode::stream<std::istream>(
              theCurrentCharset.c_str(), theStreamBuffer
            )
          );
        }
        else
          lStream.reset(new std::istream(theStreamBuffer));
      }
      catch ( std::invalid_argument const &e )
      {
        theErrorThrower.raiseException("http://www.zorba-xquery.com/errors", "ZXQP0006", e.what());
      }

      Item lItem;
      if (theCurrentContentType == "application/xml" ||
          theCurrentContentType == "application/xml-external-parsed-entity" ||
          theCurrentContentType == "application/json" ||
          theCurrentContentType == "application/x-javascript" ||
          theCurrentContentType == "text/javascript" ||
          theCurrentContentType == "text/x-javascript" ||
          theCurrentContentType == "text/x-json" ||
          (
            theCurrentContentType.length() > 5 &&
              (theCurrentContentType.find("+xml") == theCurrentContentType.size()-4 ||
              theCurrentContentType.find("+json") == theCurrentContentType.size()-5)
          ) ||
          theCurrentContentType.find("text/") == 0)
      {
        lItem = createTextItem(lStream.release());
      }
      else
      {
        lItem = createBase64Item(*lStream.get());
      }

      if (!lItem.isNull())
      {
        std::string empty;
        theHandler.any(lItem, empty);
      }

      if (!theInsideRead)
      {
        theHandler.beginResponse(theStatus, theMessage);
        lStatusAndMesssageParsed = true;
      }
      else
        theHandler.endBody();
    }

    if (!theInsideRead)
    {
      if (!lStatusAndMesssageParsed)
        theHandler.beginResponse(theStatus, theMessage);

      for (std::vector<std::pair<std::string, std::string> >::iterator i = theHeaders.begin();
          i != theHeaders.end(); ++i) {
        theHandler.header(i->first, i->second);
      }
    }

    theHandler.endResponse();
    theHandler.end();
    return lCurlCode;
  }

  void HttpResponseParser::curl_read(void*,size_t)
  {
    if (theInsideRead) {
      return;
    }
    theInsideRead = true;
    theHandler.beginResponse(theStatus, theMessage);
    for ( headers_type::const_iterator
          lIter = theHeaders.begin(); lIter != theHeaders.end(); ++lIter) {
      theHandler.header(lIter->first, lIter->second);
    }
    if (!theStatusOnly)
      theHandler.beginBody(theCurrentContentType, "", NULL);
  }

  void HttpResponseParser::registerHandler()
  {
    curl_easy_setopt(theCurl, CURLOPT_HEADERFUNCTION, &curl_headerfunction);
    curl_easy_setopt(theCurl, CURLOPT_HEADERDATA, this);
  }

  size_t HttpResponseParser::curl_headerfunction( void *ptr, size_t size,
                                                  size_t nmemb, void *data )
  {
    size_t lSize = size*nmemb;
    size_t lResult = lSize;
    HttpResponseParser* lParser = static_cast<HttpResponseParser*>(data);
    if (lParser->theInsideRead) {
      lParser->theHandler.endBody();
      lParser->theInsideRead = false;
    }
    const char* lDataChar = (const char*) ptr;
    while (lSize != 0 && (lDataChar[lSize - 1] == 10
          || lDataChar[lSize - 1] == 13)) {
      lSize--;
    }
    if (lSize == 0) {
      return lResult;
    }
    std::string lData(lDataChar, lSize);

    if (lData.find("HTTP") == 0) {
      lParser->parseStatusAndMessage(lData);
      return lResult;
    }
    std::string::size_type lPos = lData.find(':');
    if (lPos == std::string::npos) {
      return lResult;
    }
    std::string lName = lData.substr(0, lPos);
    std::string lValue = lData.substr(lPos + 2);
    {
      std::string::size_type lPosition = lValue.size() - 1;
      while (true) {
        if (lPosition != std::string::npos) {
          break;
        }
        if (lValue[lPosition] == '\n' || lValue[lPosition] == '\r') {
          --lPosition;
        } else {
          break;
        }
      }
      lValue = lValue.substr(0, lPosition + 1);
    }
    String lNameS = fn::lower_case( lName );
    if (lNameS == "content-type") {
      parse_content_type(
        lValue, &lParser->theCurrentContentType, &lParser->theCurrentCharset
      );
    } else if (lNameS == "content-id") {
      lParser->theId = lValue;
    } else if (lNameS == "content-description") {
      lParser->theDescription = lValue;
    }
    lParser->theHeaders.push_back(
      std::pair<std::string, std::string>(lName, lValue));
    return lResult;
  }

  void HttpResponseParser::parseStatusAndMessage(std::string const &aHeader)
  {
    std::string::size_type lPos = aHeader.find(' ');
    assert(lPos != std::string::npos);
    std::string lStatus = aHeader.substr(lPos, aHeader.find(' ', lPos + 1));
    theMessage = aHeader.substr(aHeader.find(' ', lPos + 1) + 1);
    {
      std::string::size_type lPosition = theMessage.size() - 1;
      while (true) {
        if (lPosition != std::string::npos) {
          break;
        }
        if (theMessage[lPosition] == '\n' || theMessage[lPosition] == '\r') {
          --lPosition;
        } else {
          break;
        }
      }
      theMessage = theMessage.substr(0, lPosition + 1);
    }
    std::stringstream lStream(lStatus);
    lStream >> theStatus;
    // everything that is not a valid http status is an error
    if (theStatus < 100) {
      theErrorThrower.raiseException("HTTP", "An HTTP error occurred. The returned status is: " + lStatus);
    }
  }

  static void streamReleaser(std::istream* aStream)
  {
    if (!aStream)
      return;

    // This istream contains our curl stream buffer, so we have to delete it too
    std::streambuf *const sbuf = aStream->rdbuf();
    if ( transcode::streambuf *tbuf =
          dynamic_cast<transcode::streambuf*>( sbuf ) )
      delete tbuf->orig_streambuf();
    else
      delete sbuf;
    delete aStream;
  }

  zorba::Item HttpResponseParser::createTextItem(std::istream* aStream)
  {
    ItemFactory* lFactory = Zorba::getInstance(0)->getItemFactory();

    // When we create a StreamableString, memory ownership gets very convoluted
    // because the StreamableString object has a longer lifecycle than the
    // iterator which creates it. The StreamableString object depends on its
    // istream, which in turn depends on its read buffer. For us, the read
    // buffer in turn depends on the HttpResponseParser (this object) because
    // it is registered as the "informer" (callback object) for
    // theStreamBuffer. Therefore, this HttpResponseParser object is no longer
    // "self-contained". We delegate ownership of ourself to theStreamBuffer
    // and mark ourselves as no longer being self-contained.
    theStreamBuffer->set_listener(this, true);
    theSelfContained = false;

    // The ownership of theStreamBuffer, in turn, is delegated to the
    // StreamableString object (via streamReleaser, which will free the
    // istream's rdbuf).
    theStreamBuffer = NULL;
    return lFactory->createStreamableString(*aStream, &streamReleaser, false);
  }

  zorba::Item HttpResponseParser::createBase64Item( std::istream& aStream )
  {
    ItemFactory* lFactory = Zorba::getInstance(0)->getItemFactory();
    // TODO: once a proper streaming implementation is in place this can be
    // changed. This required a Base64 encoding stream since the item factory
    // work only builds base64binary and assumes the data is already encoded.
    String lEncoded;
    zorba::base64::encode(aStream, &lEncoded);
    return lFactory->createBase64Binary(lEncoded.data(), lEncoded.size(), true);
  }

} // namespace http_client
} // namespace zorba
/* vim:set et sw=2 ts=2: */


text:
Library and examples for BLEPad

Please see [the wiki](http://wiki.aprbrother.com/wiki/BLEPad) for more information.


text:
@interface SKMagnificationLoupe : UIView {
    UIView* _clippingContainer;
    NSArray* _imageViews;
    CGSize _imageSize;
    CGPoint _focusPoint;
}

-(void)magnifyImages:(NSArray*)images toSize:(CGSize)size focusPoint:(CGPoint)focusPoint;

@end


text:
from twisted.internet.defer import inlineCallbacks

from vumi.dispatchers.tests.helpers import DummyDispatcher
from vumi.tests.helpers import VumiTestCase, MessageHelper

from dispatchers import TransportMetadataRouter

class TestTransportMetadataRouter(VumiTestCase):

    @inlineCallbacks
    def setUp(self):
        self.config = {
            'exposed_names': ['app'],
            'transport_names': [
                'transport',
                'transport-priority'],
            'transport_mappings':{
                'priority': 'transport-priority'},
            'transport_fallback': 'transport'
            }
        self.dispatcher = DummyDispatcher(self.config)
        self.router = TransportMetadataRouter(self.dispatcher, self.config)
        yield self.router.setup_routing()
        self.msg_helper = self.add_helper(MessageHelper())

    def test_inbound_message(self):
        msg1 = self.msg_helper.make_inbound(
            "in", transport_name='transport')
        self.router.dispatch_inbound_message(msg1)

        msg2 = self.msg_helper.make_inbound(
            "in", transport_name='transport-priority')
        self.router.dispatch_inbound_message(msg2)

        publishers = self.dispatcher.exposed_publisher
        self.assertEqual(publishers['app'].msgs, [msg1, msg2])

    def test_inbound_event(self):
        msg = self.msg_helper.make_ack(transport_name='transport')
        self.router.dispatch_inbound_event(msg)
        event_publishers = self.dispatcher.exposed_event_publisher
        self.assertEqual(event_publishers['app'].msgs, [msg])

    def test_outbound_message_routing_with_priority_transport_default(self):
        msg = self.msg_helper.make_outbound(
            content="hello outbound msg",
            from_addr='shortcode',
            transport_name='app',
            transport_type='sms')
        self.router.dispatch_outbound_message(msg)

        publishers = self.dispatcher.transport_publisher
        self.assertEqual(publishers['transport'].msgs, [msg])

    def test_outbound_message_routing_with_priority_defined(self):
        msg = self.msg_helper.make_outbound(
            content="hello outbound msg",
            from_addr='shortcode',
            transport_name='app',
            transport_type='sms',
            #priority 'prioritized' is defined
            transport_metadata={'priority':'prioritized'})
        self.router.dispatch_outbound_message(msg)

        publishers = self.dispatcher.transport_publisher
        self.assertEqual(publishers['transport-priority'].msgs, [msg])

    def test_outbound_message_routing_with_priority_undefined(self):
        msg = self.msg_helper.make_outbound(
            content="hello outbound msg",
            from_addr='shortcode',
            transport_name='app',
            transport_type='sms',
            # priority 2 is undefined
            transport_metadata={'priority':'2'})
        self.router.dispatch_outbound_message(msg)

        publishers = self.dispatcher.transport_publisher
        self.assertEqual(publishers['transport-priority'].msgs, [msg])


text:
<!DOCTYPE html>
<html class="no-js" lang="en">
	<head>
		<meta charset="utf-8">
		<meta http-equiv="x-ua-compatible" content="ie=edge">
		<title>BOUNTY HUNTING ONLINE</title>
		<meta name="description" content="">
		<meta name="viewport" content="width=device-width, initial-scale=1">

		<!--<link rel="stylesheet" href="css/normalize.css">-->
		<link rel="stylesheet" href="css/main.css">
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
	</head>

	<body>

		<!--Scripts at the bottom so to not delay page load-->
		<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'></script>
		<script src="https://cdn.firebase.com/js/client/2.4.0/firebase.js"></script>
		<script src="js/main.js"></script>

	</body>
</html>


text:
package cove

import (
	"os"
	"testing"
)

func TestToSingleAndMultiGoPath(t *testing.T) {
	oldPath := os.Getenv("GOPATH")
	defer os.Setenv("GOPATH", oldPath)

	os.Setenv("GOPATH", "/foo/bar:/local/foo/bar")
	first := GetFirstGoPath()
	if first != "/foo/bar" {
		t.Errorf("Didn't get the correct to path from to for a multi-path: %s", first)
	}
}


text:
%Created by jPicEdt 1.x
%Standard LaTeX format (emulated lines)
%Mon Mar 07 17:07:03 MSK 2005
\begin{figure}
\centering

\input ./part1/interaction/pic7.tex

\caption{Взаимодействие электромагнитного поля резонатора $F$ с
  резервуаром атомов $R$, находящихся при температуре $T$}
\label{figPart1Ch2_7}
\end{figure}


text:
(function () {
	'use strict';

	// WRITE YOUR JAVASCRIPT CODE HERE
}());


text:
class Nodectl::Context
  attr_reader :recipe
  attr_reader :service

  def initialize(recipe, service, methods = nil)
    @recipe  = recipe
    @service = service

    if methods
      extend methods
    end
  end

  def exec(*args)
    Process.exec(*args)
  end

  def chdir(dir)
    Dir.chdir(dir)
  end

  def run(command, options = {}, &blk)
    instance = Nodectl::Instance.new(service, command, options) do
      instance_eval &blk if blk
    end

    instance.run
    instance
  end

  def run_action(action_name, options = {})
    service.recipe_binding.run_action(action_name, options)
  end
end