text:
/**
 *
 */
package com.textocat.textokit.phrrecog.input

import org.apache.uima.cas.text.AnnotationFS

import scala.util.parsing.input.{Position, Reader}

/**
 * @author Rinat Gareev
 *
 */
class AnnotationSpan[A >: Null <: AnnotationFS](annoList: List[A]) {
  require(!annoList.isEmpty, "annotation list is empty")

  private val baseOffset = annoList.head.getBegin
  private lazy val endOffset = annoList.last.getEnd

  // protected val endOfSequence: A

  lazy val reader: Reader[A] = new AnnotationReader(annoList)

  private class AnnotationReader private[AnnotationSpan](inputList: List[A]) extends Reader[A] {

    override val atEnd: Boolean = inputList.isEmpty

    override val first: A =
      if (atEnd) null
      else inputList.head

    override val rest: AnnotationReader =
      if (atEnd) this
      else new AnnotationReader(inputList.tail)

    override lazy val pos: Position =
      if (atEnd) new EndOfSequencePosition
      else new AnnotationPosition(first)
  }

  class AnnotationPosition(anno: AnnotationFS) extends Position {
    require(anno.getBegin() >= baseOffset, "illegal begin of annotation")

    override val line: Int = 1
    // NOTE! Column numbers start at 1
    override val column: Int = anno.getBegin() - baseOffset + 1

    override lazy val lineContents: String = inputContentString
  }

  class EndOfSequencePosition extends Position {
    override val line: Int = 1
    // NOTE! Column numbers start at 1
    override val column: Int = endOffset

    override lazy val lineContents: String = inputContentString
  }

  private lazy val inputContentString = {
    val sb = new StringBuilder()
    appendAnnotationContent(sb, 0, annoList)
    sb.toString()
  }

  private def appendAnnotationContent(sb: StringBuilder, lastAnnoEnd: Int, list: List[A]): Unit =
    if (!list.isEmpty) {
      val anno = list.head
      lastAnnoEnd.until(anno.getBegin()).foreach(sb.append(' '))
      sb.append(anno.getCoveredText())
      appendAnnotationContent(sb, anno.getEnd(), list.tail)
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.spark.sql.execution.datasources.v2

import java.util.UUID

import scala.collection.JavaConverters._

import org.apache.spark.SparkException
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.{Dataset, SaveMode}
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions.Attribute
import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
import org.apache.spark.sql.execution.SparkPlan
import org.apache.spark.sql.sources.{AlwaysTrue, CreatableRelationProvider, Filter, InsertableRelation}
import org.apache.spark.sql.sources.v2.{SupportsWrite, Table}
import org.apache.spark.sql.sources.v2.writer._
import org.apache.spark.sql.util.CaseInsensitiveStringMap

/**
 * Physical plan node for append into a v2 table using V1 write interfaces.
 *
 * Rows in the output data set are appended.
 */
case class AppendDataExecV1(
    table: SupportsWrite,
    writeOptions: CaseInsensitiveStringMap,
    plan: LogicalPlan) extends V1FallbackWriters {

  override protected def doExecute(): RDD[InternalRow] = {
    writeWithV1(newWriteBuilder().buildForV1Write())
  }
}

/**
 * Physical plan node for overwrite into a v2 table with V1 write interfaces. Note that when this
 * interface is used, the atomicity of the operation depends solely on the target data source.
 *
 * Overwrites data in a table matched by a set of filters. Rows matching all of the filters will be
 * deleted and rows in the output data set are appended.
 *
 * This plan is used to implement SaveMode.Overwrite. The behavior of SaveMode.Overwrite is to
 * truncate the table -- delete all rows -- and append the output data set. This uses the filter
 * AlwaysTrue to delete all rows.
 */
case class OverwriteByExpressionExecV1(
    table: SupportsWrite,
    deleteWhere: Array[Filter],
    writeOptions: CaseInsensitiveStringMap,
    plan: LogicalPlan) extends V1FallbackWriters {

  private def isTruncate(filters: Array[Filter]): Boolean = {
    filters.length == 1 && filters(0).isInstanceOf[AlwaysTrue]
  }

  override protected def doExecute(): RDD[InternalRow] = {
    newWriteBuilder() match {
      case builder: SupportsTruncate if isTruncate(deleteWhere) =>
        writeWithV1(builder.truncate().asV1Builder.buildForV1Write())

      case builder: SupportsOverwrite =>
        writeWithV1(builder.overwrite(deleteWhere).asV1Builder.buildForV1Write())

      case _ =>
        throw new SparkException(s"Table does not support overwrite by expression: $table")
    }
  }
}

/** Some helper interfaces that use V2 write semantics through the V1 writer interface. */
sealed trait V1FallbackWriters extends SupportsV1Write {
  override def output: Seq[Attribute] = Nil
  override final def children: Seq[SparkPlan] = Nil

  def table: SupportsWrite
  def writeOptions: CaseInsensitiveStringMap

  protected implicit class toV1WriteBuilder(builder: WriteBuilder) {
    def asV1Builder: V1WriteBuilder = builder match {
      case v1: V1WriteBuilder => v1
      case other => throw new IllegalStateException(
        s"The returned writer ${other} was no longer a V1WriteBuilder.")
    }
  }

  protected def newWriteBuilder(): V1WriteBuilder = {
    val writeBuilder = table.newWriteBuilder(writeOptions)
      .withInputDataSchema(plan.schema)
      .withQueryId(UUID.randomUUID().toString)
    writeBuilder.asV1Builder
  }
}

/**
 * A trait that allows Tables that use V1 Writer interfaces to append data.
 */
trait SupportsV1Write extends SparkPlan {
  // TODO: We should be able to work on SparkPlans at this point.
  def plan: LogicalPlan

  protected def writeWithV1(relation: InsertableRelation): RDD[InternalRow] = {
    relation.insert(Dataset.ofRows(sqlContext.sparkSession, plan), overwrite = false)
    sparkContext.emptyRDD
  }
}


text:
/**
 *
 */
package eu.codesketch.ws.brew.service.domain.model;

/**
 * @author quirino
 *
 */
public enum Type {

    AROMA, BITTERING;
}


text:
/**
 * Error
 *  +-- BlockchainJS
 *       +-- Blockchain
 *       |    +-- VerifyBlockchainError
 *       |    +-- VerifyChunkError
 *       |    +-- VerifyHeaderError
 *       |    +-- VerifyTxError
 *       +-- Network
 *       |    +-- Chromanode
 *       |    |    +-- Error
 *       |    |    +-- Fail
 *       |    +-- ConnectionError
 *       |    +-- ConnectionTimeout
 *       |    +-- HeaderNotFound
 *       |    +-- RequestError
 *       |    +-- TxNotFound
 *       |    +-- TxSendError
 *       |    +-- SubscribeError
 *       +-- NotImplemented
 *       +-- Storage
 *            +-- CompactMode
 *                 +-- Forbidden
 *                 +-- Limitation
 */

let spec = {
  name: 'BlockchainJS',
  message: 'Internal error',
  errors: [{
    name: 'Blockchain',
    message: 'Internal error on Blockchain {0}',
    errors: [{
      name: 'VerifyBlockchainError',
      message: 'Blockchain latest: {0}'
    }, {
      name: 'VerifyChunkError',
      message: 'Chunk #{0} ({1})'
    }, {
      name: 'VerifyHeaderError',
      message: 'Header #{0} ({1})'
    }, {
      name: 'VerifyTxError',
      message: 'TxId: {0} ({1})'
    }]
  }, {
    name: 'Network',
    message: 'Internal error on Network {0}',
    errors: [{
      name: 'Chromanode',
      message: 'Internal error on Chromanode {0}',
      errors: [{
        name: 'Error',
        message: 'Chromanode error (error: {0}, uri: {1})'
      }, {
        name: 'Fail',
        message: 'Chromanode fail (error: {0}, uri: {1})'
      }]
    }, {
      name: 'ConnectionError',
      message: 'Connection error (network: {0})'
    }, {
      name: 'ConnectionTimeout',
      message: 'Connection timeout (network: {0})'
    }, {
      name: 'HeaderNotFound',
      message: 'Header not found ({0})'
    }, {
      name: 'RequestError',
      message: 'Request HTTP error (network: {0}, code: {1}, url: {2})'
    }, {
      name: 'TxNotFound',
      message: 'Transaction not found ({0})'
    }, {
      name: 'TxSendError',
      message: 'Can\'t send transaction: {0}'
    }, {
      name: 'SubscribeError',
      message: '{0}'
    }]
  }, {
    name: 'NotImplemented',
    message: 'Function {0} was not implemented yet'
  }, {
    name: 'Storage',
    message: 'Internal error on Storage {0}',
    errors: [{
      name: 'CompactMode',
      message: 'Internal error on CompactMode {0}',
      errors: [{
        name: 'Forbidden',
        message: 'Operation forbidden. Allow only with CompactMode is true.'
      }, {
        name: 'Limitation',
        message: 'CompactMode limitation: {0}'
      }]
    }]
  }]
}

require('error-system').extend(Error, spec)
module.exports = Error.BlockchainJS


text:
from django.test import TestCase
from fluent_contents.tests.factories import create_content_item
from fluent_contents.tests.utils import render_content_items

from fluentcms_filer.teaser.models import FilerTeaserItem as TeaserItem

class TeaserTests(TestCase):
    """
    Testing teaser plugin
    """

    def test_output(self):
        """
        Test the standard teaser
        """
        item = create_content_item(TeaserItem, url="http://example.com", title="TEST")
        self.assertHTMLEqual(
            render_content_items([item]).html,
            '
'
            "
TEST
"
            '  more »'
            "
",
        )


text:
/**
 *
 */
package com.cloudera.director.vsphere.service.impl;

import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudera.director.vsphere.VSphereCredentials;
import com.cloudera.director.vsphere.compute.VSphereComputeInstanceTemplate;
import com.cloudera.director.vsphere.compute.apitypes.Group;
import com.cloudera.director.vsphere.compute.apitypes.Node;
import com.cloudera.director.vsphere.resourcesplacement.ResourcesPlacement;
import com.cloudera.director.vsphere.service.intf.IGroupTerminateService;
import com.cloudera.director.vsphere.utils.VmUtil;
import com.cloudera.director.vsphere.vm.service.impl.VmService;
import com.vmware.vim25.mo.HostSystem;
import com.vmware.vim25.mo.VirtualMachine;

/**
 * @author chiq
 *
 */
public class GroupTerminateService implements IGroupTerminateService {
   private static final Logger logger = LoggerFactory.getLogger(GroupTerminateService.class);

   private final VSphereCredentials credentials;
   private final Group group;
   private final VmService vmService;
   private ResourcesPlacement resourcesPlacement;

   public GroupTerminateService(VSphereCredentials credentials, VSphereComputeInstanceTemplate template, String prefix, Collection<String> instanceIds, ResourcesPlacement resourcesPlacement) throws Exception {
      this.credentials = credentials;
      this.group = new Group(instanceIds, template, prefix, 0, VmUtil.getVirtualMachine(credentials.getServiceInstance(), template.getTemplateVm(), false));
      this.vmService = new VmService(credentials);
      this.resourcesPlacement = resourcesPlacement;
   }

   /**
    * @return the credentials
    */
   public VSphereCredentials getCredentials() {
      return credentials;
   }

   /**
    * @return the group
    */
   public Group getGroup() {
      return group;
   }

   /**
    * @return the vmService
    */
   public VmService getVmService() {
      return vmService;
   }

   /**
    * @return the resourcesPlacement
    */
   public ResourcesPlacement getResourcesPlacement() {
      return resourcesPlacement;
   }

   /**
    * @param resourcesPlacement the resourcesPlacement to set
    */
   public void setResourcesPlacement(ResourcesPlacement resourcesPlacement) {
      this.resourcesPlacement = resourcesPlacement;
   }

   @Override
   public void terminate() throws Exception {
      for (Node node : group.getNodes()) {
         terminateNode(node);
         logger.info(String.format("Deleted allocation: %s -> %s", node.getVmName(), node.getInstanceId()));
      }
      this.resourcesPlacement.update(this.credentials.getVcServer());
   }

   private void terminateNode(Node node) throws Exception {
      try {

         VirtualMachine vm = VmUtil.getVirtualMachine(this.credentials.getServiceInstance(), node.getVmName());
         HostSystem hostSystem = new HostSystem(this.credentials.getServiceInstance().getServerConnection(), vm.getRuntime().getHost());
         String datastore = vm.getDatastores()[0].getName();

         vmService.powerOps(node.getVmName(), "poweroff");
         vmService.destroyVm(node.getVmName());

         this.resourcesPlacement.updateNodesCount(this.credentials.getVcServer(), hostSystem.getName(), datastore);
      } catch (Exception e) {
         logger.error("The VM " + node.getVmName() + " already destroyed or can not be destroyed.");
      }
   }
}


text:
define("ace/snippets/sjs",["require","exports","module"],function(e,s,i){"use strict";s.snippetText=undefined,s.scope="sjs"});
//# sourceMappingURL=node_modules/ace-builds/src-min/snippets/sjs.js.map


text:
(function () {

    var roomName,
        myName = prompt("What's your name?", "Son Goku"),
        executeDelta = !1,
        storeDeltas = !1,
        sendDelta = !1,
        deltas = [],
        isNew = !1,
        editor,
        lobby;

    if (location.hash.substr(1)) {
        roomName = location.hash.substr(1);
    }
    else {
        roomName = "" + +new Date;
        isNew = !0;
    }

    location.hash = roomName;

    console.log('Connecting...');
    goinstant.connect('https://goinstant.net/ca346407cc6d/snippeRT', {room : roomName}, function (err, connection, room) {
        var notifications = new goinstant.widgets.Notifications();

        if (err) {
            console.dir(err);
            return;
        }

        console.log('Connected.');
        lobby = room;

        console.log('Subscribing to notifications...');
        notifications.subscribe(room, function(err) {
            console.log('Done subscribing');
            if (err) {
                throw err;
            }
            console.log('Publishing notifications...');
            notifications.publish({
                room: room,
                type: 'success',
                message: myName + ' has joined.'
            }, function(err) {
                console.log('Done publishing');
                if (err) {
                    throw err;
                }
            });
        });

        room.key('delta').on('set', function (value, context) {
            console.log("receiving");
            console.dir(value);
            if (executeDelta) {
                sendDelta = !1;
                editor.getSession().getDocument().applyDeltas([value]);
                sendDelta = !0;

                // root's job
                if (storeDeltas) {
                    console.log("Saving deltas");
                    room.key('deltas').set(editor.getValue(), function (err) {
                        if (err) {
                            throw err;
                        }
                    });
                }
            }
            else {
                deltas.push(value);
            }
        });

        console.log("Getting deltas");
        room.key('deltas').get(function (err, value){
            console.log("Deltas : ");
            console.dir(value);

            editor = ace.edit("editor")
            editor.setTheme('ace/theme/twilight');
            editor.getSession().setMode('ace/mode/javascript');
            editor.focus();

            if (value) {
                sendDelta = !1;
                editor.setValue(value);
                editor.clearSelection();
            }
            else {
                storeDeltas = !0;
            }

            editor.getSession().getDocument().applyDeltas(deltas);
            executeDelta = !0;
            sendDelta = !0;

            editor.on("change", function (e) {
                if (sendDelta) {
                    console.log("sending delta : ");
                    console.dir(e.data);
                    lobby.key('delta').set(e.data, function (err, value, context) {
                        if (err) {
                            throw err;
                        }
                    });

                    if (storeDeltas) {
                        console.log("Saving deltas");
                        room.key('deltas').set(editor.getValue(), function (err) {
                            if (err) {
                                throw err;
                            }
                        });
                    }
                }
            });

            if (isNew) {
                alert("You can now share your URL to other collaborators! Hoorah!");
            }
        });
    });

} () );


text:
/**
 * @file        src/include/cynara-client-async.h
 * @author      Zofia Abramowska <z.abramowska@samsung.com>
 * @author      Marcin Niesluchowski <m.niesluchow@samsung.com>
 * @version     1.0
 * @brief       This file contains asynchronous client APIs of Cynara available
 *              with libcynara-client-asynchronous.
 */

#ifndef CYNARA_CLIENT_ASYNC_H
#define CYNARA_CLIENT_ASYNC_H

#include <stddef.h>
#include <stdint.h>

#include <cynara-error.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef uint16_t cynara_check_id;
typedef struct cynara_async cynara_async;
typedef struct cynara_async_configuration cynara_async_configuration;

/**
 * \enum cynara_async_status
 * Values indicating the status of connected cynara socket.
 *
 * \var cynara_async_status::CYNARA_STATUS_FOR_READ
 * Wait for read events on socket.
 *
 * \var cynara_async_status::CYNARA_STATUS_FOR_RW
 * Wait for both read and write events on socket.
 */
typedef enum {
    CYNARA_STATUS_FOR_READ,
    CYNARA_STATUS_FOR_RW
} cynara_async_status;

/**
 * \enum cynara_async_call_cause
 * Values indicating the reason of cynara_response_callback call.
 *
 * \var cynara_async_call_cause::CYNARA_CALL_CAUSE_ANSWER
 * Callback was called due to response to previous cynara_async_create_request() or
 * cynara_async_create_simple_request() call.
 *
 * \var cynara_async_call_cause::CYNARA_CALL_CAUSE_CANCEL
 * Callback was called due to request cancellation with cynara_async_cancel_request() call.
 *
 * \var cynara_async_call_cause::CYNARA_CALL_CAUSE_FINISH
 * Callback was called due to cynara_async_finish() call.
 *
 * \var cynara_async_call_cause::CYNARA_CALL_CAUSE_SERVICE_NOT_AVAILABLE
 * Callback was called due to service not available.
 */
typedef enum {
    CYNARA_CALL_CAUSE_ANSWER,
    CYNARA_CALL_CAUSE_CANCEL,
    CYNARA_CALL_CAUSE_FINISH,
    CYNARA_CALL_CAUSE_SERVICE_NOT_AVAILABLE
} cynara_async_call_cause;

/**
 * \brief Response_callback is registered once in cynara_async_create_request() or
 * cynara_async_create_simple_request() and will be triggered exactly once in 4 kinds of situations:
 * 1) after response is received from cynara service (CYNARA_CALL_CAUSE_ANSWER)
 * 2) when request is canceled with cynara_async_cancel_request() (CYNARA_CALL_CAUSE_CANCEL)
 * 3) when request was pending for response, but cynara_async_finish() was called
 *    (CYNARA_CALL_CAUSE_FINISH)
 * 4) when connection to cynara service was broken and cannot be established again
 *    - probably cynara is unoperational (CYNARA_CALL_CAUSE_SERVICE_NOT_AVAILABLE)
 * Api functions called during this callback with CYNARA_CALL_CAUSE_SERVICE_NOT_AVAILABLE
 * or CYNARA_CALL_CAUSE_FINISH cause will return CYNARA_API_OPERATION_NOT_ALLOWED.
 * cynara_async_finish() will be ignored if called from within this callback.
 *
 * \param[in] check_id Number identifying check request. Number is generated in
 *            cynara_async_create_request() or cynara_async_create_simple_request and returned to
 *            user. It can be used to match response with sent request.
 *            Number is valid since cynara_async_create_request() call or
 *            cynara_async_create_simple_request call till callback call.
 *            After that the number can be reused by cynara to run new request.
 * \param[in] cause Cause of triggering this callback.
 * \param[in] response Response for created request. Should be ignored if cause is not
 *            an answer to request (cause != CYNARA_CALL_CAUSE_ANSWER).
 * \param[in] user_response_data User specific data - passed to cynara library in
 *            cynara_async_cancel_request() is being only remembered by library.
 *            Cynara library does not take any actions on this pointer,
 *            except for giving it back to user in cynara_response_callback.
 *            After that cynara forgets this data.
 */
typedef void (*cynara_response_callback) (cynara_check_id check_id, cynara_async_call_cause cause,
                                          int response, void *user_response_data);

/**
 * \brief Callback used by cynara async API when status of cynara socket is changed in
 * cynara_async_initialize(), cynara_async_create_request(), cynara_async_create_simple_request(),
 * cynara_async_process(), cynara_async_cancel_request() or cynara_async_finish().
 * File descriptor changes every time cynara library connects or disconnects cynara service.
 * Status change is triggered when check_request or cancel needs to be send to
 * cynara service or sending data has finished and there is nothing more to send to cynara
 * service.
 * Note, that provided file descriptor is used internally by libcynara
 * so user should not use it in other way than waiting on it in event loop.
 * In particular user should not write to, read from or close this fd.
 * CYNARA_API_OPERATION_NOT_ALLOWED will be returned for every api function called in this callback.
 * cynara_async_finish() will be ignored if called from within this callback.
 *
 * \param[in] old_fd Old descriptor which should be unregistered from event loop,
 *            Special value -1 is used when callback is called after first
 *            successful connect.
 * \param[in] new_fd New descriptor which should be registered in event loop,
 *            Special value -1 is used when cynara_async_finish() is called and
 *            cynara is disconnected. In this case status should be ignored.
 * \param[in] status Status indicating which events should be awaited on socket
 * \param[in] user_status_data User specific data - passed to cynara library in
 *            cynara_async_initialize() is being only remembered by library.
 *            Cynara library does not take any actions on this pointer,
 *            except for giving it back to user in cynara_status_callback.
 *            Data should be valid at least until cynara_async_finish() is called.
 */
typedef void (*cynara_status_callback) (int old_fd, int new_fd, cynara_async_status status,
                                        void *user_status_data);

/**
 * \par Description:
 * Initialize cynara_async_configuration. Create structure used in following configuration
 * API calls.
 *
 * \par Purpose:
 * For configuration parameter to be used in cynara async initialization function, this API must be
 * called before any other cynara async configuration API function.
 * It will create cynara_async_configuration structure, an optional parameter of cynara async
 * initialization.
 *
 * \par Typical use case:
 * Once before setting parameters of cynara async configuration and passing to
 * cynara_async_initialize().
 *
 * \par Method of function operation:
 * This API initializes inner library structures and in case of success returns pointer
 * to created cynara_async_configuration structure.
 *
 * \par Sync (or) Async:
 * This as a synchronous API.
 *
 * \par Thread-safety:
 * This function is NOT thread-safe. If functions from described API are called by multithreaded
 * application from different threads, they must be put into protected critical section.
 *
 * \par Important notes:
 * Structure cynara_async_configuration created by cynara_async_configuration_create() call
 * should be released with cynara_async_configuration_destroy().
 * Structure cynara_async_configuration should be destroyed after passing it to
 * cynara_async_initialize().
 *
 * \param[out] pp_conf Placeholder for created cynara_async_configuration structure.
 *
 * \return CYNARA_API_SUCCESS on success
 *         or negative error code on error.
 */
int cynara_async_configuration_create(cynara_async_configuration **pp_conf);

/**
 * \par Description:
 * Release cynara_async_configuration structure created with cynara_async_configuration_create().
 *
 * \par Purpose:
 * This API should be used to clean up after usage of cynara_async_configuration.
 *
 * \par Typical use case:
 * Once cynara_async_configuration is not needed.
 *
 * \par Method of function operation:
 * This API releases inner library structure and destroys cynara_async_configuration structure.
 *
 * \par Sync (or) Async:
 * This is a synchronous API.
 *
 * \par Thread-safety:
 * This function is NOT thread-safe. If functions from described API are called by multithreaded
 * application from different threads, they must be put into protected critical section.
 *
 * \param[in] p_conf cynara_async_configuration structure. If NULL, the call has no effect.
 */
void cynara_async_configuration_destroy(cynara_async_configuration *p_conf);

/**
 * \par Description:
 * Set client cache size.
 *
 * \par Purpose:
 * This API is used to change default number of cached responses returned from cynara.
 *
 * \par Typical use case:
 * Once before setting parameters of cynara async configuration and passing to
 * cynara_async_initialize().
 *
 * \par Method of function operation:
 * This API initializes cache with given capacity.
 *
 * \par Sync (or) Async:
 * This as a synchronous API.
 *
 * \par Thread-safety:
 * This function is NOT thread-safe. If functions from described API are called by multithreaded
 * application from different threads, they must be put into protected critical section.
 *
 * \par Important notes:
 * After passing cynara_async_configuration to cynara_async_initialize() calling this API will have
 * no effect.
 *
 * \param[in] p_conf cynara_async_configuration structure pointer.
 * \param[in] cache_size Cache size to be set.
 *
 * \return CYNARA_API_SUCCESS on success
 *        or negative error code on error.
 */
int cynara_async_configuration_set_cache_size(cynara_async_configuration *p_conf,
                                              size_t cache_size);
/**
 * \par Description:
 * Initialize cynara-async-client library with given configuration. Create structure used in
 * following API calls and register callback and user_status_data for
 * further cynara async API calls.
 *
 * \par Purpose:
 * This API must be used prior to calling any other cynara async API function.
 * It will create cynara_async structure required for any other cynara async API calls.
 *
 * \par Typical use case:
 * Once before entering event loop and before any other cynara async API is called.
 *
 * \par Method of function operation:
 * This API initializes inner library structures and in case of success
 * returns cynara_async structure.
 *
 * \par Sync (or) Async:
 * This is an synchronous API.
 *
 * \par Thread-safety:
 * This function is NOT thread-safe. If functions from described API are called by multithreaded
 * application from different threads, they must be put into protected critical section.
 *
 * \par Important notes:
 * Structure cynara_async created by cynara_async_initialize() call should be released
 * with cynara_async_finish().
 *
 * \param[out] pp_cynara Placeholder for created cynara_async structure.
 * \param[in] p_conf Configuration for cynara-async-client library.
 *            NULL should be used for default configuration.
 *            Configuration management functions will be added later.
 *            Configuration will be able to specify e.g. size of cache used by library
 *            for holding checks results.
 * \param[in] callback Function called when connection is started.
 *            If NULL, no callback will be called, when status changes.
 * \param[in] user_status_data User specific data, passed to callback is being only remembered
 *            by library. Cynara library does not take any actions on this pointer,
 *            except for giving it back to user in cynara_status_callback.
 *            Data should be valid at least until cynara_async_finish() is called.
 *            Can be NULL.
 *
 * \return CYNARA_API_SUCCESS on success
 *         or negative error code on error.
 */
int cynara_async_initialize(cynara_async **pp_cynara, const cynara_async_configuration *p_conf,
                            cynara_status_callback callback, void *user_status_data);

/**
 * \par Description:
 * Release cynara-async-client library and destroy structure created with cynara_async_initialize().
 *
 * \par Purpose:
 * This API should be used to clean up after usage of cynara-async-client library.
 *
 * \par Typical use case:
 * Once after connection to cynara is not needed.
 *
 * \par Method of function operation:
 * This API releases inner library structure and destroys cynara_async structure. Connection to
 * cynara server is closed. Upon disconnecting this will trigger cynara_status_callback callback
 * with -1 as new_fd param so client can unregister file descriptor connected with cynara. It will
 * also trigger cynara_response_callback callback for each created request with
 * cynara_async_call_cause::CYNARA_CALL_CAUSE_FINISH as cause param.
 *
 * \par Sync (or) Async:
 * This is an asynchronous API.
 *
 * \par Thread-safety:
 * This function is NOT thread-safe. If functions from described API are called by multithreaded
 * application from different threads, they must be put into protected critical section.
 *
 * \par Important notes:
 * No other call to cynara-async-client library should be made after call to cynara_async_finish().
 * cynara_async_finish() called from within cynara_response_callback or cynara_status_callback will
 * be ignored.
 *
 * \param[in] p_cynara cynara_async structure. If NULL, then the call has no effect.
 */
void cynara_async_finish(cynara_async *p_cynara);

/**
 * \par Description:
 * Check access to given privilege for specified user, client and client_session in cache.
 *
 * \par Purpose:
 * This API should be used to check if cache holds information about access of user,
 * running application identified as clients to a privilege.
 * This API should be used for fast check in cache.
 *
 * \par Typical use case:
 * A service wants to check in cache, if a client requesting access to some privilege
 * has proper rights.
 *
 * \par Method of function operation:
 * Client (a process / application) requesting access to a privilege is running as some user.
 * For such triple (client, user, privilege) a cache is checked.
 * If cache is invalid it is cleared and call returns same as access not found.
 * Additional parameter client_session
 * may be used to distinguish between client session (e.g. for allowing access only for this
 * particular application launch). EMpty string "" can be used, when session differentation
 * is not needed.
 *
 * \par Sync (or) Async:
 * This is an synchronous API.
 *
 * \par Thread-safety:
 * This function is NOT thread-safe. If functions from described API are called by multithreaded
 * application from different threads, they must be put into protected critical section.
 *
 * \par Important notes:
 * Call to cynara_async_check_cache() needs cynara_async structure to be created first.
 * Use cynara_async_initialize() before calling this function. cynara_async_check_cache() called
 * from within cynara_status_callback or cynara_response_callback with
 * CYNARA_CALL_CAUSE_SERVICE_NOT_AVAILABLE or CYNARA_CALL_CAUSE_FINISH cause will return
 * CYNARA_API_OPERATION_NOT_ALLOWED.
 *
 * \param[in] p_cynara cynara_async structure.
 * \param[in] client Application or process identifier.
 * \param[in] client_session Client defined session.
 * \param[in] user User of running client.
 * \param[in] privilege Privilege that is a subject of a check.
 *
 * \return CYNARA_API_ACCESS_ALLOWED on checked access allowed,
 *         CYNARA_API_ACCESS_DENIED on checked access denied,
 *         CYNARA_API_CACHE_MISS on access not in cache,
 *         or other negative error code on error.
 */
int cynara_async_check_cache(cynara_async *p_cynara, const char *client, const char *client_session,
                             const char *user, const char *privilege);

/**
 * \par Description:
 * Creates access check request to cynara service for client, user accessing given privilege.
 * Set callback and user_response_data to be called and passed when request processing is finished.
 *
 * \par Purpose:
 * This API should be used to create check request for client identified by a triple
 * (client, user, privilege) in custom defined session.
 * Response can be received with cynara_async_process().
 * Check id is returned to pair request with response for canceling purposes.
 *
 * \par Typical use case:
 * When cynara_async_check_cache() returned CYNARA_API_CACHE_MISS, so cynara service
 * has to be asked, if a client requesting access to some privilege has proper rights.
 * To receive matching response client sets callback and specifies arbitrary data to be passed
 * to this callback.
 *
 * \par Method of function operation:
 * Client (a process / application) requesting access to a privilege is running as some user.
 * For such triple (client, user, privilege) a request event is created and added to pending
 * requests for cynara_async_process() to process.
 * Socket status will be changed to CYNARA_STATUS_FOR_RW, to ensure that cynara_async_process()
 * will be triggered in event loop after socket is ready to send request to cynara service.
 * After request is sent and there is nothing more to send to cynara service, status will change
 * back to CYNARA_STATUS_FOR_READ. Status changes are delivered with cynara_status_callback.
 * When function is successfully called unique check_id is returned. It is used for matching
 * generated request with response, that will be received by registered callback.
 * Because check_id is coded as 16-bit unsigned integer, there can be only 2^16 = 65536 pending
 * requests. When response callback is called either because of getting answer or because
 * of cancel check_id used for that request is released and can be reused by cynara library.
 * When maximum of pending requests is reached cynara_async_create_request() fails with
 * CYNARA_API_MAX_PENDING_REQUESTS error code.
 *
 * \par Sync (or) Async:
 * This is an asynchronous API.
 *
 * \par Thread-safety:
 * This function is NOT thread-safe. If functions from described API are called by multithreaded
 * application from different threads, they must be put into protected critical section.
 *
 * \par Important notes:
 * Call to cynara_async_create_request() needs cynara_async structure to be created first with
 * cynara_async_initialize().
 * Call cynara_async_cancel_request() to cancel pending request.
 * Call cynara_async_process() to receive response.
 * It is guaranteed that if cynara_async_create_request() function succeeds (CYNARA_API_SUCCESS)
 * a callback will be called exactly once and that it will receive user_response_data.
 * If function fails (returns negative error code) request won't be generated and won't be pending,
 * callback function won't be ever called and user_response_data won't be remembered by library.
 * Also no check_id will be generated and *p_check_id value should be ignored.
 * cynara_async_create_request() called from within cynara_status_callback or
 * cynara_response_callback with CYNARA_CALL_CAUSE_SERVICE_NOT_AVAILABLE or CYNARA_CALL_CAUSE_FINISH
 * cause will return CYNARA_API_OPERATION_NOT_ALLOWED.
 *
 * \param[in] p_cynara cynara_async structure.
 * \param[in] client Application or process identifier.
 * \param[in] client_session Client defined session.
 * \param[in] user User of running client.
 * \param[in] privilege Privilege that is a subject of a check.
 * \param[out] p_check_id Placeholder for check id. If NULL, then no check_id is returned.
 * \param[in] callback Function called when matching response is received.
 *            If NULL then no callback will be called when response, cancel, finish
 *            or service not availble error happens.
 * \param[in] user_response_data User specific data, passed to callback is being only remembered
 *            by library. Cynara library does not take any actions on this pointer,
 *            except for giving it back to user in cynara_response_callback.
 *            Can be NULL.
 *
 * \return CYNARA_API_SUCCESS on success,
 *         CYNARA_API_MAX_PENDING_REQUESTS on too much pending requests,
 *         or other negative error code on error.
 */
int cynara_async_create_request(cynara_async *p_cynara, const char *client,
                                const char *client_session, const char *user, const char *privilege,
                                cynara_check_id *p_check_id, cynara_response_callback callback,
                                void *user_response_data);

/**
 * \par Description:
 * Creates simple access check request to cynara service for (potential) permission to take some
 * action or access a resource.
 * Set callback and user_response_data to be called and passed when request processing is finished.
 *
 * \par Purpose:
 * This API should be used for a quick check if a user running application identified as client
 * has access to a given privilege.
 * Response can be received with cynara_async_process().
 * Check id is returned to pair request with response for canceling purposes.
 *
 * \par Typical use case:
 * An application may use this API to check if it has (potential) permission to take some action
 * or access resource in future (permissions may rarely change). The typical use would be to disable
 * or hide some of functionalities if they probably could not be used anyways.
 *
 * \par Method of function operation:
 * This function is very similar to cynara_async_create_request() with the difference, that in case
 * of answer not being one of CYNARA_API_PERMISSION_DENIED or CYNARA_API_PERMISSION_ALLOWED,
 * no external application will be consulted. Instead, CYNARA_API_ACCESS_NOT_RESOLVED is returned,
 * meaning, that only creating full request through cynara_async_create_request API would yield
 * eventual answer.
 * If access permission cannot be acquired without usage of external agents, callback can be
 * called with CYNARA_CALL_CAUSE_ANSWER and response value being CYNARA_API_ACCESS_NOT_RESOLVED.
 *
 * \par Sync (or) Async:
 * This is a synchronous API.
 *
 * \par Thread-safety:
 * This function is NOT thread-safe. If functions from described API are called by multithreaded
 * application from different threads, they must be put into mutex protected critical section.
 *
 * \par Important notes:
 * Call to cynara_async_create_simple_request() needs cynara_async structure to be created first
 * with cynara_async_initialize().
 * Call cynara_async_cancel_request() to cancel pending request.
 * Call cynara_async_process() to send request and receive response.
 * The answer will be taken from cynara's database without consulting any external applications.
 * If the answer cannot be resolved in one of CYNARA_API_ACCESS_ALLOWED or
 * CYNARA_API_ACCESS_DENIED without communicating with external application, response returned
 * through callback will have value CYNARA_API_ACCESS_NOT_RESOLVED.
 *
 * \param[in] p_cynara cynara_async structure.
 * \param[in] client Application or process identifier.
 * \param[in] client_session Client defined session.
 * \param[in] user User of running client.
 * \param[in] privilege Privilege that is a subject of a check.
 * \param[out] p_check_id Placeholder for check id. If NULL, then no check_id is returned.
 * \param[in] callback Function called when matching response is received.
 *            If NULL then no callback will be called when response, cancel, finish
 *            or service not availble error happens.
 * \param[in] user_response_data User specific data, passed to callback is being only stored by
 *            library. Cynara library does not take any actions on this pointer, except for giving
 *            it back to user in cynara_response_callback.
 *            Can be NULL.
 *
 * \return CYNARA_API_SUCCESS on success,
 *         CYNARA_API_MAX_PENDING_REQUESTS on too much pending requests,
 *         or other negative error code on error.
 */
int cynara_async_create_simple_request(cynara_async *p_cynara, const char *client,
                                       const char *client_session, const char *user,
                                       const char *privilege, cynara_check_id *p_check_id,
                                       cynara_response_callback callback, void *user_response_data);

/**
 * \par Description:
 * Process events that appeared on cynara socket.
 *
 * \par Purpose:
 * Process events after they appear on cynara socket.
 *
 * \par Typical use case:
 * After request was queued with cynara_async_create_request() or
 * cynara_async_create_simple_request() this API will return response.
 * When event loop will return readiness on cynara socket, client should use this API.
 *
 * \par Method of function operation:
 * This API sends pending requests, receives all responses and reacts when cynara
 * has disconnected. If cynara has disconnected all values in cache become invalid. During these
 * operations status of cynara socket may change, so cynara_status_callback callback will be
 * triggered to indicate these changes. cynara_response_callback callback will be triggered with
 * cynara_async_call_cause::CYNARA_CALL_CAUSE_ANSWER as cause param when response is available.
 * If cynara has disconnected it will be triggered with
 * cynara_async_call_cause::CYNARA_CALL_CAUSE_SERVICE_NOT_AVAILABLE as cause param.
 *
 * \par Sync (or) Async:
 * This is an asynchronous API.
 *
 * \par Thread-safety:
 * This function is NOT thread-safe. If functions from described API are called by multithreaded
 * application from different threads, they must be put into protected critical section.
 *
 * \par Important notes:
 * Call to cynara_async_process() requires initialized cynara_async structure. For this use
 * cynara_async_initialize(). cynara_async_process() called from within cynara_status_callback or
 * cynara_response_callback with CYNARA_CALL_CAUSE_SERVICE_NOT_AVAILABLE or CYNARA_CALL_CAUSE_FINISH
 * cause will return CYNARA_API_OPERATION_NOT_ALLOWED.
 *
 * \param[in] p_cynara cynara_async structure.
 *
 * \return CYNARA_API_SUCCESS on success
 *         or negative error code on error.
 */
int cynara_async_process(cynara_async *p_cynara);

/**
 * \par Description:
 * Cancel request created by cynara_async_create_request() or cynara_async_create_simple_request().
 *
 * \par Purpose:
 * This API should be used to cancel pending check request,
 * created by cynara_async_create_request() or cynara_async_create_simple_request().
 *
 * \par Typical use case:
 * When cynara client is no longer interested in receiving an answer.
 * Same check_id value should be used to identify proper request as was generated during
 * request creation with cynara_async_create_request() or cynara_async_create_simple_request().
 *
 * \par Method of function operation:
 * Cancels request created by cynara_async_create_request() or cynara_async_create_simple_request()
 * call.
 * cynara_status_callback callback may be triggered to be able to send cancel to cynara.
 * cynara_response_callback callback will be triggered with with
 * cynara_async_call_cause::CYNARA_CALL_CAUSE_CANCEL as cause param.
 * If given id is not valid (was not requested or response callback was already delivered)
 * cynara_async_cancel_request() returns CYNARA_API_INVALID_PARAM.
 *
 * \par Sync (or) Async:
 * This is a synchronous API.
 *
 * \par Thread-safety:
 * This function is NOT thread-safe. If functions from described API are called by multithreaded
 * application from different threads, they must be put into protected critical section.
 *
 * \par Important notes:
 * Call to cynara_async_cancel_request() needs cynara_async structure to be created first. For this
 * use cynara_async_initialize(). cynara_async_cancel_request() called from within
 * cynara_status_callback or cynara_response_callback with CYNARA_CALL_CAUSE_SERVICE_NOT_AVAILABLE
 * or CYNARA_CALL_CAUSE_FINISH cause will return CYNARA_API_OPERATION_NOT_ALLOWED.
 *
 * \param[in] p_cynara cynara_async structure.
 * \param[in] check_id Check id to be cancelled
 *
 * \return CYNARA_API_SUCCESS on success
 *         or negative error code on error.
 */
int cynara_async_cancel_request(cynara_async *p_cynara, cynara_check_id check_id);

/*
 *  Example of usage:
 *
 *  void change_status(int old_fd, int new_fd, cynara_async_status status, void *user_status_data)
 *  {
 *      // unregister using old_fd
 *      ...
 *      //register using new_fd and new status
 *  }
 *
 *  int process_response(int check_id, cynara_async_call_cause cause, int response,
 *                       void *user_response_data)
 *  {
 *      switch (cause) {
 *      case cynara_async_call_cause::CYNARA_CALL_CAUSE_ANSWER:
 *          // handle answer from cynara service - use response value
 *          break;
 *      case cynara_async_call_cause::CYNARA_CALL_CAUSE_CANCEL:
 *          // handle canceled request
 *          break;
 *      case cynara_async_call_cause::CYNARA_CALL_CAUSE_FINISH:
 *          // handle finish of client async
 *          break;
 *      case cynara_async_call_cause::CYNARA_CALL_CAUSE_SERVICE_NOT_AVAILABLE:
 *          // handle disconnection
 *      }
 *      ...
 *      free_user_response_data(user_response_data);
 *  }
 *
 *  void main_process
 *  {
 *      //initialize all required objects
 *      cynara_async *p_cynara;
 *      int ret;
 *      //change_status will be called passing file descriptor connected to cynara server
 *      if ((ret = cynara_async_initalize(&p_cynara, NULL, change_status, &fd_sets)) !=
 *            CYNARA_API_SUCCESS) {
 *          // handle error
 *      }
 *
 *      //start event loop
 *      event_process(fd_sets, ...)
 *
 *      //event loop stopped, clean-up, before closing program
 *      cynara_async_finish(p_cynara);
 *  }
 *
 *  void event_process(fd_sets, ...)
 *  {
 *      //event loop of user choice
 *      select(..., fd_sets.read, fd_sets.write) {
 *         ...
 *         if(active_socket == cynara_socket) {
 *             if(cynara_async_process(p_cynara) != CYNARA_API_SUCCESS) {
 *                // handle error
 *             }
 *         } else if (active_socket == some_client_socket) {
 *             //processing clients, which may require cynara checks
 *             ...
 *             int ret = cynara_async_check_cache(p_cynara, client, client_session, user,
 *                                                privilege);
 *             switch(ret) {
 *             case CYNARA_API_ACCESS_ALLOWED:
 *                 // allow client
 *                 break;
 *             case CYNARA_API_ACCESS_DENIED:
 *                 // deny client
 *                 break;
 *             case CYNARA_API_CACHE_MISS:
 *                 // not in cache - prepare data that will be passed to callback
 *                 allocate_user_response_data(&user_response_data);
 *
 *                 // create request
 *                 ret = cynara_async_create_request(p_cynara,
 *                                                   client, client_session, user, privilege,
 *                                                   &check_id,
 *                                                   process_response, user_response_data);
 *                 if(ret != CYNARA_API_SUCCESS) {
 *                     free_user_response_data(user_response_data);
 *                     // handle error
 *                 }
 *             default:
 *                 // handle error
 *             }
 *             ...
 *             // waiting for some request too long
 *             if (ret = cynara_async_cancel_request(p_cynara, check_id)) != CYNARA_API_SUCCESS) {
 *                 // handle error
 *             }
 *         }
 *         ...
 *      }
 *      ...
 *  }
 */

#ifdef __cplusplus
}
#endif

#endif /* CYNARA_CLIENT_ASYNC_H */


text:
//
//  EmailProtocol.h
//  CloudRail_ServiceCode
//
//  Created by Felipe Cesar on 20/06/16.
//  Copyright © 2016 CloudRail. All rights reserved.
//

#import <Foundation/Foundation.h>

/**
 * An interface whose implementations allow sending emails
 */
@protocol CREmailProtocol <NSObject>

/**
 * Sends an email. Used like sendEmail("info@cloudrail.com", "CloudRail", Arrays.asList("foo@bar.com", "bar@foo.com"), "Welcome", "Hello from CloudRail", null, null, null).
 * Throws if an error occurs.
 *
 * @param fromAddress Mandatory. The sender email address. Must normally be registered with the corresponding service.
 * @param fromName Mandatory. The from name to be displayed to the recipient(s).
 * @param toAddresses Mandatory. A list of recipient email addresses.
 * @param subject Mandatory. The email's subject line.
 * @param textBody The email's body plain text part. Either this and/or the htmlBody must be specified.
 * @param htmlBody The email's body HTML part. Either this and/or the textBody must be specified.
 * @param ccAddresses Optional. A list of CC recipient email addresses.
 * @param bccAddresses Optional. A list of BCC recipient email addresses.
 */
- (void)sendEmailFromAddress:(NSString *)fromAddress
                   fromName:(NSString *)fromName
                toAddresses:(NSMutableArray<NSString *> *)toAddresses
                    subject:(NSString *)subject
                   textBody:(NSString *)textBody
                   htmlBody:(NSString *)htmlBody
                ccAddresses:(NSMutableArray<NSString *> *)ccAddresses
               bccAddresses:(NSMutableArray<NSString *> *)bccAddresses;

@end


text:
package org.intellij.lang.regexp.psi.impl;

import java.awt.Color;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import org.intellij.lang.regexp.RegExpLanguageHosts;
import org.intellij.lang.regexp.RegExpTT;
import org.intellij.lang.regexp.psi.RegExpElementVisitor;
import org.intellij.lang.regexp.psi.RegExpProperty;
import com.intellij.codeInsight.lookup.LookupValueFactory;
import com.intellij.codeInsight.lookup.LookupValueWithPriority;
import com.intellij.codeInsight.lookup.LookupValueWithUIHint;
import com.intellij.icons.AllIcons;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;

public class RegExpPropertyImpl extends RegExpElementImpl implements RegExpProperty {
    public RegExpPropertyImpl(ASTNode astNode) {
        super(astNode);
    }

    public PsiReference getReference() {
        final ASTNode lbrace = getNode().findChildByType(RegExpTT.LBRACE);
        if (lbrace == null) return null;
        return new MyPsiReference();
    }

    public boolean isNegated() {
        final ASTNode node = getNode().findChildByType(RegExpTT.PROPERTY);
        return node != null && node.textContains('P');
    }

    @Nullable
    public ASTNode getCategoryNode() {
        return getNode().findChildByType(RegExpTT.NAME);
    }

    public void accept(RegExpElementVisitor visitor) {
        visitor.visitRegExpProperty(this);
    }

  private class MyPsiReference implements PsiReference {
        public PsiElement getElement() {
            return RegExpPropertyImpl.this;
        }

        public TextRange getRangeInElement() {
            final ASTNode lbrace = getNode().findChildByType(RegExpTT.LBRACE);
            assert lbrace != null;
            final ASTNode rbrace = getNode().findChildByType(RegExpTT.RBRACE);
            int to = rbrace == null ? getTextRange().getEndOffset() : rbrace.getTextRange().getEndOffset() - 1;

            final TextRange t = new TextRange(lbrace.getStartOffset() + 1, to);
            return t.shiftRight(-getTextRange().getStartOffset());
        }

        @Nullable
        public PsiElement resolve() {
            return RegExpPropertyImpl.this;
        }

        @Nonnull
        public String getCanonicalText() {
            return getRangeInElement().substring(getElement().getText());
        }

        public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
            throw new IncorrectOperationException();
        }

        public PsiElement bindToElement(@Nonnull PsiElement element) throws IncorrectOperationException {
            throw new IncorrectOperationException();
        }

        public boolean isReferenceTo(PsiElement element) {
            return false;
        }

        @Nonnull
        public Object[] getVariants() {
            final ASTNode categoryNode = getCategoryNode();
            if (categoryNode != null && categoryNode.getText().startsWith("In") && !categoryNode.getText().startsWith("Intelli")) {
                return UNICODE_BLOCKS;
            } else {
              final String[][] knownProperties = RegExpLanguageHosts.getInstance().getAllKnownProperties(getElement());
              final Object[] objects = new Object[knownProperties.length];
                for (int i = 0; i < objects.length; i++) {
                    final String[] prop = knownProperties[i];
                    objects[i] = new MyLookupValue(prop);

                }
                return objects;
            }
        }

        public boolean isSoft() {
            return true;
        }

        private class MyLookupValue extends LookupValueFactory.LookupValueWithIcon implements LookupValueWithPriority, LookupValueWithUIHint {
            private final String[] myProp;

            public MyLookupValue(String[] prop) {
                super(prop[0], AllIcons.Nodes.Property);
                myProp = prop;
            }

            public String getPresentation() {
                final ASTNode categoryNode = getCategoryNode();
                if (categoryNode != null) {
                    if (categoryNode.getText().startsWith("Is")) {
                        return "Is" + super.getPresentation();
                    }
                }
                return super.getPresentation();
            }

            public int getPriority() {
                final String name = myProp[0];
                if (name.equals("all")) return HIGH + 1;
                if (name.startsWith("java")) return HIGHER;
                return name.length() > 2 ? HIGH : NORMAL;
            }

            public String getTypeHint() {
                return myProp.length > 1 ? myProp[1] : ("Character.is" + myProp[0].substring("java".length()) + "()");
            }

            @Nullable
            public Color getColorHint() {
                return null;
            }

            public boolean isBold() {
                return false;
            }
        }
    }

    private static final String[] UNICODE_BLOCKS;
    static {
        final Field[] fields = Character.UnicodeBlock.class.getFields();
        final List<String> unicodeBlocks = new ArrayList<String>(fields.length);
        for (Field field : fields) {
            if (field.getType().equals(Character.UnicodeBlock.class)) {
                if (Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) {
                    unicodeBlocks.add("In" + field.getName());
                }
            }
        }
      UNICODE_BLOCKS = ArrayUtil.toStringArray(unicodeBlocks);
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Revta R. Acad. Cienc. exact. fis. nat. Madr. 14: 840 (1916)

#### Original name
Boletus unicolor Bull., 1785

### Remarks
null


text:
.. _features_auto:

Features API
============

.. automodule:: wqio.features
   :members:
   :undoc-members:
   :show-inheritance:


text:
'use strict'

const express = require('express')
const config = require('./config/config')

const app = express()

require('./config/express')(app, config)
const http = require('http').Server(app)
const io = require('socket.io')(http)

require('./app/io/index')(io)

http.listen(config.port, function () {
  console.log('Express server and socket.io listening on port ' + config.port)
})


text:
/*
 * This code was generated by
 * ___ _ _ _ _ _    _ ____    ____ ____ _    ____ ____ _  _ ____ ____ ____ ___ __   __
 *  |  | | | | |    | |  | __ |  | |__| | __ | __ |___ |\ | |___ |__/ |__|  | |  | |__/
 *  |  |_|_| | |___ | |__|    |__| |  | |    |__] |___ | \| |___ |  \ |  |  | |__| |  \
 *
 * Twilio - Studio
 * This is the public Twilio REST API.
 *
 * NOTE: This class is auto generated by OpenAPI Generator.
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;

namespace Twilio.Rest.Studio.V2.Flow
{
    /// <summary> Retrieve a specific Flow revision. </summary>
    public class FetchFlowRevisionOptions : IOptions<FlowRevisionResource>
    {

        ///<summary> The SID of the Flow resource to fetch. </summary>
        public string PathSid { get; }

        ///<summary> Specific Revision number or can be `LatestPublished` and `LatestRevision`. </summary>
        public string PathRevision { get; }

        /// <summary> Construct a new FetchFlowRevisionOptions </summary>
        /// <param name="pathSid"> The SID of the Flow resource to fetch. </param>
        /// <param name="pathRevision"> Specific Revision number or can be `LatestPublished` and `LatestRevision`. </param>
        public FetchFlowRevisionOptions(string pathSid, string pathRevision)
        {
            PathSid = pathSid;
            PathRevision = pathRevision;
        }

        /// <summary> Generate the necessary parameters </summary>
        public  List<KeyValuePair<string, string>> GetParams()
        {
            var p = new List<KeyValuePair<string, string>>();

            return p;
        }

    }

    /// <summary> Retrieve a list of all Flows revisions. </summary>
    public class ReadFlowRevisionOptions : ReadOptions<FlowRevisionResource>
    {

        ///<summary> The SID of the Flow resource to fetch. </summary>
        public string PathSid { get; }

        /// <summary> Construct a new ListFlowRevisionOptions </summary>
        /// <param name="pathSid"> The SID of the Flow resource to fetch. </param>
        public ReadFlowRevisionOptions(string pathSid)
        {
            PathSid = pathSid;
        }

        /// <summary> Generate the necessary parameters </summary>
        public  override List<KeyValuePair<string, string>> GetParams()
        {
            var p = new List<KeyValuePair<string, string>>();

            if (PageSize != null)
            {
                p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
            }
            return p;
        }

    }

}


text:
from math import pi, tan
from random import random
from raytracer import RayTracer
from vector3f import Vector3f

MIN_ANGLE = 10.0
MAX_ANGLE = 160.0

class Camera(object):

    # view_position
    # view_direction
    # view_angle (radians)
    # right
    # up

    def __init__(self, position, direction, angle):

        self.view_position = Vector3f(position)
        self.view_direction = Vector3f(direction).unitize()

        if self.view_direction.is_zero():
            self.view_direction = Vector3f(0.0, 0.0, 1.0)

        self.view_angle = min(
            max(MIN_ANGLE, float(angle)), MAX_ANGLE) * (pi / 180.0)

        # calculate right and up

        self.right = Vector3f(0.0, 1.0, 0.0).cross(
            self.view_direction).unitize()

        if self.right.is_zero():
            self.up = Vector3f(
                0.0, 0.0, 1.0 if self.view_direction.y else -1.0)
            self.right = self.up.cross(self.view_direction).unitize()
        else:
            self.up = self.view_direction.cross(self.right).unitize()

    def get_frame(self, scene, image):

        raytracer = RayTracer(scene)
        aspect = float(image.height) / float(image.width)

        for y in range(image.height):
            for x in range(image.width):

                # convert x, y into sample_direction

                x_coefficient = ((x + random()) * 2.0 / image.width) - 1.0
                y_coefficient = ((y + random()) * 2.0 / image.height) - 1.0

                offset = self.right * x_coefficient + self.up * (y_coefficient * aspect)
                sample_direction = (self.view_direction + (offset * tan(self.view_angle * 0.5))).unitize()

                # calculate radiance from that direction

                radiance = raytracer.get_radiance(
                    self.view_position, sample_direction)

                # and add to image

                image.add_radiance(x, y, radiance)


text:
<?php
include_once ($_SERVER['DOCUMENT_ROOT'].'/lib/phpseclib/Net/SSH2.php');

function SSH_ls ($Host,$Username,$Password,$cmd) {

$ssh = new Net_SSH2($Host);
if (!$ssh->login($Username, $Password)) {
    exit('Login Failed');
}

return $ssh->exec($cmd);

}

?>


text:
<component name="InspectionProjectProfileManager">
  <profile version="1.0">
    <option name="myName" value="Project Default" />
  </profile>
</component>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>JBossLogger xref</title>
<link type="text/css" rel="stylesheet" href="../../../../stylesheet.css" />

View Javadoc

1
16  package org.jboss.netty.logging;
17
18  import org.jboss.logging.Logger;
19
20  /**
21   * <a href="http://anonsvn.jboss.org/repos/common/common-logging-spi/">JBoss Logging</a>
22   * logger.
23   */
24  class JBossLogger extends AbstractInternalLogger {
25
26      private final Logger logger;
27
28      JBossLogger(Logger logger) {
29          this.logger = logger;
30      }
31
32      public void debug(String msg) {
33          logger.debug(msg);
34      }
35
36      public void debug(String msg, Throwable cause) {
37          logger.debug(msg, cause);
38      }
39
40      public void error(String msg) {
41          logger.error(msg);
42      }
43
44      public void error(String msg, Throwable cause) {
45          logger.error(msg, cause);
46      }
47
48      public void info(String msg) {
49          logger.info(msg);
50      }
51
52      public void info(String msg, Throwable cause) {
53          logger.info(msg, cause);
54      }
55
56      @SuppressWarnings("deprecation")
57      public boolean isDebugEnabled() {
58          return logger.isDebugEnabled();
59      }
60
61      public boolean isErrorEnabled() {
62          return true;
63      }
64
65      @SuppressWarnings("deprecation")
66      public boolean isInfoEnabled() {
67          return logger.isInfoEnabled();
68      }
69
70      public boolean isWarnEnabled() {
71          return true;
72      }
73
74      public void warn(String msg) {
75          logger.warn(msg);
76      }
77
78      public void warn(String msg, Throwable cause) {
79          logger.warn(msg, cause);
80      }
81
82      @Override
83      public String toString() {
84          return String.valueOf(logger.getName());
85      }
86  }

This page was automatically generated by Maven


text:
// Copyright 2013 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/libplatform/default-platform.h"

#include <algorithm>
#include <queue>

#include "include/libplatform/libplatform.h"
#include "src/base/debug/stack_trace.h"
#include "src/base/logging.h"
#include "src/base/page-allocator.h"
#include "src/base/platform/platform.h"
#include "src/base/platform/time.h"
#include "src/base/sys-info.h"
#include "src/libplatform/default-foreground-task-runner.h"
#include "src/libplatform/default-job.h"
#include "src/libplatform/default-worker-threads-task-runner.h"

namespace v8 {
namespace platform {

namespace {

void PrintStackTrace() {
  v8::base::debug::StackTrace trace;
  trace.Print();
  // Avoid dumping duplicate stack trace on abort signal.
  v8::base::debug::DisableSignalStackDump();
}

}  // namespace

std::unique_ptr<v8::Platform> NewDefaultPlatform(
    int thread_pool_size, IdleTaskSupport idle_task_support,
    InProcessStackDumping in_process_stack_dumping,
    std::unique_ptr<v8::TracingController> tracing_controller) {
  if (in_process_stack_dumping == InProcessStackDumping::kEnabled) {
    v8::base::debug::EnableInProcessStackDumping();
  }
  auto platform = std::make_unique<DefaultPlatform>(
      thread_pool_size, idle_task_support, std::move(tracing_controller));
  platform->EnsureBackgroundTaskRunnerInitialized();
  return platform;
}

bool PumpMessageLoop(v8::Platform* platform, v8::Isolate* isolate,
                     MessageLoopBehavior behavior) {
  return static_cast<DefaultPlatform*>(platform)->PumpMessageLoop(isolate,
                                                                  behavior);
}

void RunIdleTasks(v8::Platform* platform, v8::Isolate* isolate,
                  double idle_time_in_seconds) {
  static_cast<DefaultPlatform*>(platform)->RunIdleTasks(isolate,
                                                        idle_time_in_seconds);
}

void SetTracingController(
    v8::Platform* platform,
    v8::platform::tracing::TracingController* tracing_controller) {
  static_cast<DefaultPlatform*>(platform)->SetTracingController(
      std::unique_ptr<v8::TracingController>(tracing_controller));
}

namespace {
constexpr int kMaxThreadPoolSize = 16;

int GetActualThreadPoolSize(int thread_pool_size) {
  DCHECK_GE(thread_pool_size, 0);
  if (thread_pool_size < 1) {
    thread_pool_size = base::SysInfo::NumberOfProcessors() - 1;
  }
  return std::max(std::min(thread_pool_size, kMaxThreadPoolSize), 1);
}
}  // namespace

DefaultPlatform::DefaultPlatform(
    int thread_pool_size, IdleTaskSupport idle_task_support,
    std::unique_ptr<v8::TracingController> tracing_controller)
    : thread_pool_size_(GetActualThreadPoolSize(thread_pool_size)),
      idle_task_support_(idle_task_support),
      tracing_controller_(std::move(tracing_controller)),
      page_allocator_(std::make_unique<v8::base::PageAllocator>()) {
  if (!tracing_controller_) {
    tracing::TracingController* controller = new tracing::TracingController();
#if !defined(V8_USE_PERFETTO)
    controller->Initialize(nullptr);
#endif
    tracing_controller_.reset(controller);
  }
}

DefaultPlatform::~DefaultPlatform() {
  base::MutexGuard guard(&lock_);
  if (worker_threads_task_runner_) worker_threads_task_runner_->Terminate();
  for (const auto& it : foreground_task_runner_map_) {
    it.second->Terminate();
  }
}

namespace {

double DefaultTimeFunction() {
  return base::TimeTicks::HighResolutionNow().ToInternalValue() /
         static_cast<double>(base::Time::kMicrosecondsPerSecond);
}

}  // namespace

void DefaultPlatform::EnsureBackgroundTaskRunnerInitialized() {
  base::MutexGuard guard(&lock_);
  if (!worker_threads_task_runner_) {
    worker_threads_task_runner_ =
        std::make_shared<DefaultWorkerThreadsTaskRunner>(
            thread_pool_size_, time_function_for_testing_
                                   ? time_function_for_testing_
                                   : DefaultTimeFunction);
  }
}

void DefaultPlatform::SetTimeFunctionForTesting(
    DefaultPlatform::TimeFunction time_function) {
  base::MutexGuard guard(&lock_);
  time_function_for_testing_ = time_function;
  // The time function has to be right after the construction of the platform.
  DCHECK(foreground_task_runner_map_.empty());
}

bool DefaultPlatform::PumpMessageLoop(v8::Isolate* isolate,
                                      MessageLoopBehavior wait_for_work) {
  bool failed_result = wait_for_work == MessageLoopBehavior::kWaitForWork;
  std::shared_ptr<DefaultForegroundTaskRunner> task_runner;
  {
    base::MutexGuard guard(&lock_);
    auto it = foreground_task_runner_map_.find(isolate);
    if (it == foreground_task_runner_map_.end()) return failed_result;
    task_runner = it->second;
  }

  std::unique_ptr<Task> task = task_runner->PopTaskFromQueue(wait_for_work);
  if (!task) return failed_result;

  DefaultForegroundTaskRunner::RunTaskScope scope(task_runner);
  task->Run();
  return true;
}

void DefaultPlatform::RunIdleTasks(v8::Isolate* isolate,
                                   double idle_time_in_seconds) {
  DCHECK_EQ(IdleTaskSupport::kEnabled, idle_task_support_);
  std::shared_ptr<DefaultForegroundTaskRunner> task_runner;
  {
    base::MutexGuard guard(&lock_);
    if (foreground_task_runner_map_.find(isolate) ==
        foreground_task_runner_map_.end()) {
      return;
    }
    task_runner = foreground_task_runner_map_[isolate];
  }
  double deadline_in_seconds =
      MonotonicallyIncreasingTime() + idle_time_in_seconds;

  while (deadline_in_seconds > MonotonicallyIncreasingTime()) {
    std::unique_ptr<IdleTask> task = task_runner->PopTaskFromIdleQueue();
    if (!task) return;
    DefaultForegroundTaskRunner::RunTaskScope scope(task_runner);
    task->Run(deadline_in_seconds);
  }
}

std::shared_ptr<TaskRunner> DefaultPlatform::GetForegroundTaskRunner(
    v8::Isolate* isolate) {
  base::MutexGuard guard(&lock_);
  if (foreground_task_runner_map_.find(isolate) ==
      foreground_task_runner_map_.end()) {
    foreground_task_runner_map_.insert(std::make_pair(
        isolate, std::make_shared<DefaultForegroundTaskRunner>(
                     idle_task_support_, time_function_for_testing_
                                             ? time_function_for_testing_
                                             : DefaultTimeFunction)));
  }
  return foreground_task_runner_map_[isolate];
}

void DefaultPlatform::CallOnWorkerThread(std::unique_ptr<Task> task) {
  EnsureBackgroundTaskRunnerInitialized();
  worker_threads_task_runner_->PostTask(std::move(task));
}

void DefaultPlatform::CallDelayedOnWorkerThread(std::unique_ptr<Task> task,
                                                double delay_in_seconds) {
  EnsureBackgroundTaskRunnerInitialized();
  worker_threads_task_runner_->PostDelayedTask(std::move(task),
                                               delay_in_seconds);
}

bool DefaultPlatform::IdleTasksEnabled(Isolate* isolate) {
  return idle_task_support_ == IdleTaskSupport::kEnabled;
}

/*std::unique_ptr<JobHandle> DefaultPlatform::PostJob(
    TaskPriority priority, std::unique_ptr<JobTask> job_task) {
  size_t num_worker_threads = 0;
  switch (priority) {
    case TaskPriority::kUserBlocking:
      num_worker_threads = NumberOfWorkerThreads();
      break;
    case TaskPriority::kUserVisible:
      num_worker_threads = NumberOfWorkerThreads() / 2;
      break;
    case TaskPriority::kBestEffort:
      num_worker_threads = 1;
      break;
  }
  return std::make_unique<DefaultJobHandle>(std::make_shared<DefaultJobState>(
      this, std::move(job_task), priority, num_worker_threads));
}*/

double DefaultPlatform::MonotonicallyIncreasingTime() {
  if (time_function_for_testing_) return time_function_for_testing_();
  return DefaultTimeFunction();
}

double DefaultPlatform::CurrentClockTimeMillis() {
  return base::OS::TimeCurrentMillis();
}

TracingController* DefaultPlatform::GetTracingController() {
  return tracing_controller_.get();
}

void DefaultPlatform::SetTracingController(
    std::unique_ptr<v8::TracingController> tracing_controller) {
  DCHECK_NOT_NULL(tracing_controller.get());
  tracing_controller_ = std::move(tracing_controller);
}

int DefaultPlatform::NumberOfWorkerThreads() { return thread_pool_size_; }

Platform::StackTracePrinter DefaultPlatform::GetStackTracePrinter() {
  return PrintStackTrace;
}

v8::PageAllocator* DefaultPlatform::GetPageAllocator() {
  return page_allocator_.get();
}

}  // namespace platform
}  // namespace v8


text:
<?php

/**
 * PluginrtShopPromotionTable
 *
 * @package    rtShopPlugin
 * @author     Piers Warmers <piers@wranglers.com.au>
 * @author     Konny Zurcher <konny@wranglers.com.au>
 */
class PluginrtShopPromotionTable extends Doctrine_Table
{
  /**
   * Returns an instance of this class.
   *
   * @return object PluginrtShopPromotionTable
   */
  public static function getInstance()
  {
    return Doctrine_Core::getTable('PluginrtShopPromotion');
  }

  /**
   * Find available promotions
   *
   * @param Float $total      Order total
   * @param DateTime $date    Timestamp
   * @param Doctrine_Query $q An optional query object
   * @return Array            Found promotions
   */
  public function findAvailable($total, $date = null, Doctrine_Query $q = null)
  {
    $q = $this->getQuery($q);
    $q = $this->getDateRestrictionQuery($date, $q);
    $q = $this->getTotalRestrictionQuery($total, $q);
    return $q->fetchArray();
  }

  /**
   * Find nearly available promotions
   *
   * @param Float $total      Order total
   * @param DateTime $date    Timestamp
   * @param Doctrine_Query $q An optional query object
   * @return Array            Found promotions
   */
  public function findNearlyAvailable($total, $date = null, Doctrine_Query $q = null)
  {
    $q = $this->getQuery($q);
    $q = $this->getDateRestrictionQuery($date, $q);
    $q = $this->getTotalRestrictionUpperQuery($total, $q);
    return $q->fetchArray();
  }

  /**
   * Return a query that checks for availability
   *
   * @param Doctrine_Query $query
   * @return Doctrine_Query
   */
  public function getDateRestrictionQuery($date = NULL, Doctrine_Query $q = null)
  {
    if(is_null($date))
    {
      $date = date("Y-m-d H:i:s");
    }

    $q = $this->getQuery($q);
    $q->andWhere('(p.date_from <= ? OR p.date_from IS NULL)', date('Y-m-d H:i:s', strtotime($date)));
    $q->andWhere('(p.date_to > ? OR p.date_to IS NULL)', date('Y-m-d H:i:s', strtotime($date)));
    return $q;
  }

  /**
   * Return a query with total condition
   *
   * @param  float           $total  Total price
   * @param  Doctrine_Query  $query  an optional query object
   * @return Doctrine_Query
   */
  public function getTotalRestrictionQuery($total, Doctrine_Query $q = null)
  {
    $q = $this->getQuery($q);
    $q->andWhere('(p.total_from <= ? OR p.total_from IS NULL)', $total);
    $q->andWhere('(p.total_to >= ? OR p.total_to IS NULL)', $total);
    return $q;
  }

   /**
   * Return a query with total condition
   *
   * @param  float           $total  Total price
   * @param  Doctrine_Query  $query  an optional query object
   * @return Doctrine_Query
   */
  public function getTotalRestrictionUpperQuery($total, Doctrine_Query $q = null)
  {
    $q = $this->getQuery($q);
    $q->andWhere('p.total_from > ?', $total);
    return $q;
  }

  /**
   * Returns a Doctrine_Query object.
   *
   * @param Doctrine_Query $q
   * @return Doctrine_Query
   */
  public function getQuery(Doctrine_Query $q = null)
  {
    if (is_null($q))
    {
      $q = $this->getQueryObject()->from($this->getComponentName() .' p');
    }

    return $q;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.github.chrisvest</groupId>
  <artifactId>stormpot</artifactId>
  <version>2.4.2-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>stormpot</name>
  <description>A fast object pool library.</description>
  <url>http://chrisvest.github.io/stormpot</url>
  <inceptionYear>2011-2014</inceptionYear>

  <parent>
    <groupId>org.sonatype.oss</groupId>
    <artifactId>oss-parent</artifactId>
    <version>7</version>
  </parent>

  <licenses>
    <license>
      <name>Apache 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <scm>
    <url>https://github.com/chrisvest/stormpot</url>
    <connection>scm:git:git://github.com/chrisvest/stormpot.git</connection>
    <developerConnection>scm:git:git@github.com:chrisvest/stormpot.git</developerConnection>
  </scm>

  <developers>
    <developer>
      <id>chrisvest</id>
      <name>Chris Vest</name>
      <email>mr.chrisvest@gmail.com</email>
      <roles>
        <role>Programmer</role>
      </roles>
      <timezone>+1</timezone>
    </developer>
  </developers>

  <properties>
    <outputEncoding>UTF-8</outputEncoding>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.6</java.version>
    <jacoco.version>0.7.2.201409121644</jacoco.version>
    <javadoc.version>2.9.1</javadoc.version>
    <asciidoclet.version>1.5.1</asciidoclet.version>
  </properties>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-checkstyle-plugin</artifactId>
        <version>2.15</version>
        <configuration>
          <configLocation>src/etc/checkstyle.xml</configLocation>
        </configuration>
        <executions>
          <execution>
            <goals>
              <goal>check</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <compilerVersion>${java.version}</compilerVersion>
          <source>${java.version}</source>
          <target>${java.version}</target>
          <compilerArgument>-Xlint:all</compilerArgument>
          <showWarnings>true</showWarnings>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <version>2.9</version>
        <configuration>
          <downloadSources>true</downloadSources>
          <downloadJavadocs>true</downloadJavadocs>
          <useProjectReferences>false</useProjectReferences>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.16</version>
        <configuration>
          <systemProperties>
            <property>
              <name>forkMode</name>
              <value>none</value>
            </property>
          </systemProperties>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-failsafe-plugin</artifactId>
        <version>2.16</version>
        <executions>
          <execution>
            <goals>
              <goal>integration-test</goal>
              <goal>verify</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>${jacoco.version}</version>
        <executions>
          <execution>
            <goals>
              <goal>prepare-agent</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <version>3.3</version>
      </plugin>
      <plugin>
        <!--
          Run mutation tests like this:
          mvn clean install org.pitest:pitest-maven:mutationCoverage
        -->
        <groupId>org.pitest</groupId>
        <artifactId>pitest-maven</artifactId>
        <version>1.1.3</version>
        <configuration>
          <targetTests>
            <param>stormpot.*</param>
          </targetTests>
          <targetClasses>
            <param>stormpot.*</param>
          </targetClasses>
          <excludedGroups>
            <excludedGroup>stormpot.slow.SlowTest</excludedGroup>
          </excludedGroups>
          <threads>4</threads>
          <jvmArgs>
            <value>-ea</value>
          </jvmArgs>
        </configuration>
      </plugin>
      <plugin>
        <groupId>com.mycila</groupId>
        <artifactId>license-maven-plugin</artifactId>
        <version>2.5</version>
        <configuration>
          <header>com/mycila/maven/plugin/license/templates/APACHE-2.txt</header>
          <properties>
            <owner>Chris Vest</owner>
            <year>${project.inceptionYear}</year>
            <email>mr.chrisvest@gmail.com</email>
          </properties>
          <mapping>
            <java>SLASHSTAR_STYLE</java>
          </mapping>
          <includes>
            <include>**/*.java</include>
          </includes>
        </configuration>
        <executions>
          <execution>
            <phase>compile</phase>
            <goals>
              <goal>check</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>${javadoc.version}</version>
        <configuration>
          <doclet>org.asciidoctor.Asciidoclet</doclet>
          <docletArtifact>
            <groupId>org.asciidoctor</groupId>
            <artifactId>asciidoclet</artifactId>
            <version>${asciidoclet.version}</version>
          </docletArtifact>
          <additionalparam>--base-dir ${project.basedir}</additionalparam>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.asciidoctor</groupId>
        <artifactId>asciidoctor-maven-plugin</artifactId>
        <version>1.5.2</version>
        <executions>
          <execution>
            <id>output-html</id>
            <phase>pre-site</phase>
            <goals>
              <goal>process-asciidoc</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <sourceDirectory>docs</sourceDirectory>
          <outputDirectory>target/docs</outputDirectory>
          <backend>html</backend>
          <sourceHighlighter>coderay</sourceHighlighter>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>org.hamcrest</groupId>
          <artifactId>hamcrest-core</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest-all</artifactId>
      <version>1.3</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>io.dropwizard.metrics</groupId>
      <artifactId>metrics-core</artifactId>
      <version>3.1.0</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.hdrhistogram</groupId>
      <artifactId>HdrHistogram</artifactId>
      <version>2.1.2</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <reporting>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-project-info-reports-plugin</artifactId>
        <version>2.7</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>${javadoc.version}</version>
        <configuration>
          <doclet>org.asciidoctor.Asciidoclet</doclet>
          <docletArtifact>
            <groupId>org.asciidoctor</groupId>
            <artifactId>asciidoclet</artifactId>
            <version>${asciidoclet.version}</version>
          </docletArtifact>
          <additionalparam>--base-dir ${project.basedir}</additionalparam>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jxr-plugin</artifactId>
        <version>2.3</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-pmd-plugin</artifactId>
        <version>3.0.1</version>
        <configuration>
          <linkXRef>true</linkXRef>
          <sourceEncoding>utf-8</sourceEncoding>
          <targetJdk>${java.version}</targetJdk>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>${jacoco.version}</version>
      </plugin>
      <!-- Does not support Java 8 just yet -->
      <!--<plugin>-->
        <!--<groupId>org.codehaus.mojo</groupId>-->
        <!--<artifactId>findbugs-maven-plugin</artifactId>-->
        <!--<version>2.5.3</version>-->
        <!--<configuration>-->
          <!--<effort>Max</effort>-->
        <!--</configuration>-->
      <!--</plugin>-->
    </plugins>
  </reporting>
</project>


text:
<?php
class A {
    public static function foo() {}
}


text:
tsnug.learnedMomentsFromNow = function(commitment, numPastEvent) {

  var hoursPerSession = commitment.hoursPerSession;
  var sessionIndexSpan = hoursPerSession * 2;
  var numSessions = commitment.numSessions - numPastEvent;

  // obtain intervals of safe starts
  var intervals = tsnug.safeStarts(commitment.userId, hoursPerSession);
  if (_.isEmpty(intervals)) {
    return [];
  }

  // Return a list of indices of possible start times, in ascending order.
  var availableStartIndices = [];
  _.each(intervals, function(interval){
    var candidates = tsnug.findRoundingCandidates(interval[0], false);
    var candidate = _.find(candidates, function (candidate) {
      return tsnug.contains(interval, candidate);
    });
    var timeIndex =
      moment(candidate).diff(
        moment(candidate).startOf('week'), 'hours', true)*2;
    while(tsnug.contains(interval, candidate)){
      availableStartIndices.push(timeIndex++);
      candidate.add('hours', 0.5);
    }
  });

  // Sanity checks: given availableStartIndices, is it possible to generate
  // numSessions sessions of duration hoursPerSession?
  // Check 1: Simple arithmetic. Necessary but insufficient.
  if (numSessions > availableStartIndices.length) return [];
  // Check 2: A greedy solution. Assumes ascending availableStartIndices.
  var sessionCount = 0;
  var lastStartIdx = -sessionIndexSpan;
  for (var i=0; i < availableStartIndices.length; i++) {
    if (availableStartIndices[i] < lastStartIdx + sessionIndexSpan) continue;
    if (++sessionCount === numSessions) break;
    lastStartIdx = availableStartIndices[i];
  }
  if (sessionCount < numSessions) return [];

  // From preferences, generate ranking of available start indices.
  // Indices without preference are to be shuffled via randomly assigned
  // ranks in the range (-1, 0].
  // E.g., [{startIndex: 1, rank: -3},{startIndex: 3, rank: -5}]
  // means that Sun 12:30am has weight 3 and Sun 01:30am has weight 5.
  // Ranking is by absolute value.
  var prefs = commitment.prefs;
  var indexRank = _.map(availableStartIndices, function(i) {
    return {
      index: i,
      rank: _.has(prefs, i) ? -prefs[i] : -Math.random()
    };
  });
  var rankedIndices = _.pluck(_.sortBy(indexRank, 'rank'), 'index');

  // Generate an array of numSessions moments, each the start of a session.
  // Priority is successively given to each index by rank. While priority by
  // sum-of-weights would intuitively be more ideal, such a solution requires
  // exponential space.
  var iMax = rankedIndices.length - 1;

  // Each element in candidate represents an index in rankedIndices
  var candidate = new Array(numSessions);
  candidate[0] = 0;

  // Function to check collision of a new event with allocated events
  var compatibleCandidate = function (cIdx) {
    var cTimeIndex = rankedIndices[candidate[cIdx]];
    var allocatedInterval;
    var tmp;
    return _.every(candidate.slice(0,cIdx), function (c) {
      tmp = rankedIndices[c];
      // tsnug.contains is inclusive, hence the -1 in the line below
      allocatedInterval = [tmp, tmp + sessionIndexSpan - 1];
      return !tsnug.contains(allocatedInterval, cTimeIndex);
    });
  };

  var cIdx = 0;
  while (candidate[0] + (numSessions-1) <= iMax) {
    if (compatibleCandidate(cIdx)) {
      // Terminates when last session is compatible
      if (cIdx === numSessions - 1) {
        break;
      }
      cIdx++;
      candidate[cIdx] = candidate[cIdx-1];
    } else if (candidate[cIdx] + ((numSessions-cIdx)-1) > iMax) { // backtrack
      cIdx--;
    }
    candidate[cIdx] += 1;
  }
  if (candidate[0] + (numSessions-1) > iMax) return [];

  var startAts = _.map(candidate, function (c) {
    return rankedIndices[c];
  });
  var startOfWeek = moment(intervals[0][0]).startOf('week');
  return _.map(startAts, function(startAt){
    return moment(startOfWeek).add('hours', startAt/2);
  });
};