text:
package com.koch.ambeth.persistence.orm;

public interface IOrmPatternMatcher {
	boolean matchesSequencePattern(String potentialSequenceName);

	boolean matchesFieldPattern(String potentialFieldName);

	boolean matchesPermissionGroupPattern(String potentialPermissionGroupName);

	boolean matchesOptimisticLockTriggerPattern(String potentialOptimisticLockTriggerName);

	boolean matchesArchivePattern(String potentialArchiveName);

	boolean matchesTablePattern(String potentialTableName);

	String buildSequenceFromTableName(String tableName, int maxNameLength);

	String buildPermissionGroupFromTableName(String tableName, int maxNameLength);

	String buildOptimisticLockTriggerFromTableName(String tableName, int maxNameLength);

	String buildArchiveFromTableName(String tableName, int maxNameLength);

	String buildTableNameFromSoftName(String softName, int maxNameLength);

	String buildFieldNameFromSoftName(String softName, int maxNameLength);
}


text:
using std::istream;

istream& Student_info::read(istream& is)
{
	char ch;
	is >> ch;     // get record type

	// allocate new object of the appropriate type
	// use `Handle<T>(T*)' to build a `Handle<Core>' from the pointer to that object
	// call `Handle<T>::operator=' to assign the `Handle<Core>' to the left-hand side
	if (ch == 'U')
		cp = new Core(is);
	else
		cp = new Grad(is);

	return is;
}

redpajama_set_name: RedPajamaGithub


text:
module AParser where

import Control.Applicative

import Data.Char

-- A parser for a value of type a is a function which takes a String
-- represnting the input to be parsed, and succeeds or fails; if it
-- succeeds, it returns the parsed value along with the remainder of
-- the input.
newtype Parser a = Parser { runParser :: String -> Maybe (a, String) }

-- For example, 'satisfy' takes a predicate on Char, and constructs a
-- parser which succeeds only if it sees a Char that satisfies the
-- predicate (which it then returns).  If it encounters a Char that
-- does not satisfy the predicate (or an empty input), it fails.
satisfy :: (Char -> Bool) -> Parser Char
satisfy p = Parser f
  where
    f [] = Nothing    -- fail on the empty input
    f (x:xs)          -- check if x satisfies the predicate
                        -- if so, return x along with the remainder
                        -- of the input (that is, xs)
        | p x       = Just (x, xs)
        | otherwise = Nothing  -- otherwise, fail

-- Using satisfy, we can define the parser 'char c' which expects to
-- see exactly the character c, and fails otherwise.
char :: Char -> Parser Char
char c = satisfy (== c)

{- For example:

*Parser> runParser (satisfy isUpper) "ABC"
Just ('A',"BC")
*Parser> runParser (satisfy isUpper) "abc"
Nothing
*Parser> runParser (char 'x') "xyz"
Just ('x',"yz")

-}

-- For convenience, we've also provided a parser for positive
-- integers.
posInt :: Parser Integer
posInt = Parser f
  where
    f xs
      | null ns   = Nothing
      | otherwise = Just (read ns, rest)
      where (ns, rest) = span isDigit xs

------------------------------------------------------------
-- Your code goes below here
------------------------------------------------------------
first :: (a -> b) -> (a, c) -> (b, c)
first f (a, c) = (f a, c)

instance Functor Parser where
  fmap f (Parser rp) = Parser (fmap (first f) . rp)

instance Applicative Parser where
  pure a = Parser f
    where f str = Just (a, str)

  p1 <*> p2 = Parser f
    where
      f str = case runParser p1 str of
                Nothing -> Nothing
                Just (fRes, strRes) -> first fRes <$> runParser p2 strRes

      -- other possibility using pattern-guards
      {-f str-}
        {-| Nothing <- res             = Nothing-}
        {-| Just (fRes, strRes) <- res = first fRes <$> runParser p2 strRes-}
        {-where res = runParser p1 str-}

abParser :: Parser (Char, Char)
abParser = (,) <$> char 'a' <*> char 'b'

abParser_ :: Parser ()
abParser_ = const () <$> abParser

intPair :: Parser [Integer]
intPair = (\a _ b -> [a, b]) <$> posInt <*> char ' ' <*> posInt

instance Alternative Parser where
  empty = Parser (const Nothing)
  p1 <|> p2 = Parser f
    where f str = runParser p1 str <|> runParser p2 str

intOrUppercase :: Parser ()
intOrUppercase = const () <$> posInt <|> const () <$> satisfy isUpper


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/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>BeyondHooperville: com.mesaverde.village.Logger Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

BeyondHooperville

A Village Ecodynamics Project simulation

com

mesaverde

village

Logger

Classes |
Public Member Functions |
Static Public Attributes |
List of all members

com.mesaverde.village.Logger Class Reference

Classes

class  	file

Public Member Functions

void 	init ()

synchronized void 	write (String str, String filename, boolean usingYr, int yr)

Static Public Attributes

static int 	MAXLEN = 25

static int 	MAXFILES = 25

static String 	LOGDIR = "output"

static String 	LOGPREFIX = ""

static String 	LOGSUFFIX = ".csv"

static final boolean 	NO = false

static final boolean 	YES = true

Detailed Description

Unified data logging, avoids many redundant buffer flushed each sim year.

Examples of usage are in Agent.m in the methods saveLinks and saveLinksBRN.

Member Function Documentation

§ init()

          void com.mesaverde.village.Logger.init
          (
          	)

Initialize the file array to known values so the empty check works properly.

§ write()

          synchronized void com.mesaverde.village.Logger.write
          (
          String
          str,

          String
          filename,

          boolean
          usingYr,

          int
          yr

          )

Main logging function. Call this function to log output.

Give this function a string, a filename, a year and tell it whether to use the year in the filename. The string should not include the trailing newline. If you don't need a year, just pass 0 and set usingYear: NO.

Perhaps "filename" is too strong a word. The function is not limited to flat files. It could just as easily be adapted to write to a database. This is just the data storage name, such as "links." This function maintains its own open file handles and indexes by this name. In the current implementation, a call to this function using "links" as the filename and 649 as the year would generate a persistent file named "output/links649.out" and all subsequent calls using those parameters will write to that same file.

Parameters

str	The string to log. Should not include the trailing newline.

filename	The name of the file to write to

usingYr	Should the output file include the year?

yr	The current year of the simulation.

The documentation for this class was generated from the following file:

src/com/mesaverde/village/Logger.java

<address class="footer">
Generated by

 1.8.12
</address>


text:
import urllib2
from flask import jsonify, render_template, request
import base64

from Maraschino import app
from maraschino.tools import *
from maraschino import logger

foscammjeg_settings = {
    #uses base control
    'control_base': '/decoder_control.cgi?command=',
    'down': '0',
    'down_stop': '1',
    'up': '2',
    'up_stop': '3',
    'left': '4',
    'left_stop': '5',
    'right': '6',
    'right_stop': '7',
    'center': '25',
    'vertical_patrol': '26',
    'stop_vertical_patrol': '27',
    'horizontal_patrol': '28',
    'stop_horizontal_patrol': '29',
    'preset_1': '31',
    'preset_2': '33',
    'preset_3': '35',
    'preset_4': '37',
    'set_preset_1': '30',
    'set_preset_2': '32',
    'set_preset_3': '34',
    'set_preset_4': '36',
    'ir_off': '95',
    'ir_on': '94',
    # uses camera settigns
    'camera_settings': '/camera_control.cgi?param=',
    'oi_output_high': '94',
    'oi_output_low': '95',
    'resolution': '0',
    'resolution_qvga': '0&value=8',
    'resolution_vga': '0&value=32',
    'brightness': '1',
    'contrast': '2',
    'mode': '3',
    'fifty': '3&value=0',
    'sixty': '3&value=1',
    'outdoor': '3&value=2',
    'flippandmirror': '5',
    'default': '5&value=3',
    'flip': '5&value=1',
    'mirror': '5&value=2',
    'fam': '5&value=0',
    # uses set_alarm
    'set_alarm': '/set_alarm.cgi?',
    'motion_armed_on': '&motion_armed=1',
    'motion_armed_off': '&motion_armed=0',
    'motion_sensitivity_high': '&motion_sensitivity=0',
    'motion_sensitivity_medium': '&motion_sensitivity=1',
    'motion_sensitivity_low': '&motion_sensitivity=2',
    'motion_sensitivity_ultralow': '&motion_sensitivity=3',
    'input_armed_yes': '&input_armed=0',
    'input_armed_no': '&input_armed=1',
    # uses set_misc
    'set_misc': '/set_misc.cgi?',
    'led_mode_always_off': '&led_mode=2',
    'led_mode_blink' :'&led_mode=1' ,
    'led_mode_blink_once': '&led_mode=0',
    # stream urls
    'videostream': '/videostream.cgi'
    }

def camera_url(login=True):
    credentials = ''
    ip = get_setting_value('ipcamera_ip')
    port = get_setting_value('ipcamera_port')
    username = get_setting_value('ipcamera_username')
    password = get_setting_value('ipcamera_password')

    if login and username and password:
        credentials = '%s:%s@' % (username, password)

    return 'http://%s%s:%s' % (credentials, ip, port)

def send_camera_request(cat, arg):
    type = get_setting_value('ipcamera_type')
    username = get_setting_value('ipcamera_username')
    password = get_setting_value('ipcamera_password')
    url = camera_url(login=False)
    if type == 'foscammjeg':
        url += foscammjeg_settings[cat] + foscammjeg_settings[arg]
    elif type == 'foscammp4':
        url += foscammjeg_settings['control_base'] + foscammjeg_settings[arg]
    else:
        logger.log('IPCamera Error :: Missing camera type', 'INFO')

    try:
        r = urllib2.Request(url)
        if username and password:
            base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
            r.add_header('Authorization', 'Basic %s' % base64string)
        data = urllib2.urlopen(r).read()
        logger.log('IPCamera :: Webcam is to turn %s' % (arg), 'INFO')
    except Exception as e:
        data = False
        logger.log('IPCamera Error :: Error on %s -> %s call :: %s' % (cat, arg, e), 'DEBUG')

    return jsonify({'status': data})

@app.route('/xhr/ipcamera/')
@requires_auth
def rend_page():
    type = get_setting_value('ipcamera_type')
    stream_url = '%s/videostream.cgi' % (camera_url())
    if type == 'foscammjeg':
        return render_template('ipcamera/foscammjeg.html', stream_url=stream_url)
    elif type == 'foscammp4':
        return render_template('ipcamera/foscammp4.html', stream_url=stream_url)

@app.route('/xhr/ipcamera/<cat>/<arg>/')
@requires_auth
def camera(cat, arg):
    return send_camera_request(cat, arg)


text:
package org.kuali.kra.award;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.kuali.kra.award.commitments.AwardCostShareRuleEvent;
import org.kuali.kra.award.document.AwardDocument;
import org.kuali.kra.award.home.AwardSponsorTerm;
import org.kuali.kra.rule.event.KraDocumentEventBase;
import org.kuali.rice.krad.rules.rule.BusinessRule;

/**
 * AwardSponsorTermRuleEvent class for rule processing.
 */
public class AwardSponsorTermRuleEvent extends KraDocumentEventBase {

    private static final Log LOG = LogFactory.getLog(AwardCostShareRuleEvent.class);
    private AwardSponsorTerm awardSponsorTerm;
    private String sponsorTermCode;
    private int sponsorTermTypeCode;

    /**
     * Constructs a AwardSponsorTermRuleEvent.
     * @param errorPathPrefix
     * @param awardDocument
     * @param awardSponsorTerm
     * @param sponsorTermCode the sponsor term code from the HTTP request
     * @param sponsorTermTypeCode the index of the subpanel within the terms panel
     */
    public AwardSponsorTermRuleEvent(String errorPathPrefix,
                                           AwardDocument awardDocument,
                                           AwardSponsorTerm awardSponsorTerm,
                                           String sponsorTermCode,
                                           int sponsorTermTypeCode) {
        super("Cost Share", errorPathPrefix, awardDocument);
        this.awardSponsorTerm = awardSponsorTerm;
        this.sponsorTermCode = sponsorTermCode;
        this.sponsorTermTypeCode = sponsorTermTypeCode;
    }

    /**
     * Convenience method to return an AwardDocument
     * @return
     */
    public AwardDocument getAwardDocument() {
        return (AwardDocument) getDocument();
    }

    /**
     * This method returns the sponsor term for validation
     * @return
     */
    public AwardSponsorTerm getAwardSponsorTermForValidation() {
        return awardSponsorTerm;
    }

    public String getSponsorTermCode() {
        return sponsorTermCode;
    }

    public int getSponsorTermTypeCode() {
        return sponsorTermTypeCode;
    }

    /**
     * @see org.kuali.kra.rule.event.KraDocumentEventBase#logEvent()
     */
    @Override
    protected void logEvent() {
        LOG.info("Logging AwardSponsorTermRuleEvent");
    }

    /**
     * @see org.kuali.core.rule.event.KualiDocumentEvent#getRuleInterfaceClass()
     */
    @SuppressWarnings("unchecked")
    public Class getRuleInterfaceClass() {
        return AwardSponsorTermRule.class;
    }

    /**
     * @see org.kuali.core.rule.event.KualiDocumentEvent#invokeRuleMethod(org.kuali.core.rule.BusinessRule)
     */
    public boolean invokeRuleMethod(BusinessRule rule) {
        return ((AwardSponsorTermRule)rule).processAddSponsorTermBusinessRules(this);
    }

}


text:
package org.kie.workbench.common.stunner.bpmn.client.forms.fields.assigneeEditor;

import java.util.List;

import com.google.gwt.user.client.ui.IsWidget;
import org.kie.workbench.common.stunner.bpmn.client.forms.fields.model.AssigneeRow;
import org.kie.workbench.common.stunner.bpmn.client.forms.util.ListBoxValues;
import org.kie.workbench.common.stunner.bpmn.forms.model.AssigneeType;

public interface AssigneeEditorWidgetView extends IsWidget {

    interface Presenter {

        AssigneeType getType();

        Integer getMax();

        void doSave();

        void notifyModelChanged();

        List<AssigneeRow> deserializeAssignees(final String s);

        String serializeAssignees(final List<AssigneeRow> assigneeRows);

        void setNames(final List<String> names);

        void addAssignee();

        boolean isDuplicateName(final String name);

        void removeAssignee(final AssigneeRow assigneeRow);

        ListBoxValues.ValueTester namesTester();
    }

    void init(final Presenter presenter);

    void doSave();

    int getAssigneeRowsCount();

    void setTableDisplayStyle();

    void setNoneDisplayStyle();

    void setAssigneesNames(final ListBoxValues nameListBoxValues);

    void setAssigneeRows(final List<AssigneeRow> rows);

    List<AssigneeRow> getAssigneeRows();

    AssigneeListItemWidgetView getAssigneeWidget(final int index);

    boolean isDuplicateName(final String name);

    void showMaxAssigneesAdded();
}


text:
#include "ctkNetworkConnectorZeroMQ.h"
#include "ctkEventBusManager.h"

#include <service/event/ctkEvent.h>

using namespace ctkEventBus;

ctkNetworkConnectorZeroMQ::ctkNetworkConnectorZeroMQ() : ctkNetworkConnector() {

    m_Protocol = "SOCKET";
}

void ctkNetworkConnectorZeroMQ::initializeForEventBus() {
    //ctkRegisterRemoteSignal("ctk/remote/eventBus/comunication/??????????", this, "remoteCommunication(const QString, ctkEventArgumentsList *)");
    //ctkRegisterRemoteCallback("ctk/remote/eventBus/comunication/????????????", this, "send(const QString, ctkEventArgumentsList *)");
}

ctkNetworkConnectorZeroMQ::~ctkNetworkConnectorZeroMQ() {
    }

//retrieve an instance of the object
ctkNetworkConnector *ctkNetworkConnectorZeroMQ::clone() {
    ctkNetworkConnectorZeroMQ *copy = new ctkNetworkConnectorZeroMQ();
    return copy;
}

void ctkNetworkConnectorZeroMQ::createClient(const QString hostName, const unsigned int port) {
    Q_UNUSED(hostName);
    Q_UNUSED(port);
    //@@ TODO
}

void ctkNetworkConnectorZeroMQ::createServer(const unsigned int port) {
   Q_UNUSED(port);
   //@@ TODO
}

void ctkNetworkConnectorZeroMQ::stopServer() {
    //@@ TODO
}

void ctkNetworkConnectorZeroMQ::startListen() {
    //@@ TODO
}

void ctkNetworkConnectorZeroMQ::send(const QString event_id, ctkEventArgumentsList *argList) {
	Q_UNUSED(event_id);
	Q_UNUSED(argList);
    //@@ TODO
}

void ctkNetworkConnectorZeroMQ::processReturnValue( int requestId, QVariant value ) {
	Q_UNUSED(requestId);
	Q_UNUSED(value);
    //@@ TODO
}


text:
<?php

/**
 * Exception class for exceptions thrown by Horde_Yaml
 *
 * @category Horde
 * @package  Horde_Yaml
 */
class Horde_Yaml_Exception extends Horde_Exception_LastError
{
}


text:
## PHPUnit 4.2.5

* New release of PHPUnit as PHP Archive (PHAR) with updated dependencies

## PHPUnit 4.2.4

* Fixed [#1413](https://github.com/sebastianbergmann/phpunit/issues/1413): `assertCount()` hangs in infinite loop on HHVM

## PHPUnit 4.2.3

* Fixed [#1403](https://github.com/sebastianbergmann/phpunit/issues/1403): `phpunit --self-update` does not work

## PHPUnit 4.2.2

* Fixed [#1399](https://github.com/sebastianbergmann/phpunit/issues/1399): `enforceTimeLimit` configuration option is not handled

## PHPUnit 4.2.1

* Fixed [#1380](https://github.com/sebastianbergmann/phpunit/issues/1380): `assertMatch()` returns `Unexpected end tag : hr`
* Fixed [#1390](https://github.com/sebastianbergmann/phpunit/issues/1390): Licensing issue with third-party components bundled in PHAR distribution

## PHPUnit 4.2.0

* Tests annotated with `@todo` will now be reported as risky when the `--disallow-todo-tests` option is used or `beStrictAboutTodoAnnotatedTests=true` is set in the configuration file
* The `atLeast()` and `atMost()` invocation count matchers were added
* The `assertTag()` and `assertSelect*()` assertion methods have been deprecated in favor of the [phpunit-dom-assertions](https://github.com/phpunit/phpunit-dom-assertions) extension; these methods will be removed in PHPUnit 5.0
* `trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);` is used now to indicate that a PHPUnit API method is deprecated; the old "system" for deprecating methods has been removed
* The PHP Archive (PHAR) distribution of PHPUnit can now be used as a library; `include()`ing or `require()`ing it will not execute the CLI test runner


text:
package monix.tail
package internal

import cats.effect.Sync
import cats.syntax.all._
import monix.execution.internal.collection.ChunkedArrayStack

import scala.util.control.NonFatal
import monix.tail.Iterant.{Concat, Halt, Last, Next, NextBatch, NextCursor, Scope, Suspend}
import monix.tail.batches.BatchCursor

import scala.collection.mutable.ArrayBuffer

private[tail] object IterantScan {
  /** Implementation for `Iterant#scan`. */
  def apply[F[_], A, S](fa: Iterant[F, A], initial: => S, f: (S, A) => S)(implicit F: Sync[F]): Iterant[F, S] = {
    // Given that `initial` is a by-name value, we have
    // to suspend
    val task = F.delay {
      try new Loop(initial, f).apply(fa)
      catch { case e if NonFatal(e) => Halt[F, S](Some(e)) }
    }
    Suspend(task)
  }

  class Loop[F[_], A, S](initial: S, f: (S, A) => S)(implicit F: Sync[F]) extends Iterant.Visitor[F, A, Iterant[F, S]] {

    private[this] var state = initial
    private[this] var stackRef: ChunkedArrayStack[F[Iterant[F, A]]] = _

    private def stackPush(item: F[Iterant[F, A]]): Unit = {
      if (stackRef == null) stackRef = ChunkedArrayStack()
      stackRef.push(item)
    }

    private def stackPop(): F[Iterant[F, A]] = {
      if (stackRef != null) stackRef.pop()
      else null.asInstanceOf[F[Iterant[F, A]]]
    }

    def visit(ref: Next[F, A]): Iterant[F, S] = {
      state = f(state, ref.item)
      Next(state, ref.rest.map(this))
    }

    def visit(ref: NextBatch[F, A]): Iterant[F, S] =
      processCursor(ref.batch.cursor(), ref.rest)

    def visit(ref: NextCursor[F, A]): Iterant[F, S] =
      processCursor(ref.cursor, ref.rest)

    def visit(ref: Suspend[F, A]): Iterant[F, S] =
      Suspend(ref.rest.map(this))

    def visit(ref: Concat[F, A]): Iterant[F, S] = {
      stackPush(ref.rh)
      Suspend(ref.lh.map(this))
    }

    def visit[R](ref: Scope[F, R, A]): Iterant[F, S] =
      ref.runMap(this)

    def visit(ref: Last[F, A]): Iterant[F, S] = {
      state = f(state, ref.item)
      stackPop() match {
        case null => Last(state)
        case next => Next(state, next.map(this))
      }
    }

    def visit(ref: Halt[F, A]): Iterant[F, S] =
      ref.e match {
        case Some(_) =>
          ref.asInstanceOf[Iterant[F, S]]
        case None =>
          stackPop() match {
            case null =>
              ref.asInstanceOf[Iterant[F, S]]
            case next =>
              Suspend(next.map(this))
          }
      }

    def fail(e: Throwable): Iterant[F, S] =
      Iterant.raiseError(e)

    private[this] def processCursor(cursor: BatchCursor[A], rest: F[Iterant[F, A]]) = {
      if (!cursor.hasNext()) {
        Suspend(rest.map(this))
      } else if (cursor.recommendedBatchSize <= 1) {
        state = f(state, cursor.next())
        val next: F[Iterant[F, A]] =
          if (cursor.hasNext()) F.pure(NextCursor(cursor, rest))
          else rest

        Next(state, next.map(this))
      } else {
        val buffer = ArrayBuffer.empty[S]
        var toProcess = cursor.recommendedBatchSize

        while (toProcess > 0 && cursor.hasNext()) {
          state = f(state, cursor.next())
          buffer += state
          toProcess -= 1
        }

        val next: F[Iterant[F, A]] =
          if (cursor.hasNext()) F.pure(NextCursor(cursor, rest))
          else rest

        val elems = BatchCursor.fromArray(buffer.toArray[Any]).asInstanceOf[BatchCursor[S]]
        NextCursor(elems, next.map(this))
      }
    }
  }
}


text:
//
// OrcScriptException.java -- Java class OrcScriptException
// Project OrcScala
//
// Created by jthywiss on Aug 3, 2010.
//
// Copyright (c) 2017 The University of Texas at Austin. All rights reserved.
//
// Use and redistribution of this file is governed by the license terms in
// the LICENSE file found in the project's top-level directory and also found at
// URL: http://orc.csres.utexas.edu/license.shtml .
//

package orc.script;

import java.io.PrintStream;
import java.io.PrintWriter;

import javax.script.ScriptException;

import orc.compile.parse.OrcSourceRange;
import orc.error.OrcException;

/**
 * A ScriptException proxy for an OrcException
 *
 * @author jthywiss
 */
public class OrcScriptException extends ScriptException {
    private static final long serialVersionUID = 8541712728830055894L;

    private final OrcException orcE;

    /**
     * Constructs an object of class OrcScriptException.
     *
     * @param e
     */
    public OrcScriptException(final OrcException e) {
        super(e);
        orcE = e;
    }

    @Override
    public String getFileName() {
        final OrcSourceRange pos = orcE.getPosition();
        if (pos != null) {
            return pos.start().resource().descr();
        } else {
            return "";
        }
    }

    @Override
    public int getLineNumber() {
        final OrcSourceRange pos = orcE.getPosition();
        if (pos != null) {
            return pos.start().line();
        } else {
            return -1;
        }
    }

    @Override
    public int getColumnNumber() {
        final OrcSourceRange pos = orcE.getPosition();
        if (pos != null) {
            return pos.start().column();
        } else {
            return -1;
        }
    }

    @Override
    public String getMessage() {
        return orcE.getMessage();
    }

    @Override
    public synchronized Throwable fillInStackTrace() {
        throw new UnsupportedOperationException("OrcScriptException.fillInStackTrace is not supported");
    }

    @Override
    synchronized public Throwable getCause() {
        return orcE.getCause();
    }

    @Override
    public String getLocalizedMessage() {
        return orcE.getLocalizedMessage();
    }

    @Override
    public StackTraceElement[] getStackTrace() {
        return orcE.getStackTrace();
    }

    @Override
    public synchronized Throwable initCause(final Throwable cause) {
        throw new UnsupportedOperationException("OrcScriptException.initCause is not supported");
    }

    @Override
    public void printStackTrace() {
        orcE.printStackTrace();
    }

    @Override
    public void printStackTrace(final PrintStream s) {
        orcE.printStackTrace(s);
    }

    @Override
    public void printStackTrace(final PrintWriter s) {
        orcE.printStackTrace(s);
    }

    @Override
    public void setStackTrace(final StackTraceElement[] stackTrace) {
        throw new UnsupportedOperationException("OrcScriptException.setStackTrace is not supported");
    }

    @Override
    public String toString() {
        return orcE.toString();
    }

}


text:
class A {
    get p() { return 'oh no' }
}
class B extends A {
    p = 'yep' // error
}
class C {
    _secret = 11
    get p() { return this._secret }
    set p(value) { this._secret = value }
}
class D extends C {
    p = 101 // error
}

//// [propertyOverridesAccessors.js]
class A {
    get p() { return 'oh no'; }
}
class B extends A {
    constructor() {
        super(...arguments);
        Object.defineProperty(this, "p", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: 'yep'
        }); // error
    }
}
class C {
    constructor() {
        Object.defineProperty(this, "_secret", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: 11
        });
    }
    get p() { return this._secret; }
    set p(value) { this._secret = value; }
}
class D extends C {
    constructor() {
        super(...arguments);
        Object.defineProperty(this, "p", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: 101
        }); // error
    }
}


text:
package org.apache.asterix.common.annotations;

public class DateBetweenYearsDataGen implements IRecordFieldDataGen {

    private final int minYear;
    private final int maxYear;

    public DateBetweenYearsDataGen(int minYear, int maxYear) {
        this.minYear = minYear;
        this.maxYear = maxYear;
    }

    @Override
    public Kind getKind() {
        return Kind.DATEBETWEENYEARS;
    }

    public int getMinYear() {
        return minYear;
    }

    public int getMaxYear() {
        return maxYear;
    }

}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('config', '0002_config'),
    ]

    operations = [
        migrations.AddField(
            model_name='config',
            name='seo_description',
            field=models.CharField(max_length=255, blank=True),
        ),
    ]


text:
package org.hisp.dhis.expression;

import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.Boolean.FALSE;
import static org.hisp.dhis.antlr.AntlrParserUtils.castBoolean;
import static org.hisp.dhis.antlr.AntlrParserUtils.castDouble;
import static org.hisp.dhis.antlr.AntlrParserUtils.castString;
import static org.hisp.dhis.common.DimensionItemType.DATA_ELEMENT_OPERAND;
import static org.hisp.dhis.expression.MissingValueStrategy.NEVER_SKIP;
import static org.hisp.dhis.expression.MissingValueStrategy.SKIP_IF_ALL_VALUES_MISSING;
import static org.hisp.dhis.expression.ParseType.INDICATOR_EXPRESSION;
import static org.hisp.dhis.expression.ParseType.PREDICTOR_EXPRESSION;
import static org.hisp.dhis.expression.ParseType.PREDICTOR_SKIP_TEST;
import static org.hisp.dhis.expression.ParseType.SIMPLE_TEST;
import static org.hisp.dhis.expression.ParseType.VALIDATION_RULE_EXPRESSION;
import static org.hisp.dhis.parser.expression.ExpressionItem.ITEM_EVALUATE;
import static org.hisp.dhis.parser.expression.ExpressionItem.ITEM_GET_DESCRIPTIONS;
import static org.hisp.dhis.parser.expression.ExpressionItem.ITEM_GET_EXPRESSION_INFO;
import static org.hisp.dhis.parser.expression.ParserUtils.COMMON_EXPRESSION_ITEMS;
import static org.hisp.dhis.parser.expression.ParserUtils.DOUBLE_VALUE_IF_NULL;
import static org.hisp.dhis.parser.expression.antlr.ExpressionLexer.SUB_EXPRESSION;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.AGGREGATION_TYPE;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.AVG;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.A_BRACE;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.COUNT;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.DAYS;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.D_BRACE;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.HASH_BRACE;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.I_BRACE;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.MAX;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.MAX_DATE;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.MEDIAN;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.MIN;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.MIN_DATE;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.N_BRACE;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.ORGUNIT_ANCESTOR;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.ORGUNIT_DATASET;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.ORGUNIT_GROUP;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.ORGUNIT_PROGRAM;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.OUG_BRACE;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.PERCENTILE_CONT;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.PERIOD_OFFSET;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.R_BRACE;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.STDDEV;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.STDDEV_POP;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.STDDEV_SAMP;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.SUM;
import static org.springframework.util.ObjectUtils.isEmpty;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.hisp.dhis.analytics.DataType;
import org.hisp.dhis.antlr.Parser;
import org.hisp.dhis.antlr.ParserException;
import org.hisp.dhis.cache.Cache;
import org.hisp.dhis.cache.CacheProvider;
import org.hisp.dhis.common.BaseIdentifiableObject;
import org.hisp.dhis.common.DimensionService;
import org.hisp.dhis.common.DimensionalItemId;
import org.hisp.dhis.common.DimensionalItemObject;
import org.hisp.dhis.common.IdScheme;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.common.IdentifiableObjectManager;
import org.hisp.dhis.common.IdentifiableObjectUtils;
import org.hisp.dhis.commons.collection.CachingMap;
import org.hisp.dhis.commons.util.TextUtils;
import org.hisp.dhis.constant.Constant;
import org.hisp.dhis.constant.ConstantService;
import org.hisp.dhis.dataset.DataSet;
import org.hisp.dhis.expression.dataitem.DimItemDataElementAndOperand;
import org.hisp.dhis.expression.dataitem.DimItemIndicator;
import org.hisp.dhis.expression.dataitem.DimItemProgramAttribute;
import org.hisp.dhis.expression.dataitem.DimItemProgramDataElement;
import org.hisp.dhis.expression.dataitem.DimItemProgramIndicator;
import org.hisp.dhis.expression.dataitem.DimItemReportingRate;
import org.hisp.dhis.expression.dataitem.ItemDays;
import org.hisp.dhis.expression.dataitem.ItemOrgUnitGroupCount;
import org.hisp.dhis.expression.function.FunctionOrgUnitAncestor;
import org.hisp.dhis.expression.function.FunctionOrgUnitDataSet;
import org.hisp.dhis.expression.function.FunctionOrgUnitGroup;
import org.hisp.dhis.expression.function.FunctionOrgUnitProgram;
import org.hisp.dhis.expression.function.FunctionSubExpression;
import org.hisp.dhis.hibernate.HibernateGenericStore;
import org.hisp.dhis.i18n.I18nManager;
import org.hisp.dhis.indicator.Indicator;
import org.hisp.dhis.indicator.IndicatorValue;
import org.hisp.dhis.jdbc.StatementBuilder;
import org.hisp.dhis.organisationunit.OrganisationUnitGroup;
import org.hisp.dhis.parser.expression.CommonExpressionVisitor;
import org.hisp.dhis.parser.expression.ExpressionItem;
import org.hisp.dhis.parser.expression.ExpressionItemMethod;
import org.hisp.dhis.parser.expression.ExpressionState;
import org.hisp.dhis.parser.expression.function.FunctionAggregationType;
import org.hisp.dhis.parser.expression.function.FunctionMaxDate;
import org.hisp.dhis.parser.expression.function.FunctionMinDate;
import org.hisp.dhis.parser.expression.function.PeriodOffset;
import org.hisp.dhis.parser.expression.function.VectorAvg;
import org.hisp.dhis.parser.expression.function.VectorCount;
import org.hisp.dhis.parser.expression.function.VectorMax;
import org.hisp.dhis.parser.expression.function.VectorMedian;
import org.hisp.dhis.parser.expression.function.VectorMin;
import org.hisp.dhis.parser.expression.function.VectorPercentileCont;
import org.hisp.dhis.parser.expression.function.VectorStddevPop;
import org.hisp.dhis.parser.expression.function.VectorStddevSamp;
import org.hisp.dhis.parser.expression.function.VectorSum;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.util.DateUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.ImmutableMap;

/**
 * The expression is a string describing a formula containing data element ids
 * and category option combo ids. The formula can potentially contain references
 * to data element totals.
 *
 * @author Margrethe Store
 * @author Lars Helge Overland
 * @author Jim Grace
 */
@Slf4j
@Service( "org.hisp.dhis.expression.ExpressionService" )
public class DefaultExpressionService
    implements ExpressionService
{
    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    private final HibernateGenericStore<Expression> expressionStore;

    private final ConstantService constantService;

    private final DimensionService dimensionService;

    private final IdentifiableObjectManager idObjectManager;

    private final StatementBuilder statementBuilder;

    private final I18nManager i18nManager;

    // -------------------------------------------------------------------------
    // Static data
    // -------------------------------------------------------------------------

    private static final ImmutableMap<Integer, ExpressionItem> BASE_EXPRESSION_ITEMS = ImmutableMap
        .<Integer, ExpressionItem> builder()
        .putAll( COMMON_EXPRESSION_ITEMS )
        .put( HASH_BRACE, new DimItemDataElementAndOperand() )
        .put( A_BRACE, new DimItemProgramAttribute() )
        .put( D_BRACE, new DimItemProgramDataElement() )
        .put( I_BRACE, new DimItemProgramIndicator() )
        .put( OUG_BRACE, new ItemOrgUnitGroupCount() )
        .put( R_BRACE, new DimItemReportingRate() )
        .put( DAYS, new ItemDays() )
        .build();

    private static final ImmutableMap<Integer, ExpressionItem> VALIDATION_RULE_EXPRESSION_ITEMS = ImmutableMap
        .<Integer, ExpressionItem> builder()
        .putAll( BASE_EXPRESSION_ITEMS )
        .put( ORGUNIT_ANCESTOR, new FunctionOrgUnitAncestor() )
        .put( ORGUNIT_DATASET, new FunctionOrgUnitDataSet() )
        .put( ORGUNIT_GROUP, new FunctionOrgUnitGroup() )
        .put( ORGUNIT_PROGRAM, new FunctionOrgUnitProgram() )
        .build();

    private static final ImmutableMap<Integer, ExpressionItem> PREDICTOR_EXPRESSION_ITEMS = ImmutableMap
        .<Integer, ExpressionItem> builder()
        .putAll( VALIDATION_RULE_EXPRESSION_ITEMS )
        .put( AVG, new VectorAvg() )
        .put( COUNT, new VectorCount() )
        .put( MAX, new VectorMax() )
        .put( MEDIAN, new VectorMedian() )
        .put( MIN, new VectorMin() )
        .put( PERCENTILE_CONT, new VectorPercentileCont() )
        .put( STDDEV, new VectorStddevSamp() )
        .put( STDDEV_POP, new VectorStddevPop() )
        .put( STDDEV_SAMP, new VectorStddevSamp() )
        .put( SUM, new VectorSum() )
        .build();

    private static final ImmutableMap<Integer, ExpressionItem> INDICATOR_EXPRESSION_ITEMS = ImmutableMap
        .<Integer, ExpressionItem> builder()
        .putAll( BASE_EXPRESSION_ITEMS )
        .put( AGGREGATION_TYPE, new FunctionAggregationType() )
        .put( N_BRACE, new DimItemIndicator() )
        .put( MAX_DATE, new FunctionMaxDate() )
        .put( MIN_DATE, new FunctionMinDate() )
        .put( PERIOD_OFFSET, new PeriodOffset() )
        .put( SUB_EXPRESSION, new FunctionSubExpression() )
        .build();

    private static final ImmutableMap<ParseType, ImmutableMap<Integer, ExpressionItem>> PARSE_TYPE_EXPRESSION_ITEMS = ImmutableMap
        .<ParseType, ImmutableMap<Integer, ExpressionItem>> builder()
        .put( INDICATOR_EXPRESSION, INDICATOR_EXPRESSION_ITEMS )
        .put( VALIDATION_RULE_EXPRESSION, VALIDATION_RULE_EXPRESSION_ITEMS )
        .put( PREDICTOR_EXPRESSION, PREDICTOR_EXPRESSION_ITEMS )
        .put( PREDICTOR_SKIP_TEST, PREDICTOR_EXPRESSION_ITEMS )
        .put( SIMPLE_TEST, COMMON_EXPRESSION_ITEMS )
        .build();

    private static final String CONSTANT_EXPRESSION = "C\\{(?<id>[a-zA-Z]\\w{10})\\}";

    private static final String OU_GROUP_EXPRESSION = "OUG\\{(?<id>[a-zA-Z]\\w{10})\\}";

    private static final String GROUP_ID = "id";

    private static final String NULL_REPLACEMENT = "0";

    /**
     * Constant pattern. Contains the named group {@code id}.
     */
    private static final Pattern CONSTANT_PATTERN = Pattern.compile( CONSTANT_EXPRESSION );

    /**
     * Organisation unit groups pattern. Contains the named group {@code id}.
     */
    private static final Pattern OU_GROUP_PATTERN = Pattern.compile( OU_GROUP_EXPRESSION );

    // -------------------------------------------------------------------------
    // Cache
    // -------------------------------------------------------------------------

    /**
     * Cache for the constant map.
     */
    private final Cache<Map<String, Constant>> constantMapCache;

    // -------------------------------------------------------------------------
    // Constructor
    // -------------------------------------------------------------------------

    public DefaultExpressionService(
        @Qualifier( "org.hisp.dhis.expression.ExpressionStore" ) HibernateGenericStore<Expression> expressionStore,
        ConstantService constantService, DimensionService dimensionService, IdentifiableObjectManager idObjectManager,
        StatementBuilder statementBuilder, I18nManager i18nManager, CacheProvider cacheProvider )
    {
        checkNotNull( expressionStore );
        checkNotNull( constantService );
        checkNotNull( dimensionService );
        checkNotNull( idObjectManager );
        checkNotNull( statementBuilder );
        checkNotNull( i18nManager );
        checkNotNull( cacheProvider );

        this.expressionStore = expressionStore;
        this.constantService = constantService;
        this.dimensionService = dimensionService;
        this.idObjectManager = idObjectManager;
        this.statementBuilder = statementBuilder;
        this.i18nManager = i18nManager;
        this.constantMapCache = cacheProvider.createAllConstantsCache();

        FunctionSubExpression fn = (FunctionSubExpression) INDICATOR_EXPRESSION_ITEMS.get( SUB_EXPRESSION );
        if ( fn != null )
        {
            fn.init( cacheProvider );
        }
    }

    // -------------------------------------------------------------------------
    // Expression CRUD operations
    // -------------------------------------------------------------------------

    @Override
    @Transactional
    public long addExpression( Expression expression )
    {
        expressionStore.save( expression );

        return expression.getId();
    }

    @Override
    @Transactional
    public void updateExpression( Expression expression )
    {
        expressionStore.update( expression );
    }

    @Override
    @Transactional
    public void deleteExpression( Expression expression )
    {
        expressionStore.delete( expression );
    }

    @Override
    @Transactional( readOnly = true )
    public Expression getExpression( long id )
    {
        return expressionStore.get( id );
    }

    @Override
    @Transactional( readOnly = true )
    public List<Expression> getAllExpressions()
    {
        return expressionStore.getAll();
    }

    // -------------------------------------------------------------------------
    // Indicator expression logic
    // -------------------------------------------------------------------------

    @Override
    public Map<DimensionalItemId, DimensionalItemObject> getIndicatorDimensionalItemMap(
        Collection<Indicator> indicators )
    {
        Set<DimensionalItemId> itemIds = indicators.stream()
            .flatMap( i -> Stream.of( i.getNumerator(), i.getDenominator() ) )
            .map( e -> getExpressionDimensionalItemIds( e, INDICATOR_EXPRESSION ) )
            .flatMap( Set::stream )
            .collect( Collectors.toSet() );

        return dimensionService.getDataDimensionalItemObjectMap( itemIds );
    }

    @Override
    public List<OrganisationUnitGroup> getOrgUnitGroupCountGroups( Collection<Indicator> indicators )
    {
        if ( indicators == null )
        {
            return Collections.emptyList();
        }

        Set<String> uids = new HashSet<>();

        for ( Indicator indicator : indicators )
        {
            uids.addAll( getOrgUnitGroupCountIds( indicator.getNumerator() ) );
            uids.addAll( getOrgUnitGroupCountIds( indicator.getDenominator() ) );
        }

        return idObjectManager.getByUid( OrganisationUnitGroup.class, uids );
    }

    @Override
    public IndicatorValue getIndicatorValueObject( Indicator indicator, List<Period> periods,
        Map<DimensionalItemId, DimensionalItemObject> itemMap, Map<DimensionalItemObject, Object> valueMap,
        Map<String, Integer> orgUnitCountMap )
    {
        if ( indicator == null || indicator.getNumerator() == null || indicator.getDenominator() == null )
        {
            return null;
        }

        Integer days = periods != null ? getDaysFromPeriods( periods ) : null;

        ExpressionParams params = ExpressionParams.builder()
            .parseType( INDICATOR_EXPRESSION )
            .itemMap( itemMap )
            .valueMap( valueMap )
            .orgUnitCountMap( orgUnitCountMap )
            .days( days )
            .missingValueStrategy( SKIP_IF_ALL_VALUES_MISSING )
            .build();

        Double denominatorValue = castDouble( getExpressionValue( params.toBuilder()
            .expression( indicator.getDenominator() ).build() ) );

        Double numeratorValue = castDouble( getExpressionValue( params.toBuilder()
            .expression( indicator.getNumerator() ).build() ) );

        if ( denominatorValue != null && denominatorValue != 0d && numeratorValue != null )
        {
            int multiplier = indicator.getIndicatorType().getFactor();

            int divisor = 1;

            if ( indicator.isAnnualized() && periods != null )
            {
                final int daysInPeriod = getDaysFromPeriods( periods );

                multiplier *= DateUtils.DAYS_IN_YEAR;

                divisor = daysInPeriod;
            }

            return new IndicatorValue()
                .setNumeratorValue( numeratorValue )
                .setDenominatorValue( denominatorValue )
                .setMultiplier( multiplier )
                .setDivisor( divisor );
        }

        return null;
    }

    @Override
    @Transactional
    public void substituteIndicatorExpressions( Collection<Indicator> indicators )
    {
        if ( indicators == null || indicators.isEmpty() )
        {
            return;
        }

        Map<String, Constant> constants = new CachingMap<String, Constant>()
            .load( idObjectManager.getAllNoAcl( Constant.class ), BaseIdentifiableObject::getUid );

        Map<String, OrganisationUnitGroup> orgUnitGroups = new CachingMap<String, OrganisationUnitGroup>()
            .load( idObjectManager.getAllNoAcl( OrganisationUnitGroup.class ), BaseIdentifiableObject::getUid );

        for ( Indicator indicator : indicators )
        {
            indicator.setExplodedNumerator(
                regenerateIndicatorExpression( indicator.getNumerator(), constants, orgUnitGroups ) );
            indicator.setExplodedDenominator(
                regenerateIndicatorExpression( indicator.getDenominator(), constants, orgUnitGroups ) );
        }
    }

    // -------------------------------------------------------------------------
    // Get information about the expression
    // -------------------------------------------------------------------------

    @Override
    @Transactional
    public ExpressionValidationOutcome expressionIsValid( String expression, ParseType parseType )
    {
        try
        {
            getExpressionDescription( expression, parseType );

            return ExpressionValidationOutcome.VALID;
        }
        catch ( IllegalStateException e )
        {
            return ExpressionValidationOutcome.EXPRESSION_IS_NOT_WELL_FORMED;
        }
    }

    @Override
    public String getExpressionDescription( String expression, ParseType parseType )
    {
        return getExpressionDescription( expression, parseType, parseType.getDataType() );
    }

    @Override
    public String getExpressionDescription( String expression, ParseType parseType, DataType dataType )
    {
        if ( isEmpty( expression ) )
        {
            return "";
        }

        CommonExpressionVisitor visitor = newVisitor( ITEM_GET_DESCRIPTIONS, ExpressionParams.builder()
            .expression( expression )
            .parseType( parseType )
            .dataType( dataType )
            .missingValueStrategy( NEVER_SKIP )
            .build() );

        visit( expression, dataType, visitor, false );

        Map<String, String> itemDescriptions = visitor.getItemDescriptions();

        String description = expression;

        for ( Map.Entry<String, String> entry : itemDescriptions.entrySet() )
        {
            description = description.replace( entry.getKey(), entry.getValue() );
        }

        return description;
    }

    @Override
    public ExpressionInfo getExpressionInfo( ExpressionParams params )
    {
        if ( StringUtils.isEmpty( params.getExpression() ) )
        {
            return new ExpressionInfo();
        }

        CommonExpressionVisitor visitor = newVisitor( ITEM_GET_EXPRESSION_INFO, params );

        visit( params.getExpression(), params.getDataType(), visitor, true );

        return visitor.getInfo();
    }

    @Override
    public ExpressionParams getBaseExpressionParams( ExpressionInfo info )
    {
        return ExpressionParams.builder()
            .itemMap( dimensionService.getNoAclDataDimensionalItemObjectMap( info.getAllItemIds() ) )
            .orgUnitGroupMap( getUidMap( OrganisationUnitGroup.class, info.getOrgUnitGroupIds() ) )
            .dataSetMap( getUidMap( DataSet.class, info.getOrgUnitDataSetIds() ) )
            .programMap( getUidMap( Program.class, info.getOrgUnitProgramIds() ) )
            .build();
    }

    @Override
    public Set<String> getExpressionElementAndOptionComboIds( String expression, ParseType parseType )
    {
        return getExpressionDimensionalItemIds( expression, parseType ).stream()
            .filter( DimensionalItemId::isDataElementOrOperand )
            .map( i -> i.getId0() + (i.getId1() == null ? "" : Expression.SEPARATOR + i.getId1()) )
            .collect( Collectors.toSet() );
    }

    @Override
    public Set<String> getExpressionDataElementIds( String expression, ParseType parseType )
    {
        return getExpressionDimensionalItemIds( expression, parseType ).stream()
            .filter( DimensionalItemId::isDataElementOrOperand )
            .map( DimensionalItemId::getId0 )
            .collect( Collectors.toSet() );
    }

    @Override
    public Set<String> getExpressionOptionComboIds( String expression, ParseType parseType )
    {
        Set<String> categoryOptionComboIds = new HashSet<>();

        for ( DimensionalItemId itemId : getExpressionDimensionalItemIds( expression, parseType ) )
        {
            if ( itemId.getDimensionItemType() == DATA_ELEMENT_OPERAND )
            {
                if ( itemId.getId1() != null )
                {
                    categoryOptionComboIds.add( itemId.getId1() );
                }
                if ( itemId.getId2() != null )
                {
                    categoryOptionComboIds.add( itemId.getId2() );
                }
            }
        }

        return categoryOptionComboIds;
    }

    @Override
    public Set<DimensionalItemId> getExpressionDimensionalItemIds( String expression, ParseType parseType )
    {
        Set<DimensionalItemId> itemIds = new HashSet<>();

        getExpressionDimensionalItemIds( expression, parseType, itemIds, itemIds );

        return itemIds;
    }

    @Override
    public Set<String> getExpressionOrgUnitGroupIds( String expression, ParseType parseType )
    {
        if ( isEmpty( expression ) )
        {
            return Collections.emptySet();
        }

        ExpressionInfo info = getExpressionInfo( ExpressionParams.builder()
            .expression( expression )
            .parseType( parseType )
            .build() );

        return info.getOrgUnitGroupIds();
    }

    // -------------------------------------------------------------------------
    // Compute the value of the expression
    // -------------------------------------------------------------------------

    @Override
    public Object getExpressionValue( ExpressionParams params )
    {
        if ( isEmpty( params.getExpression() ) )
        {
            return null;
        }

        CommonExpressionVisitor visitor = newVisitor( ITEM_EVALUATE, params );

        Object value = visit( params.getExpression(), params.getDataType(), visitor, true );

        ExpressionState state = visitor.getState();

        int itemsFound = state.getItemsFound();
        int itemValuesFound = state.getItemValuesFound();

        if ( state.isUnprotectedNullDateFound() )
        {
            return null;
        }

        switch ( params.getMissingValueStrategy() )
        {
        case SKIP_IF_ANY_VALUE_MISSING:
            if ( itemValuesFound < itemsFound )
            {
                return null;
            }
            break;

        case SKIP_IF_ALL_VALUES_MISSING:
            if ( itemsFound != 0 && itemValuesFound == 0 )
            {
                return null;
            }
            break;

        case NEVER_SKIP:
            break;
        }

        if ( value == null && state.isReplaceNulls() )
        {
            switch ( params.getDataType() )
            {
            case NUMERIC:
                return 0d;

            case BOOLEAN:
                return FALSE;

            case TEXT:
                return "";
            }
        }

        return value;
    }

    // -------------------------------------------------------------------------
    // Create a new CommonExpressionVisitor
    // -------------------------------------------------------------------------

    @Override
    public Map<String, Constant> getConstantMap()
    {
        return constantMapCache.get( "x", key -> constantService.getConstantMap() );
    }

    // -------------------------------------------------------------------------
    // Supportive methods
    // -------------------------------------------------------------------------

    /**
     * Returns the OrgUnitGroupCountIds from an expression
     */
    private Set<String> getOrgUnitGroupCountIds( String expression )
    {
        if ( expression == null )
        {
            return Collections.emptySet();
        }
        try
        {
            ExpressionInfo info = getExpressionInfo( ExpressionParams.builder()
                .expression( expression )
                .parseType( INDICATOR_EXPRESSION )
                .build() );

            return info.getOrgUnitGroupCountIds();
        }
        catch ( ParserException e )
        {
            log.warn( "Parsing error in indicator expression " + expression );

            return Collections.emptySet();
        }
    }

    /**
     * Returns all non-aggregated and all aggregated dimensional item object ids
     * in the given expression
     */
    private void getExpressionDimensionalItemIds( String expression, ParseType parseType,
        Set<DimensionalItemId> itemIds,
        Set<DimensionalItemId> sampleItemIds )
    {
        if ( isEmpty( expression ) )
        {
            return;
        }

        ExpressionInfo info = getExpressionInfo( ExpressionParams.builder()
            .expression( expression )
            .parseType( parseType )
            .build() );

        itemIds.addAll( info.getItemIds() );
        sampleItemIds.addAll( info.getSampleItemIds() );
    }

    private <T extends IdentifiableObject> Map<String, T> getUidMap( Class<T> type, Collection<String> uids )
    {
        List<T> objects = idObjectManager.getNoAcl( type, uids );

        return IdentifiableObjectUtils.getIdMap( objects, IdScheme.UID );
    }

    /**
     * Creates a new {@see CommonExpressionVisitor}
     */
    private CommonExpressionVisitor newVisitor( ExpressionItemMethod itemMethod, ExpressionParams params )
    {
        return CommonExpressionVisitor.builder()
            .idObjectManager( idObjectManager )
            .dimensionService( dimensionService )
            .statementBuilder( statementBuilder )
            .i18n( i18nManager.getI18n() )
            .constantMap( getConstantMap() )
            .itemMap( PARSE_TYPE_EXPRESSION_ITEMS.get( params.getParseType() ) )
            .itemMethod( itemMethod )
            .params( params )
            .info( params.getExpressionInfo() )
            .build();
    }

    /**
     * Visits an expression and returns the expected expression type.
     */
    private Object visit( String expression, DataType dataType, CommonExpressionVisitor visitor, boolean logWarnings )
    {
        try
        {
            Object result = Parser.visit( expression, visitor );

            switch ( dataType )
            {
            case NUMERIC:
                return castDouble( result );

            case BOOLEAN:
                return castBoolean( result );

            case TEXT:
                return castString( result );
            }
        }
        catch ( ParserException ex )
        {
            String message = ex.getMessage() + " parsing expression '" + expression + "'";

            if ( logWarnings )
            {
                log.warn( message );
            }
            else
            {
                throw new ParserException( message );
            }
        }

        return DOUBLE_VALUE_IF_NULL;
    }

    /**
     * Regenerates an expression from the parse tree, with values substituted
     * for constants and orgUnitCounts.
     */
    private String regenerateIndicatorExpression( String expression,
        Map<String, Constant> constants, Map<String, OrganisationUnitGroup> orgUnitGroups )
    {
        if ( expression == null || expression.isEmpty() )
        {
            return null;
        }

        // ---------------------------------------------------------------------
        // Constants
        // ---------------------------------------------------------------------

        StringBuffer sb = new StringBuffer();
        Matcher matcher = CONSTANT_PATTERN.matcher( expression );

        while ( matcher.find() )
        {
            String co = matcher.group( GROUP_ID );

            Constant constant = constants.get( co );

            String replacement = constant != null ? String.valueOf( constant.getValue() ) : NULL_REPLACEMENT;

            matcher.appendReplacement( sb, Matcher.quoteReplacement( replacement ) );
        }

        expression = TextUtils.appendTail( matcher, sb );

        // ---------------------------------------------------------------------
        // Org unit groups
        // ---------------------------------------------------------------------

        sb = new StringBuffer();
        matcher = OU_GROUP_PATTERN.matcher( expression );

        while ( matcher.find() )
        {
            String oug = matcher.group( GROUP_ID );

            OrganisationUnitGroup group = orgUnitGroups.get( oug );

            String replacement = group != null ? String.valueOf( group.getMembers().size() ) : NULL_REPLACEMENT;

            matcher.appendReplacement( sb, replacement );

            // TODO sub tree
        }

        return TextUtils.appendTail( matcher, sb );
    }

    /**
     * Finds the total number of days in a list of periods.
     */
    private int getDaysFromPeriods( List<Period> periods )
    {
        return periods.stream()
            .filter( Objects::nonNull )
            .mapToInt( Period::getDaysInPeriod ).sum();
    }
}


text:
.class public Lcom/samsung/android/content/smartclip/SemSmartClipViewHelper;
.super Ljava/lang/Object;
.source "SemSmartClipViewHelper.java"

# static fields
.field private static final TAG:Ljava/lang/String; = "SemSmartClipViewHelper"

# direct methods
.method public constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static addMetaTag(Landroid/view/View;Lcom/samsung/android/content/smartclip/SemSmartClipMetaTag;)Z
    .locals 4

    const/4 v3, 0x0

    if-eqz p0, :cond_0

    if-nez p1, :cond_1

    :cond_0
    const-string/jumbo v1, "SemSmartClipViewHelper"

    const-string/jumbo v2, "addMetaTag : Have null parameter"

    invoke-static {v1, v2}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    return v3

    :cond_1
    invoke-virtual {p1}, Lcom/samsung/android/content/smartclip/SemSmartClipMetaTag;->getType()Ljava/lang/String;

    move-result-object v1

    if-eqz v1, :cond_0

    invoke-static {p1}, Lcom/samsung/android/content/smartclip/SmartClipUtils;->isValidMetaTag(Lcom/samsung/android/content/smartclip/SemSmartClipMetaTag;)Z

    move-result v1

    if-eqz v1, :cond_3

    invoke-virtual {p0}, Landroid/view/View;->semGetSmartClipTags()Lcom/samsung/android/content/smartclip/SemSmartClipMetaTagArray;

    move-result-object v0

    if-nez v0, :cond_2

    new-instance v0, Lcom/samsung/android/content/smartclip/SmartClipMetaTagArrayImpl;

    invoke-direct {v0}, Lcom/samsung/android/content/smartclip/SmartClipMetaTagArrayImpl;-><init>()V

    invoke-virtual {p0, v0}, Landroid/view/View;->semSetSmartClipTags(Lcom/samsung/android/content/smartclip/SemSmartClipMetaTagArray;)Z

    :cond_2
    invoke-virtual {v0, p1}, Lcom/samsung/android/content/smartclip/SemSmartClipMetaTagArray;->add(Ljava/lang/Object;)Z

    const/4 v1, 0x1

    return v1

    :cond_3
    const-string/jumbo v1, "SemSmartClipViewHelper"

    const-string/jumbo v2, "addMetaTag : Invalid metatag"

    invoke-static {v1, v2}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    return v3
.end method

.method public static clearAllMetaTags(Landroid/view/View;)Z
    .locals 1

    const/4 v0, 0x0

    if-nez p0, :cond_0

    const/4 v0, 0x0

    return v0

    :cond_0
    invoke-virtual {p0, v0}, Landroid/view/View;->semSetSmartClipTags(Lcom/samsung/android/content/smartclip/SemSmartClipMetaTagArray;)Z

    move-result v0

    return v0
.end method

.method public static extractDefaultSmartClipData(Landroid/view/View;Lcom/samsung/android/content/smartclip/SemSmartClipCroppedArea;Lcom/samsung/android/content/smartclip/SemSmartClipDataElement;)I
    .locals 3

    const/4 v2, 0x0

    if-nez p0, :cond_0

    const-string/jumbo v0, "SemSmartClipViewHelper"

    const-string/jumbo v1, "extractDefaultSmartClipData : The view is null!"

    invoke-static {v0, v1}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    return v2

    :cond_0
    if-nez p2, :cond_1

    const-string/jumbo v0, "SemSmartClipViewHelper"

    const-string/jumbo v1, "extractDefaultSmartClipData : The result element is null!"

    invoke-static {v0, v1}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    return v2

    :cond_1
    if-nez p1, :cond_2

    const-string/jumbo v0, "SemSmartClipViewHelper"

    const-string/jumbo v1, "extractDefaultSmartClipData : The cropped area is null!"

    invoke-static {v0, v1}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    return v2

    :cond_2
    invoke-virtual {p0, p1, p2}, Landroid/view/View;->semExtractSmartClipData(Lcom/samsung/android/content/smartclip/SemSmartClipCroppedArea;Lcom/samsung/android/content/smartclip/SemSmartClipDataElement;)I

    move-result v0

    return v0
.end method

.method public static getMetaTags(Landroid/view/View;)Lcom/samsung/android/content/smartclip/SemSmartClipMetaTagArray;
    .locals 1

    const/4 v0, 0x0

    if-nez p0, :cond_0

    return-object v0

    :cond_0
    invoke-virtual {p0}, Landroid/view/View;->semGetSmartClipTags()Lcom/samsung/android/content/smartclip/SemSmartClipMetaTagArray;

    move-result-object v0

    return-object v0
.end method

.method public static removeMetaTag(Landroid/view/View;Ljava/lang/String;)I
    .locals 2

    const/4 v1, 0x0

    if-eqz p0, :cond_0

    if-nez p1, :cond_1

    :cond_0
    return v1

    :cond_1
    invoke-virtual {p0}, Landroid/view/View;->semGetSmartClipTags()Lcom/samsung/android/content/smartclip/SemSmartClipMetaTagArray;

    move-result-object v0

    if-eqz v0, :cond_2

    if-nez p1, :cond_3

    :cond_2
    return v1

    :cond_3
    invoke-virtual {v0, p1}, Lcom/samsung/android/content/smartclip/SemSmartClipMetaTagArray;->removeMetaTags(Ljava/lang/String;)I

    move-result v1

    return v1
.end method

.method public static setDataExtractionListener(Landroid/view/View;Lcom/samsung/android/content/smartclip/SemSmartClipDataExtractionListener;)Z
    .locals 1

    if-nez p0, :cond_0

    const/4 v0, 0x0

    return v0

    :cond_0
    invoke-virtual {p0, p1}, Landroid/view/View;->semSetSmartClipDataExtractionListener(Lcom/samsung/android/content/smartclip/SemSmartClipDataExtractionListener;)Z

    const/4 v0, 0x1

    return v0
.end method

.method public static setMetaTags(Landroid/view/View;Lcom/samsung/android/content/smartclip/SemSmartClipMetaTagArray;)Z
    .locals 1

    if-eqz p0, :cond_0

    if-nez p1, :cond_1

    :cond_0
    const/4 v0, 0x0

    return v0

    :cond_1
    invoke-virtual {p0, p1}, Landroid/view/View;->semSetSmartClipTags(Lcom/samsung/android/content/smartclip/SemSmartClipMetaTagArray;)Z

    const/4 v0, 0x1

    return v0
.end method


text:
require 'set'
require 'socket'
require 'yaml'

class Cassandra
  attr_reader :data_path, :cluster_name, :node_name

  def initialize(config_file, disk_threshold, logger)
    @logger = logger

    read_config_file(config_file)

    @node_name = Socket.gethostname

    @logger.info("Cassandra cluster name = #{@cluster_name}")
    @logger.info("Cassandra node name = #{@node_name}")
    @logger.info("Cassandra data path = #{@data_path}")

    @disk_threshold = disk_threshold
  end

  def read_config_file(config_file)
    config = YAML.load_file(config_file)
    if config.include? 'cluster_name'
      @cluster_name = config['cluster_name'].tr(' ', '_')
    else
      @logger.warn("Could not found cluster name in Cassandra config file #{@config_file}")
      @cluster_name = 'noname_cassandra_cluster'
    end
    if config.include? 'data_file_directories'
      if config['data_file_directories'].length == 1
        @data_path = config['data_file_directories'][0]
      else
        # TODO : manage multiple data directories
        raise('This backup tool does not currently work with multiple data directories')
      end
    else
      raise('Not data directory defined in config file')
    end
  rescue Exception => e
    raise("Could not parse Cassandra config file #{config_file} (#{e.message})")
  end

  private :read_config_file

  def nodetool_snapshot(name)
    # First delete the snapshot if it exists.
    nodetool_clearsnapshot(name)

    # Check if we have enough disk space left
    m = /\ ([0-9]+)%\ /.match(IO.popen("df #{@data_path}").readlines[1])
    used = Integer(m[1])
    if used > @disk_threshold
      raise("Not enough disk space remaining for snapshot (#{used}% used > #{@disk_threshold}% required)")
    end

    # Then trigger it.
    @logger.debug("Starting a new Cassandra snapshot #{name}")
    begin
      success = system('nodetool', 'snapshot', '-t', name)
      if success
        @logger.debug('Cassandra Snapshot successful')
      else
        raise
      end
    rescue Exception => e
      raise("Error while snapshot command (#{e.message})")
    end
  end

  private :nodetool_snapshot

  def nodetool_clearsnapshot(name)
    @logger.debug("Deleting snapshot #{name} in Cassandra")
    begin
      success = system('nodetool', 'clearsnapshot', '-t', name)
      if success
        @logger.debug('Cassandra Snapshot deletion successful')
      else
        raise
      end
    rescue Exception => e
      raise("Error while clearsnapshot command (#{e.message})")
    end
  end

  private :nodetool_clearsnapshot

  def get_keyspaces_and_tables
    result = {}
    Dir.foreach(@data_path) do |keyspace|
      next if keyspace == '.' || keyspace == '..' || !Dir.exist?(@data_path + '/' + keyspace)
      result[keyspace] = []
      Dir.foreach(@data_path + '/' + keyspace) do |table|
        next if table == '.' || table == '..'
        result[keyspace].push(table)
      end
    end
    result
  end

  private :get_keyspaces_and_tables

  def build_metadata(name)
    result = Set.new
    ks = get_keyspaces_and_tables
    ks.each do |keyspace, tables|
      tables.each do |table|
        snapdir = @data_path + '/' + keyspace + '/' + table + '/snapshots/' + name
        next unless Dir.exist?(snapdir)
        Dir.foreach(snapdir) do |filename|
          next if filename == '.' || filename == '..'
          result.add(keyspace + '/' + table + '/snapshots/' + name + '/' + filename)
        end
      end
    end
    result
  end

  private :build_metadata

  def new_snapshot
    today = Time.new.strftime('%Y_%m_%d')
    snapname = 'cass_snap'

    nodetool_snapshot(snapname)
    metadata = build_metadata(snapname)

    CassandraSnapshot.new(@cluster_name, @node_name, today, metadata)
  end

  def delete_snapshot(_snapshot)
    snapname = 'cass_snap'
    nodetool_clearsnapshot(snapname)
  end
end

class CassandraSnapshot
  attr_reader :cluster, :node, :date, :metadata

  def initialize(cluster, node, date, metadata = nil)
    @cluster = cluster
    @node = node
    @date = date
    @metadata = if metadata.nil?
                  Set.new
                else
                  metadata
    end
  end

  def to_s
    "[#{@cluster}|#{@node}|#{@date}]"
  end

  def ==(other)
    @cluster == other.cluster && @node == other.node && @date == other.date
  end

  def <=>(other)
    c = @cluster <=> other.cluster
    n = @node <=> other.node
    d = @date <=> other.date
    c * 3 + n * 2 + d
  end

  def get_date
    DateTime.strptime(@date, '%Y_%m_%d')
  end
end

class BackupFlag
  attr_reader :cluster, :date, :file

  def initialize(cluster, file)
    @cluster = cluster
    @file = file.dup
    date_as_string = file.sub! 'BACKUP_COMPLETED_', ''
    @date = DateTime.strptime(date_as_string, '%Y_%m_%d')
  end
end


text:
using System.Net;

namespace NanoByte.Common.Tasks;

/// <summary>
/// Contains test methods for <see cref="ForEachTask{T}"/>.
/// </summary>
public class ForEachTaskTest
{
    [Fact]
    public void TestCallback()
    {
        var target = new[] {"element1", "element2", "element2"};
        var calledFor = new List<string>();

        var task = new ForEachTask<string>("Test task", target, calledFor.Add);
        task.Run();

        calledFor.Should().Equal(target);
    }

    [Fact]
    public void TestExceptionPassing()
    {
        new ForEachTask<string>("Test task", new[] {""}, delegate { throw new IOException("Test exception"); })
           .Invoking(x => x.Run())
           .Should().Throw<IOException>();
        new ForEachTask<string>("Test task", new[] {""}, delegate { throw new WebException("Test exception"); })
           .Invoking(x => x.Run())
           .Should().Throw<WebException>();
    }
}


text:
using System;
using System.Runtime.Serialization;
using Elasticsearch.Net.Serialization;
using FluentAssertions;

namespace Serilog.Sinks.Elasticsearch.Tests.Discrepancies
{
    public class ElasticsearchSinkUniformityTestsBase : ElasticsearchSinkTestsBase
    {
        public ElasticsearchSinkUniformityTestsBase(IElasticsearchSerializer serializer)
        {
            _options.Serializer = serializer;
        }

        public void ThrowAndLogAndCatchBulkOutput(string exceptionMessage)
        {
            var loggerConfig = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .Enrich.WithMachineName()
                .WriteTo.ColoredConsole()
                .WriteTo.Elasticsearch(_options);

            var logger = loggerConfig.CreateLogger();
            using (logger as IDisposable)
            {
                try
                {
                    try
                    {
                        throw new Exception("inner most exception");
                    }
                    catch (Exception e)
                    {
                        var innerException = new NastyException("nasty inner exception", e);
                        throw new Exception(exceptionMessage, innerException);
                    }
                }
                catch (Exception e)
                {
                    logger.Error(e, "Test exception. Should contain an embedded exception object.");
                }
                logger.Error("Test exception. Should not contain an embedded exception object.");
            }

            var postedEvents = this.GetPostedLogEvents(expectedCount: 2);
            Console.WriteLine("BULK OUTPUT BEGIN ==========");
            foreach (var post in _seenHttpPosts)
                Console.WriteLine(post);
            Console.WriteLine("BULK OUTPUT END ============");

            var firstEvent = postedEvents[0];
            firstEvent.Exceptions.Should().NotBeNull().And.HaveCount(3);
            firstEvent.Exceptions[0].Message.Should().NotBeNullOrWhiteSpace()
                .And.Be(exceptionMessage);
            var realException = firstEvent.Exceptions[0];
            realException.ExceptionMethod.Should().NotBeNull();
            realException.ExceptionMethod.Name.Should().NotBeNullOrWhiteSpace();
            realException.ExceptionMethod.AssemblyName.Should().NotBeNullOrWhiteSpace();
            realException.ExceptionMethod.AssemblyVersion.Should().NotBeNullOrWhiteSpace();
            realException.ExceptionMethod.ClassName.Should().NotBeNullOrWhiteSpace();
            realException.ExceptionMethod.Signature.Should().NotBeNullOrWhiteSpace();
            realException.ExceptionMethod.MemberType.Should().BeGreaterThan(0);

            var nastyException = firstEvent.Exceptions[1];
            nastyException.Depth.Should().Be(1);
            nastyException.Message.Should().Be("nasty inner exception");
            nastyException.HelpUrl.Should().Be("help url");
            nastyException.StackTraceString.Should().Be("stack trace string");
            nastyException.RemoteStackTraceString.Should().Be("remote stack trace string");
            nastyException.RemoteStackIndex.Should().Be(1);
            nastyException.HResult.Should().Be(123123);
            nastyException.Source.Should().Be("source");
            nastyException.ClassName.Should().Be("classname nasty exception");
            //nastyException.WatsonBuckets.Should().BeEquivalentTo(new byte[] {1,2,3});

            var secondEvent = postedEvents[1];
            secondEvent.Exceptions.Should().BeNullOrEmpty();
        }
    }

    /// <summary>
    /// Exception that forces often empty serializationinfo values to have a value
    /// </summary>
    public class NastyException : Exception
    {
        public NastyException(string message) : base(message) { }
        public NastyException(string message, Exception innerException) : base(message, innerException) { }

        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Message", this.Message);
            info.AddValue("HelpURL", "help url");
            info.AddValue("StackTraceString", "stack trace string");
            info.AddValue("RemoteStackTraceString", "remote stack trace string");
            info.AddValue("RemoteStackIndex", 1);
            info.AddValue("ExceptionMethod", "exception method");
            info.AddValue("HResult", 123123);
            info.AddValue("Source", "source");
            info.AddValue("ClassName", "classname nasty exception");
            info.AddValue("WatsonBuckets", new byte[] { 1, 2, 3 }, typeof(byte[]));
        }
    }
}


text:
cask :v1 => 'phoenix-slides' do
  version '1.3.1'
  sha256 '6e5df9e586bb33b79249d9917f99f50395f255b85bf39c5fafca64fe66aef758'

  url "http://blyt.net/phxslides/phoenix-slides-#{version.gsub('.','')}.zip"
  name 'Phoenix Slides'
  homepage 'http://blyt.net/phxslides'
  license :unknown    # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder

  app 'Phoenix Slides.app'
end


text:
package io.reneses.tela.core.sessions;

import io.reneses.tela.TestUtils;
import io.reneses.tela.core.sessions.exceptions.ModuleTokenNotFoundException;
import io.reneses.tela.core.sessions.exceptions.SessionNotFoundException;
import io.reneses.tela.core.sessions.models.Session;
import org.junit.*;

import static org.junit.Assert.*;

public class SessionManagerImplTest {

    SessionManager sessionManager;

    @Before
    public void setUp() throws Exception {
        sessionManager = TestUtils.configureSessionManager();
    }

    @After
    public void tearDown() throws Exception {
        TestUtils.destroyDatabase();
    }

    @Test
    public void create() throws Exception {
        Session session = sessionManager.create();
        assertTrue(sessionManager.existsByAccessToken(session.getAccessToken()));
        assertNotNull(sessionManager.findByAccessToken(session.getAccessToken()));
    }

    @Test
    public void createWithModuleToken() throws Exception {
        sessionManager.createWithModuleToken("test", "1");
        assertNotNull(sessionManager.findByModuleToken("test", "1"));
    }

    @Test(expected = IllegalArgumentException.class)
    public void createWithModuleTokenNullToken() throws Exception {
        sessionManager.createWithModuleToken("test", null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void createWithModuleTokenNullModule() throws Exception {
        sessionManager.createWithModuleToken(null, "1");
    }

    @Test
    public void existsByAccessToken() throws Exception {
        assertFalse(sessionManager.existsByAccessToken(new Session().getAccessToken()));
        Session session = sessionManager.create();
        assertTrue(sessionManager.existsByAccessToken(session.getAccessToken()));
    }

    @Test
    public void existsByAccessTokenWithNull() throws Exception {
        assertFalse(sessionManager.existsByAccessToken(null));
    }

    @Test
    public void delete() throws Exception {
        Session session = sessionManager.create();
        sessionManager.delete(session);
        assertFalse(sessionManager.existsByAccessToken(session.getAccessToken()));
    }

    @Test
    public void deleteWithToken() throws Exception {
        Session session = sessionManager.createWithModuleToken("test", "1");
        sessionManager.delete(session);
        assertFalse(sessionManager.existsByAccessToken(session.getAccessToken()));
        assertNull(sessionManager.findByModuleToken("test", "1"));
    }

    @Test
    public void getModuleToken() throws Exception {
        Session session = sessionManager.createWithModuleToken("test", "1");
        String token = sessionManager.getModuleToken(session, "test");
        assertEquals("1", token);
    }

    @Test(expected = SessionNotFoundException.class)
    public void getModuleTokenNotExistingSession() throws Exception {
        sessionManager.getModuleToken(new Session(), "test");
    }

    @Test(expected = ModuleTokenNotFoundException.class)
    public void getModuleTokenNotExistingToken() throws Exception {
        Session session = sessionManager.create();
        sessionManager.getModuleToken(session, "test");
    }

    @Test(expected = SessionNotFoundException.class)
    public void getModuleTokenAfterDeleteSession() throws Exception {
        Session session = sessionManager.createWithModuleToken("test", "1");
        sessionManager.delete(session);
        sessionManager.getModuleToken(session, "test");
    }

    @Test
    public void deleteModuleToken() throws Exception {
        Session session = sessionManager.createWithModuleToken("test", "1");
        assertTrue(sessionManager.deleteModuleToken(session, "test"));
        assertTrue(sessionManager.existsByAccessToken(session.getAccessToken()));
    }

    @Test
    public void deleteModuleTokenNotSessionFound() throws Exception {
        assertFalse(sessionManager.deleteModuleToken(new Session(), "test"));
    }

    @Test
    public void deleteModuleTokenNotExisting() throws Exception {
        Session session = sessionManager.create();
        assertFalse(sessionManager.deleteModuleToken(session, "test"));
    }

    @Test
    public void deleteModuleTokenWithOtherTokens() throws Exception {
        Session session = sessionManager.create();
        sessionManager.addModuleToken(session, "test", "1");
        sessionManager.addModuleToken(session, "test2", "2");
        sessionManager.deleteModuleToken(session, "test");
        assertTrue(sessionManager.existsByAccessToken(session.getAccessToken()));
        assertEquals("2", sessionManager.getModuleToken(session, "test2"));
    }

    @Test
    public void findByModuleByToken() throws Exception {
        Session session = sessionManager.createWithModuleToken("test", "1");
        Session retrieved = sessionManager.findByModuleToken("test", "1");
        assertEquals(session.getId(), retrieved.getId());
    }

    @Test
    public void findByModuleByTokenNotExisting() throws Exception {
        assertNull(sessionManager.findByModuleToken("test", "1"));
    }

    @Test
    public void deleteByModuleToken() throws Exception {
        Session session = sessionManager.createWithModuleToken("test", "1");
        assertTrue(sessionManager.deleteByModuleToken("test", "1"));
        assertFalse(sessionManager.existsByAccessToken(session.getAccessToken()));
    }

    @Test
    public void deleteByModuleTokenNotExistingToken() throws Exception {
        assertFalse(sessionManager.deleteByModuleToken("test", "1"));
    }

    @Test
    public void deleteByModuleTokenOtherTokens() throws Exception {
        Session session = sessionManager.createWithModuleToken("test", "1");
        sessionManager.addModuleToken(session, "test2", "2");
        assertTrue(sessionManager.deleteByModuleToken("test", "1"));
        assertFalse(sessionManager.existsByAccessToken(session.getAccessToken()));
    }

    @Test(expected = SessionNotFoundException.class)
    public void addTokenSessionNotExisting() throws Exception {
        sessionManager.addModuleToken(new Session(), "test", "2");
    }

    @Test
    public void addTokenSession() throws Exception {
        Session session = sessionManager.create();
        sessionManager.addModuleToken(session, "test", "2");
        assertEquals("2", sessionManager.getModuleToken(session, "test"));
        assertEquals(session, sessionManager.findByModuleToken("test", "2"));
    }

    @Test
    public void addTokenAlreadyExisting() throws Exception {
        Session s1 = sessionManager.createWithModuleToken("test", "1");
        Session s2 = sessionManager.create();
        sessionManager.addModuleToken(s2, "test", "1");
        assertTrue(sessionManager.existsByAccessToken(s1.getAccessToken()));
        try {
            sessionManager.getModuleToken(s1, "test");
            Assert.fail();
        } catch (ModuleTokenNotFoundException ignored) {
        }
        assertEquals("1", sessionManager.getModuleToken(s2, "test"));
        assertEquals(s2, sessionManager.findByModuleToken("test", "1"));
    }

}